<?php

/**
 * Create Layout Component Tool
 * Allows the AI to create new reusable layout components
 */

if (!$app->module('layout')) {
    return false;
}

return [
    'name' => 'createLayoutComponent',
    'description' => 'Create a new layout component definition.',
    'parameters' => [
        'type' => 'object',
        'properties' => [
            'name' => [
                'type' => 'string',
                'description' => 'Unique component name (alphanumeric only, no spaces).'
            ],
            'label' => [
                'type' => 'string',
                'description' => 'Human-readable label for the component.'
            ],
            'group' => [
                'type' => 'string',
                'description' => 'Component group (e.g., "Custom", "Marketing").'
            ],
            'type' => [
                'type' => 'string',
                'description' => 'Component behavior type.',
                'enum' => ['standard', 'grid', 'row'],
                'default' => 'standard'
            ],
            'children' => [
                'type' => 'boolean',
                'description' => 'Whether the component allows nested child components (only for standard type).',
                'default' => false
            ],
            'allowedComponents' => [
                'type' => 'array',
                'description' => 'List of allowed child component names (if children is true). Leave empty for all.',
                'items' => ['type' => 'string']
            ],
            'icon' => [
                'type' => 'string',
                'description' => 'Icon path (e.g., "layout:assets/icons/component.svg").'
            ],
            'image' => [
                'type' => 'string',
                'description' => 'URL or path to a preview image for the component.'
            ],
            'html' => [
                'type' => 'string',
                'description' => 'Vue-compatible HTML template for the component. Use {{ data.fieldname }} to access field values.'
            ],
            'css' => [
                'type' => 'string',
                'description' => 'CSS styles for the component.'
            ],
            'js' => [
                'type' => 'string',
                'description' => 'JavaScript logic for the component.'
            ],
            'fields' => [
                'type' => 'array',
                'description' => 'List of configurable fields. Infer "type" and "multiple" from the name (e.g. "slides" -> set + multiple).',
                'items' => [
                    'type' => 'object',
                    'properties' => [
                        'name' => [
                            'type' => 'string',
                            'description' => 'Field name.'
                        ],
                        'type' => [
                            'type' => 'string',
                            'description' => 'Field type.',
                            'enum' => [
                                'text', 'boolean', 'code', 'color', 'date', 'datetime',
                                'nav', 'number', 'object', 'select', 'set', 'table',
                                'tags', 'time', 'wysiwyg', 'asset', 'contentItemLink', 'layout',
                                'component', 'pageUrl', 'seo'
                            ],
                            'default' => 'text'
                        ],
                        'label' => [
                            'type' => 'string',
                            'description' => 'Field label.'
                        ],
                        'options' => [
                            'description' => 'Specific options for the field type. Examples:
- set: {"fields": [{"name": "subfield", "type": "text"}], "display": "${data.fieldname}"}
- select: {"options": ["Option A", "Option B"]}
- table: {"columns": [{"name": "col1"}, {"name": "col2"}]}
- asset: {"filter": "{\"type\": \"image\"}"}
- contentItemLink: {"link": "model_name", "display": "${data.title}"}
- layout: {"allowedComponents": ["image", "text", "section", "grid"]}
- code: {"mode": "html", "height": 200}
- text: {"multiline": true, "showCount": true, "maxlength": 140}
- gallery: use "asset" type with "multiple": true'
                        ],
                        'required' => [
                            'type' => 'boolean',
                            'default' => false
                        ],
                        'multiple' => [
                            'type' => 'boolean',
                            'description' => 'Set to TRUE if the field implies a list (e.g., "slides", "gallery").',
                            'default' => false
                        ],
                        'i18n' => [
                            'type' => 'boolean',
                            'description' => 'Whether the field can be localized.',
                            'default' => false
                        ],
                        'condition' => [
                            'type' => 'string',
                            'description' => 'Conditional logic to show/hide the field.'
                        ]
                    ],
                    'required' => ['name', 'type']
                ]
            ]
        ],
        'required' => ['name', 'html'],
        'additionalProperties' => false
    ],
    'handler' => function($args, $app) {

        $name = $args['name'];

        // Sanitize name
        $name = preg_replace('/[^a-zA-Z0-9]/', '', $name);

        if (!$name) {
            return ['error' => 'Invalid component name.'];
        }

        // Check if exists
        $existing = $app->dataStorage->findOne('layout/components', ['name' => $name]);
        if ($existing) {
            return ['error' => "Layout component '{$name}' already exists."];
        }

        // Process fields (similar to createContentModel)
        $fields = $args['fields'] ?? [];
        $formattedFields = [];

        if (!empty($fields)) {
            foreach ($fields as $field) {
                // Ensure options is an array
                if (isset($field['options']) && !is_array($field['options'])) {
                    $field['options'] = [];
                }

                $formattedFields[] = array_merge([
                    'type' => 'text',
                    'label' => $field['name'],
                    'options' => [],
                    'required' => false,
                    'multiple' => false,
                    'i18n' => false,
                    'condition' => $field['condition'] ?? ''
                ], $field);
            }
        }

        // Map 'standard' type to null as per component.php logic, or keep as string if valid
        $type = $args['type'] ?? 'standard';
        $componentType = ($type === 'standard') ? null : $type;

        $component = [
            'name' => $name,
            'meta' => [
                'label' => $args['label'] ?? $name,
                'group' => $args['group'] ?? 'Custom',
                'info'  => $args['info'] ?? '',
                'icon'  => $args['icon'] ?? 'layout:assets/icons/component.svg',
                'image' => $args['image'] ?? '',
                'type'  => $componentType,
                'preview' => $args['html'], // HTML is stored as preview template
                'fields' => $formattedFields,
                'children' => $args['children'] ?? false,
                'allowedComponents' => $args['allowedComponents'] ?? [],
                'opts' => [
                    'css' => $args['css'] ?? '',
                    'js' => $args['js'] ?? ''
                ]
            ],
            '_created' => time(),
            '_modified' => time()
        ];

        try {
            // Save to storage
            $app->dataStorage->save('layout/components', $component);

            // Trigger cache update
            $app->helper('layoutComponents')->cache();

            return [
                'success' => true,
                'message' => "Layout component '{$name}' created successfully.",
                'component' => [
                    'name' => $name,
                    'label' => $component['meta']['label'],
                    'fields_count' => count($formattedFields)
                ]
            ];

        } catch (\Throwable $e) {
            return ['error' => "Exception occurred: " . $e->getMessage()];
        }
    },
    'options' => [
        'permission' => 'layout/components/manage'
    ]
];
