<?php
declare(strict_types=1);
if (!defined('ABSPATH')) { exit; }

wp_register_ability('tpaep/tpaep-advanced-typography', [
'label' => __('Advanced Typography', 'theplus'),
    'description' => __('Adds The Plus "Advanced Typography" widget (tp-advanced-typography) to an Elementor container with Marquee and Reveal effects.', 'theplus'),
    'category' => 'tpae',
    'input_schema' => ['type' => 'object', 'properties' => [
        'post_id'               => ['type' => 'integer', 'description' => 'Elementor page/post ID'],
        'parent_id'             => ['type' => 'string',  'description' => 'Target Elementor container ID'],
        'position'              => ['type' => 'integer', 'description' => 'Insert position (-1 = append)', 'default' => -1],
        'typography_listing'    => ['type' => 'string',  'enum' => ['default', 'listing'], 'description' => 'Layout mode', 'default' => 'default'],
        'advanced_typography_text' => ['type' => 'string', 'description' => 'Primary text (default mode)'],
        'span_replace_tag'         => ['type' => 'string', 'description' => 'HTML Tag (h1-h6, div, span, p)', 'default' => 'span'],
        'text_align'               => ['type' => 'string', 'enum' => ['left', 'center', 'right', 'justify'], 'description' => 'Global text align', 'default' => 'center'],
        'text_write_mode'          => ['type' => 'string', 'enum' => ['unset', 'vertical-lr', 'vertical-rl'], 'description' => 'Vertical Text', 'default' => 'unset'],
        'text_orientation'         => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Vertical Letters'],
        'text_direction_ltr'       => ['type' => 'string', 'enum' => ['initial', 'ltr', 'rtl'], 'description' => 'Vertical Direction', 'default' => 'initial'],
        'transform_css'            => ['type' => 'string', 'description' => 'Transform CSS (e.g. rotate(10deg))'],
        'transform_css_hover'      => ['type' => 'string', 'description' => 'Transform CSS Hover'],
        'transform_origin_css'     => ['type' => 'string', 'description' => 'Transform Origin', 'default' => 'center'],
        'stroke_switch'            => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Enable Stroke/Fill'],
        'circular_text_switch'     => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Enable Circular Text'],
        'circular_text_custom'     => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Custom Radius for Circular'],
        'circular_radious'         => ['type' => 'integer', 'description' => 'Circular Radius (px)'],
        'circular_text_reversed'   => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Reverse Circular Direction'],
        'background_based_text_switch' => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Background Blend Mode'],
        'background_based_text_style'  => ['type' => 'string', 'description' => 'Blend Mode Variation'],
        'img_gif_ovly_txtimg_switch'   => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Knockout Text'],
        'on_hover_img_reveal_switch'   => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'On Hover Image Reveal'],
        'on_hover_img_source'          => ['type' => 'string', 'description' => 'Hover Image URL'],
        'adv_hover_img_reveal_style'   => ['type' => 'string', 'description' => 'Hover Reveal Style', 'default' => 'style-1'],
        'marquee_switch'               => ['type' => 'string', 'enum' => ['yes', 'no'], 'description' => 'Enable Marquee'],
        'marquee_type'                 => ['type' => 'string', 'enum' => ['default', 'on_transition'], 'default' => 'default'],
        'marquee_direction'            => ['type' => 'string', 'enum' => ['left', 'right', 'up', 'down'], 'default' => 'left'],
        'marquee_behavior'             => ['type' => 'string', 'enum' => ['initial', 'normal', 'alternate'], 'default' => 'initial'],
        'marquee_loop'                 => ['type' => 'integer', 'description' => '-1 for infinite', 'default' => -1],
        'marquee_scrollamount'         => ['type' => 'integer', 'description' => 'Marquee Speed', 'default' => 6],
        'listing_items'         => [
            'type' => 'array',
            'description' => 'Multiple text items for listing mode',
            'items' => [
                'type' => 'object',
                'properties' => [
                    'typo_text'      => ['type' => 'string', 'description' => 'Item text'],
                    'text_link'      => ['type' => 'string', 'description' => 'URL'],
                    'list_typo_stroke' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'bg_based_text_switch' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'bg_based_text_style' => ['type' => 'string'],
                    'img_gif_ovly_txtimg_switch' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'on_hover_img_reveal_switch' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'on_hover_img_source' => ['type' => 'string', 'description' => 'URL'],
                    'adv_hover_img_reveal_style' => ['type' => 'string'],
                    'marquee_switch' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'marquee_type' => ['type' => 'string'],
                    'marquee_direction' => ['type' => 'string'],
                    'marquee_behavior' => ['type' => 'string'],
                    'marquee_loop' => ['type' => 'integer'],
                    'marquee_scrollamount' => ['type' => 'integer'],
                    'loop_magic_scroll' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'plus_mouse_move_parallax' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'text_continuous_animation' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'text_animation_effect' => ['type' => 'string'],
                    'text_animation_hover' => ['type' => 'string', 'enum' => ['yes', 'no']],
                    'typo_underline_style' => ['type' => 'string'],
                    'typo_overlay_under_style' => ['type' => 'string'],
                    'typo_classic_under' => ['type' => 'string'],
                    'typo_classic_under_style' => ['type' => 'string'],
                    'transform_css' => ['type' => 'string'],
                    'transform_css_hover' => ['type' => 'string'],
                    'typo_advanced_style' => ['type' => 'string', 'enum' => ['yes', 'no']],
                ],
                'required' => ['typo_text']
            ]
        ],
        'settings'              => ['type' => 'object',  'description' => 'Raw Elementor control key/value pairs to merge.'],
    ], 'required' => ['post_id', 'parent_id'], 'additionalProperties' => false],
    'output_schema' => ['type' => 'object', 'properties' => [
        'element_id'  => ['type' => 'string'],
        'widget_type' => ['type' => 'string'],
        'post_id'     => ['type' => 'integer'],
    ]],
    'execute_callback'    => 'tpaep_mcp_theplus_advanced_typography_ability',
    'permission_callback' => 'tpaep_mcp_theplus_advanced_typography_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function tpaep_mcp_theplus_advanced_typography_permission(?array $input = null): bool {
    if (!current_user_can('edit_posts')) { return false; }
    $post_id = absint($input['post_id'] ?? 0);
    if ($post_id > 0 && !current_user_can('edit_post', $post_id)) { return false; }
    return true;
}

function tpaep_mcp_theplus_advanced_typography_ability(array $input) {
    if (!tpaep_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'theplus')); }
    $widget_type = 'tp-advanced-typography';
    if (!tpaep_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Advanced Typography widget is not registered.', 'theplus')); }
    $post_id   = absint($input['post_id'] ?? 0);
    $parent_id = sanitize_text_field((string)($input['parent_id'] ?? ''));
    $position  = intval($input['position'] ?? -1);
    if ($post_id <= 0 || $parent_id === '') { return new WP_Error('missing_params', __('post_id and parent_id are required.', 'theplus')); }
    $post = get_post($post_id);
    if (!$post instanceof WP_Post) { return new WP_Error('invalid_post', __('Target post was not found.', 'theplus')); }
    $page_data = tpaep_mcp_get_elementor_page_data($post_id);
    if (is_wp_error($page_data)) { return $page_data; }

    $settings = [
        'typography_listing' => sanitize_key($input['typography_listing'] ?? 'default'),
    ];

    $string_keys = [
        'advanced_typography_text', 'span_replace_tag', 'text_align', 'text_write_mode', 'text_orientation',
        'text_direction_ltr', 'transform_css', 'transform_css_hover', 'transform_origin_css',
        'stroke_switch', 'circular_text_switch', 'circular_text_custom', 'circular_text_reversed',
        'background_based_text_switch', 'background_based_text_style', 'img_gif_ovly_txtimg_switch',
        'on_hover_img_reveal_switch', 'adv_hover_img_reveal_style',
        'marquee_switch', 'marquee_type', 'marquee_direction', 'marquee_behavior'
    ];
    $number_keys = [
        'circular_radious', 'marquee_loop', 'marquee_scrollamount'
    ];

    foreach ($string_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = sanitize_text_field($input[$key]);
        }
    }
    foreach ($number_keys as $key) {
        if (isset($input[$key])) {
            $settings[$key] = intval($input[$key]);
        }
    }

    if (!empty($input['on_hover_img_source'])) {
        $settings['on_hover_img_source'] = ['url' => esc_url_raw($input['on_hover_img_source'])];
    }

    if (isset($input['circular_radious'])) {
        $settings['circular_radious'] = ['unit' => 'px', 'size' => intval($input['circular_radious'])];
    }

    // Handle old single_text backwards-compatibility securely
    if (isset($input['single_text']) && !isset($input['advanced_typography_text'])) {
        $settings['advanced_typography_text'] = sanitize_textarea_field($input['single_text']);
    } elseif (isset($input['advanced_typography_text'])) {
        $settings['advanced_typography_text'] = sanitize_textarea_field($input['advanced_typography_text']);
    }

    if (!empty($input['listing_items']) && is_array($input['listing_items'])) {
        $settings['listing_content'] = array_map(function($item) {
            $tab = [
                'typo_text' => sanitize_textarea_field((string)($item['typo_text'] ?? '')),
            ];

            $item_string_keys = [
                'list_typo_stroke', 'bg_based_text_switch', 'bg_based_text_style', 'img_gif_ovly_txtimg_switch', 'on_hover_img_reveal_switch',
                'adv_hover_img_reveal_style', 'marquee_switch', 'marquee_type', 'marquee_direction', 'marquee_behavior',
                'loop_magic_scroll', 'plus_mouse_move_parallax', 'text_continuous_animation', 'text_animation_effect', 'text_animation_hover',
                'typo_underline_style', 'typo_overlay_under_style', 'typo_classic_under', 'typo_classic_under_style',
                'transform_css', 'transform_css_hover', 'typo_advanced_style'
            ];
            $item_number_keys = [
                'marquee_loop', 'marquee_scrollamount'
            ];

            foreach ($item_string_keys as $key) {
                if (isset($item[$key])) {
                    $tab[$key] = sanitize_text_field((string)$item[$key]);
                }
            }
            foreach ($item_number_keys as $key) {
                if (isset($item[$key])) {
                    $tab[$key] = intval($item[$key]);
                }
            }

            if (!empty($item['text_link'])) {
                $tab['text_link'] = ['url' => esc_url_raw($item['text_link'])];
            }
            if (!empty($item['on_hover_img_source'])) {
                $tab['on_hover_img_source'] = ['url' => esc_url_raw($item['on_hover_img_source'])];
            }
            
            return $tab;
        }, $input['listing_items']);
    }

    $settings = tpaep_mcp_merge_widget_settings($settings, $input['settings'] ?? []);
    $widget = [
        'id'         => tpaep_mcp_generate_elementor_element_id(),
        'elType'     => 'widget',
        'widgetType' => $widget_type,
        'isInner'    => false,
        'settings'   => $settings,
        'elements'   => [],
    ];
    if (!tpaep_mcp_insert_elementor_element($page_data, $parent_id, $widget, $position)) { return new WP_Error('parent_not_found', __('Parent container not found.', 'theplus')); }
    $save_result = tpaep_mcp_save_elementor_page_data($post_id, $page_data);
    if (is_wp_error($save_result)) { return $save_result; }
    return ['element_id' => $widget['id'], 'widget_type' => $widget_type, 'post_id' => $post_id];
}
