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

wp_register_ability('sprout/tpae-heading-title', [
'label' => __('Heading Title (Pro)', 'sprout-mcp'),
    'description' => __('Adds The Plus "Heading Title" widget (tp-heading-title) to an Elementor container. Pro version with extra styles and dynamic sources.', 'sprout-mcp'),
    '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],
        
        'heading_style'   => ['type' => 'string',  'enum' => ['style_1', 'style_2', 'style_4', 'style_5', 'style_6', 'style_7', 'style_8', 'style_9', 'style_10'], 'description' => 'Heading visual style', 'default' => 'style_1'],
        'select_heading'  => ['type' => 'string',  'enum' => ['default', 'page_title'], 'description' => 'Heading text source', 'default' => 'default'],
        
        'title'           => ['type' => 'string',  'description' => 'Main heading text'],
        'sub_title'       => ['type' => 'string',  'description' => 'Sub heading text'],
        'title_s'         => ['type' => 'string',  'description' => 'Extra prefix/postfix text (for Extra Title)'],
        
        'heading_s_style' => ['type' => 'string',  'enum' => ['text_before', 'text_after'], 'description' => 'Position of Extra Title'],
        'position'        => ['type' => 'string',  'enum' => ['before', 'after'], 'description' => 'Title Position relative to Sub Title', 'default' => 'after'],
        'sub_title_align' => ['type' => 'string',  'enum' => ['left', 'center', 'right', 'justify'], 'description' => 'Text alignment'],
        
        'title_link'      => ['type' => 'string',  'description' => 'Heading Title URL'],
        'ast_title_link'  => ['type' => 'string',  'description' => 'Heading Title Link for Animated Split (style 10)'],
        
        'ani_split_type'  => ['type' => 'string',  'enum' => ['words', 'chars', 'lines'], 'description' => 'Split type for Animated Split text'],
        
        'heading_title_subtitle_limit' => ['type' => 'string', 'enum' => ['yes', 'no']],
        'display_heading_title_limit'  => ['type' => 'string', 'enum' => ['yes', 'no']],
        'display_heading_title_by'     => ['type' => 'string', 'enum' => ['char', 'word']],
        'display_heading_title_input'  => ['type' => 'integer'],
        
        'display_sub_title_limit'      => ['type' => 'string', 'enum' => ['yes', 'no']],
        'display_sub_title_by'         => ['type' => 'string', 'enum' => ['char', 'word']],
        'display_sub_title_input'      => ['type' => 'integer'],
        
        'enable_text_animation'         => ['type' => 'string', 'enum' => ['yes', 'no']],
        'text_animation_type'           => ['type' => 'string', 'enum' => ['normal', 'explode', 'scramble', 'typing']],
        'enable_text_animation_sub_txt' => ['type' => 'string', 'enum' => ['yes', 'no']],
        'text_animation_type_sub_txt'   => ['type' => 'string', 'enum' => ['normal', 'explode', 'scramble', 'typing']],
        
        'settings'        => ['type' => 'object',  'description' => 'Raw Elementor control key/value pairs to merge.'],
    ], 'required' => ['post_id', 'parent_id', 'title'], 'additionalProperties' => false],
    'output_schema' => ['type' => 'object', 'properties' => [
        'element_id'  => ['type' => 'string'],
        'widget_type' => ['type' => 'string'],
        'post_id'     => ['type' => 'integer'],
    ]],
    'execute_callback'    => 'sprout_mcp_theplus_pro_heading_title_ability',
    'permission_callback' => 'sprout_mcp_theplus_pro_heading_title_permission',
    'meta' => ['show_in_rest' => true, 'mcp' => ['public' => true, 'type' => 'tool']],
]);

function sprout_mcp_theplus_pro_heading_title_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 sprout_mcp_theplus_pro_heading_title_ability(array $input) {
    if (!sprout_mcp_has_elementor()) { return new WP_Error('elementor_missing', __('Elementor must be active.', 'sprout-mcp')); }
    $widget_type = 'tp-heading-title';
    if (!sprout_mcp_has_registered_widget($widget_type)) { return new WP_Error('widget_missing', __('The Plus Heading Title widget is not registered.', 'sprout-mcp')); }
    $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.', 'sprout-mcp')); }
    if (empty($input['title'])) { return new WP_Error('missing_params', __('title is required.', 'sprout-mcp')); }
    $post = get_post($post_id);
    if (!$post instanceof WP_Post) { return new WP_Error('invalid_post', __('Target post was not found.', 'sprout-mcp')); }
    $page_data = sprout_mcp_get_elementor_page_data($post_id);
    if (is_wp_error($page_data)) { return $page_data; }
    
    $settings = [];
    $string_keys = [
        'heading_style', 'select_heading', 'title', 'sub_title', 'title_s',
        'heading_s_style', 'position', 'sub_title_align', 'ani_split_type',
        'heading_title_subtitle_limit', 'display_heading_title_limit', 'display_heading_title_by',
        'display_sub_title_limit', 'display_sub_title_by',
        'enable_text_animation', 'text_animation_type', 'enable_text_animation_sub_txt', 'text_animation_type_sub_txt'
    ];
    $number_keys = [
        'display_heading_title_input', 'display_sub_title_input'
    ];
    
    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['title_link'])) {
        $settings['title_link'] = ['url' => esc_url_raw($input['title_link'])];
    }
    if (!empty($input['ast_title_link'])) {
        $settings['ast_title_link'] = ['url' => esc_url_raw($input['ast_title_link'])];
    }
    
    // Backward compatibility for inputs
    if (!isset($settings['title_s']) && !empty($input['extra_title'])) {
        $settings['title_s'] = sanitize_text_field($input['extra_title']);
    }
    if (!isset($settings['sub_title_align']) && !empty($input['alignment'])) {
        $settings['sub_title_align'] = sanitize_key($input['alignment']);
    }
    if (!isset($settings['select_heading']) && !empty($input['heading_type'])) {
        if ($input['heading_type'] === 'page_title') {
            $settings['select_heading'] = 'page_title';
        }
    }
    
    $settings = sprout_mcp_merge_widget_settings($settings, $input['settings'] ?? []);
    $widget = [
        'id'         => sprout_mcp_generate_elementor_element_id(),
        'elType'     => 'widget',
        'widgetType' => $widget_type,
        'isInner'    => false,
        'settings'   => $settings,
        'elements'   => [],
    ];
    if (!sprout_mcp_insert_elementor_element($page_data, $parent_id, $widget, $position)) { return new WP_Error('parent_not_found', __('Parent container not found.', 'sprout-mcp')); }
    $save_result = sprout_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];
}
