<?php

namespace Unlockafe_addons\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Widget_Base;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Text Generator
 *
 * @since 1.0.0
 */
class Text_Generator extends Widget_Base
{
    use \Unlockafe_addons\Traits\Widget_helper;
    use \Unlockafe_addons\Traits\Utils;

    /**
     * Retrieve the widget name.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget name.
     */
    public function get_name()
    {
        return 'unlockafe_text_generator';
    }

    /**
     * Retrieve the widget title.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget title.
     */
    public function get_title()
    {
        return esc_html__('AI Text Generator', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon()
    {
        return 'eicon-text ulicon';
    }

    /**
     * Retrieve the list of categories the widget belongs to.
     *
     * Used to determine where to display the widget in the editor.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of scripts the widget depended on.
     *
     * Used to set scripts dependencies required to run the widget.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget scripts dependencies.
     */
    public function get_script_depends()
    {
        return ['unlockafe-text-generator'];
    }

    /**
     * Register the widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     *
     * @access protected
     */
    protected function register_controls()
    {
        $this->start_controls_section(
            'section_general',
            [
                'label' => esc_html__('General', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        // Get current API settings for debug info
        $settings_instance = \Unlockafe_addons\Admin\Text_Generator_Settings::getInstance();
        $api_settings = $settings_instance->get_settings();
        $api_provider = isset($api_settings['api_provider']) ? $api_settings['api_provider'] : 'custom';
        $api_key_set = !empty($api_settings['openai_api_key']);
        $api_endpoint = isset($api_settings['api_endpoint']) ? $api_settings['api_endpoint'] : '';

        // Add debug info
        $this->add_control(
            'api_info',
            [
                'label' => esc_html__('API Provider Info', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::RAW_HTML,
                'raw' => sprintf(
                    '<div style="background: #f7f7f7; padding: 10px; border-left: 3px solid #0073aa;">
                        <p><strong>Current API Provider:</strong> %s</p>
                        <p><strong>OpenAI API Key:</strong> %s</p>
                        %s
                        <p><a href="%s" target="_blank">Configure API Settings</a></p>
                    </div>',
                    $api_provider === 'openai' ? 'OpenAI' : 'Custom API (Ollama)',
                    $api_key_set ? 'Set' : 'Not Set',
                    $api_provider === 'custom' ? '<p><strong>Custom Endpoint:</strong> ' . esc_html($api_endpoint) . '</p>' : '',
                    admin_url('admin.php?page=unlock-addons-integrations')
                ),
                'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
            ]
        );

        $this->add_control(
            'placeholder_text',
            [
                'label' => esc_html__('Placeholder Content', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::WYSIWYG,
                'default' => '',
                'placeholder' => esc_html__('Start typing or generate content...', 'unlock-addons-for-elementor'),
                'description' => esc_html__('Enter content to display initially or leave blank. You can then generate content using AI.', 'unlock-addons-for-elementor'),
            ]
        );

        // Note: We'll add more advanced controls in future steps

        $this->end_controls_section();

        // Style Tab for the generated text
        $this->start_controls_section(
            'section_style_content',
            [
                'label' => esc_html__('Content', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'text_align',
            [
                'label' => esc_html__('Alignment', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => esc_html__('Left', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => esc_html__('Right', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ],
                    'justify' => [
                        'title' => esc_html__('Justified', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-justify',
                    ],
                ],
                'default' => '',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content' => 'text-align: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'text_typography',
                'selector' => '{{WRAPPER}} .unlockafe-text-generator-content',
            ]
        );

        $this->add_control(
            'text_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Text_Shadow::get_type(),
            [
                'name' => 'text_shadow',
                'selector' => '{{WRAPPER}} .unlockafe-text-generator-content',
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Border::get_type(),
            [
                'name' => 'content_border',
                'selector' => '{{WRAPPER}} .unlockafe-text-generator-content',
                'separator' => 'before',
            ]
        );

        $this->add_responsive_control(
            'content_border_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            \Elementor\Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'content_box_shadow',
                'selector' => '{{WRAPPER}} .unlockafe-text-generator-content',
            ]
        );

        $this->add_responsive_control(
            'content_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'default' => [
                    'top' => '10',
                    'right' => '10',
                    'bottom' => '10',
                    'left' => '10',
                    'unit' => 'px',
                    'isLinked' => true,
                ],
            ]
        );

        $this->add_control(
            'heading_img_style',
            [
                'label' => esc_html__('Embedded Images', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $this->add_responsive_control(
            'image_max_width',
            [
                'label' => esc_html__('Max Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 1000,
                        'step' => 10,
                    ],
                    '%' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'unit' => '%',
                    'size' => 100,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content img' => 'max-width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'image_spacing',
            [
                'label' => esc_html__('Spacing', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 100,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 0,
                        'max' => 10,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 15,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-text-generator-content img' => 'margin-bottom: {{SIZE}}{{UNIT}}; margin-top: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Style Tab for the button
        $this->start_controls_section(
            'section_style_button',
            [
                'label' => esc_html__('Button', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'button_text_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-generate-button' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'button_background_color',
            [
                'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#4054b2',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-generate-button' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'button_typography',
                'selector' => '{{WRAPPER}} .unlockafe-generate-button',
            ]
        );

        $this->add_control(
            'button_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-generate-button' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'default' => [
                    'top' => 12,
                    'right' => 24,
                    'bottom' => 12,
                    'left' => 24,
                    'unit' => 'px',
                    'isLinked' => false,
                ],
            ]
        );

        $this->add_control(
            'button_border_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-generate-button' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'default' => [
                    'top' => 4,
                    'right' => 4,
                    'bottom' => 4,
                    'left' => 4,
                    'unit' => 'px',
                    'isLinked' => true,
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render the widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     *
     * @access protected
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $widget_id = $this->get_id();
        $editor_id = 'unlockafe-editor-' . $widget_id;
        $content = wp_kses_post($settings['placeholder_text']);
        
        // Enqueue the required scripts in the editor
        if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
            wp_enqueue_script('unlockafe-text-generator-editor', UNLOCKAFE_ASSETS . 'front-end/js/text-generator-editor.js', ['jquery', 'elementor-editor'], UNLOCKAFE_VERSION, true);
            wp_localize_script('unlockafe-text-generator-editor', 'unlockafe_text_generator', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('unlockafe_text_generator_nonce')
            ]);
        }
        
        ?>
        <div class="unlockafe-text-generator-wrapper">
            <div class="unlockafe-text-generator-content" id="<?php echo esc_attr('content-' . $widget_id); ?>">
                <?php 
                if (\Elementor\Plugin::$instance->editor->is_edit_mode()): 
                    // In editor mode, display the WYSIWYG content
                    echo '<div class="elementor-text-editor elementor-clearfix">' . wp_kses_post($content) . '</div>';
                else:
                    // On frontend, display the formatted content
                    echo '<div class="elementor-text-editor elementor-clearfix">' . wp_kses_post($content) . '</div>';
                endif;
                ?>
            </div>
            <?php if (\Elementor\Plugin::$instance->editor->is_edit_mode()): ?>
            <div class="unlockafe-text-generator-button-wrapper">
                <button class="unlockafe-generate-button" data-widget-id="<?php echo esc_attr($this->get_id()); ?>" onclick="unlockafe_handle_btn_click(this)">
                    Generate Text
                </button>
            </div>
            <?php endif; ?>
        </div>

        <style>
            .unlockafe-text-generator-content {
                line-height: 1.6;
                min-height: 100px;
            }
            .unlockafe-text-generator-content:focus-within {
                box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
            }
            .unlockafe-text-generator-content img {
                max-width: 100%;
                height: auto;
                margin: 10px 0;
                display: block;
            }
            .unlockafe-text-generator-content p {
                margin-bottom: 15px;
            }
            .unlockafe-text-generator-content h1, 
            .unlockafe-text-generator-content h2,
            .unlockafe-text-generator-content h3,
            .unlockafe-text-generator-content h4,
            .unlockafe-text-generator-content h5,
            .unlockafe-text-generator-content h6 {
                margin-bottom: 15px;
                margin-top: 25px;
            }
            .unlockafe-text-generator-button-wrapper {
                margin-top: 15px;
            }
        </style>

        <script>
        // Global modal reference
        var unlockAfeModal = null;

        function closeUnlockAfeModal() {
            document.removeEventListener('keydown', handleModalKeydown);
            if (unlockAfeModal && unlockAfeModal.parentNode) {
                unlockAfeModal.parentNode.removeChild(unlockAfeModal);
                unlockAfeModal = null;
            }
        }
        
        function unlockafe_handle_btn_click(btn) {
            // Prevent default action
            event.preventDefault();
            
            // Log click for debugging
            console.log('Button clicked via inline handler');
            
            // Check if a modal is already open
            if (document.querySelector('.unlockafe-modal-overlay')) {
                console.log('Modal already open, not opening another one');
                return;
            }
            
            // Create and open a basic modal
            var modalHTML = '<style>' +
                '.unlockafe-modal-overlay {' +
                '  position: fixed;' +
                '  top: 0;' +
                '  left: 0;' +
                '  width: 100%;' +
                '  height: 100%;' +
                '  background-color: rgba(0, 0, 0, 0.7);' +
                '  display: flex;' +
                '  justify-content: center;' +
                '  align-items: center;' +
                '  z-index: 99999;' +
                '  opacity: 1;' +
                '}' +
                '.unlockafe-modal {' +
                '  background-color: #ffffff;' +
                '  border-radius: 6px;' +
                '  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);' +
                '  max-width: 500px;' +
                '  width: 90%;' +
                '  max-height: 90vh;' +
                '  overflow-y: auto;' +
                '  margin: 0 20px;' +
                '  position: relative;' +
                '  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;' +
                '}' +
                '.unlockafe-modal-header {' +
                '  display: flex;' +
                '  justify-content: space-between;' +
                '  align-items: center;' +
                '  padding: 20px;' +
                '  border-bottom: 1px solid #eaeaea;' +
                '  background-color: #fff;' +
                '}' +
                '.unlockafe-modal-title {' +
                '  font-size: 20px;' +
                '  font-weight: 600;' +
                '  color: #444;' +
                '  margin: 0;' +
                '  line-height: 1.2;' +
                '}' +
                '.unlockafe-modal-close {' +
                '  background: none;' +
                '  border: none;' +
                '  color: #a4afb7;' +
                '  font-size: 24px;' +
                '  cursor: pointer;' +
                '  padding: 0;' +
                '  width: 30px;' +
                '  height: 30px;' +
                '  display: flex;' +
                '  align-items: center;' +
                '  justify-content: center;' +
                '}' +
                '.unlockafe-modal-body {' +
                '  padding: 20px;' +
                '  background-color: #fff;' +
                '}' +
                '.unlockafe-modal-form-group {' +
                '  margin-bottom: 20px;' +
                '  display: grid;' +
                '  grid-template-columns: 1fr;' +
                '  grid-gap: 8px;' +
                '}' +
                '.unlockafe-modal-label {' +
                '  display: block;' +
                '  margin-bottom: 8px;' +
                '  font-weight: 500;' +
                '  color: #556068;' +
                '  font-size: 14px;' +
                '}' +
                '.unlockafe-modal-input,' +
                '.unlockafe-modal-select,' +
                '.unlockafe-modal-textarea {' +
                '  width: 100%;' +
                '  padding: 10px 12px;' +
                '  border: 1px solid #d5dadf;' +
                '  border-radius: 3px;' +
                '  background-color: #ffffff;' +
                '  font-size: 14px;' +
                '  color: #495157;' +
                '}' +
                '.unlockafe-modal-textarea {' +
                '  min-height: 100px;' +
                '  resize: vertical;' +
                '  font-family: inherit;' +
                '}' +
                '.unlockafe-modal-input:focus,' +
                '.unlockafe-modal-select:focus,' +
                '.unlockafe-modal-textarea:focus {' +
                '  border-color: #4054b2;' +
                '  outline: none;' +
                '  box-shadow: 0 0 0 1px rgba(64, 84, 178, 0.3);' +
                '}' +
                '.unlockafe-modal-footer {' +
                '  display: flex;' +
                '  justify-content: flex-end;' +
                '  padding: 15px 20px;' +
                '  border-top: 1px solid #eaeaea;' +
                '  background-color: #f7f7f7;' +
                '  gap: 10px;' +
                '}' +
                '.unlockafe-modal-button {' +
                '  padding: 10px 20px;' +
                '  border-radius: 3px;' +
                '  font-size: 14px;' +
                '  font-weight: 500;' +
                '  cursor: pointer;' +
                '  border: 1px solid transparent;' +
                '}' +
                '.unlockafe-modal-cancel {' +
                '  background-color: #f1f3f5;' +
                '  color: #6d7882;' +
                '}' +
                '.unlockafe-modal-cancel:hover {' +
                '  background-color: #e8eaed;' +
                '}' +
                '.unlockafe-modal-submit {' +
                '  background-color: #4054b2;' +
                '  color: #ffffff;' +
                '}' +
                '.unlockafe-modal-submit:hover {' +
                '  background-color: #3448a0;' +
                '}' +
                '.unlockafe-spinner {' +
                '  display: inline-block;' +
                '  width: 20px;' +
                '  height: 20px;' +
                '  border: 3px solid rgba(255, 255, 255, 0.3);' +
                '  border-radius: 50%;' +
                '  border-top-color: #fff;' +
                '  animation: unlockafe-spin 1s linear infinite;' +
                '  margin-right: 5px;' +
                '  vertical-align: middle;' +
                '}' +
                '@keyframes unlockafe-spin {' +
                '  to { transform: rotate(360deg); }' +
                '}' +
                '.unlockafe-debug-container {' +
                '  position: fixed;' +
                '  bottom: 10px;' +
                '  right: 10px;' +
                '  z-index: 99999;' +
                '  background: white;' +
                '  border: 1px solid #ccc;' +
                '  padding: 10px;' +
                '  max-width: 500px;' +
                '  max-height: 300px;' +
                '  overflow: auto;' +
                '  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);' +
                '  font-family: monospace;' +
                '  font-size: 12px;' +
                '}' +
                '</style>' +
                '<div class="unlockafe-modal-overlay active">' +
                '<div class="unlockafe-modal" role="dialog" aria-labelledby="unlockafe-modal-title" aria-modal="true">' +
                '<div class="unlockafe-modal-header">' +
                '<h3 class="unlockafe-modal-title" id="unlockafe-modal-title">Generate Text</h3>' +
                '<button class="unlockafe-modal-close" onclick="closeUnlockAfeModal()" aria-label="Close">&times;</button>' +
                '</div>' +
                '<div class="unlockafe-modal-body">' +
                '<form id="unlockafe-text-generator-form" onsubmit="event.preventDefault(); generateTextFromModal(document.querySelector(\'.unlockafe-modal-submit\'), \'' + btn.getAttribute('data-widget-id') + '\')">' +
                '<input type="hidden" id="unlockafe-widget-id" value="' + btn.getAttribute('data-widget-id') + '">' +
                '<input type="hidden" name="unlockafe_text_generator_nonce" id="unlockafe_text_generator_nonce" value="' + unlockafe_text_generator_nonce + '">' +
                '<div class="unlockafe-modal-form-group">' +
                '<label class="unlockafe-modal-label" for="unlockafe-topic">Topic</label>' +
                '<input type="text" id="unlockafe-topic" class="unlockafe-modal-input unlockafe-modal-topic" placeholder="Enter a topic">' +
                '</div>' +
                '<div class="unlockafe-modal-form-group">' +
                '<label class="unlockafe-modal-label" for="unlockafe-length">Length</label>' +
                '<select id="unlockafe-length" class="unlockafe-modal-select unlockafe-modal-length">' +
                '<option value="very-short">Very Short (50-100 words)</option>' +
                '<option value="short">Short (100-200 words)</option>' +
                '<option value="medium" selected>Medium (200-500 words)</option>' +
                '<option value="long">Long (500+ words)</option>' +
                '</select>' +
                '</div>' +
                '<div class="unlockafe-modal-form-group">' +
                '<label class="unlockafe-modal-label" for="unlockafe-tone">Tone</label>' +
                '<select id="unlockafe-tone" class="unlockafe-modal-select unlockafe-modal-tone">' +
                '<option value="professional">Professional</option>' +
                '<option value="casual" selected>Casual</option>' +
                '<option value="formal">Formal</option>' +
                '<option value="friendly">Friendly</option>' +
                '<option value="persuasive">Persuasive</option>' +
                '</select>' +
                '</div>' +
                '<div class="unlockafe-modal-form-group">' +
                '<label class="unlockafe-modal-label" for="unlockafe-instructions">Additional Instructions (Optional)</label>' +
                '<textarea id="unlockafe-instructions" class="unlockafe-modal-textarea unlockafe-modal-instructions" placeholder="Any specific instructions for the text generator"></textarea>' +
                '</div>' +
                '</form>' +
                '</div>' +
                '<div class="unlockafe-modal-footer">' +
                '<button class="unlockafe-modal-button unlockafe-modal-cancel" onclick="closeUnlockAfeModal()">Cancel</button>' +
                '<button type="button" class="unlockafe-modal-button unlockafe-modal-submit" onclick="generateTextFromModal(this, \'' + btn.getAttribute('data-widget-id') + '\')">Generate</button>' +
                '</div>' +
                '</div>' +
                '</div>';
            
            // Add modal to body
            document.body.insertAdjacentHTML('beforeend', modalHTML);
            unlockAfeModal = document.querySelector('.unlockafe-modal-overlay');
            
            // Focus on topic field
            setTimeout(function() {
                document.getElementById('unlockafe-topic').focus();
            }, 100);

            // Add keyboard event listeners for accessibility
            document.addEventListener('keydown', handleModalKeydown);
            
            // Add click event listener for overlay
            document.querySelector('.unlockafe-modal-overlay').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeUnlockAfeModal();
                }
            });
        }
        
        function generateTextFromModal(btn, widgetId) {
            // BUGFIX: Handle duplicate elements - find all topic inputs and use the one with content
            var topicElements = document.querySelectorAll('.unlockafe-modal-topic');
            var topic = '';
            var topicElement = null;
            
            // Loop through all topic inputs and find the one with content
            for (var i = 0; i < topicElements.length; i++) {
                console.log('Topic input #' + i + ':', topicElements[i].value);
                if (topicElements[i].value && topicElements[i].value.trim() !== '') {
                    topicElement = topicElements[i];
                    topic = topicElement.value;
                    console.log('Found non-empty topic in input #' + i + ':', topic);
                    break;
                }
            }
            
            // If no non-empty topic found, default to the first one
            if (!topic && topicElements.length > 0) {
                topicElement = topicElements[0];
                topic = topicElement.value;
                console.log('Using first topic element as fallback:', topic);
            }
            
            // Get other form values
            var lengthElements = document.querySelectorAll('.unlockafe-modal-length');
            var length = lengthElements.length > 0 ? lengthElements[0].value : 'medium';
            
            var toneElements = document.querySelectorAll('.unlockafe-modal-tone');
            var tone = toneElements.length > 0 ? toneElements[0].value : 'casual';
            
            var instructionsElements = document.querySelectorAll('.unlockafe-modal-instructions');
            var instructions = instructionsElements.length > 0 ? instructionsElements[0].value : '';
            
            var storedWidgetId = document.getElementById('unlockafe-widget-id') ? document.getElementById('unlockafe-widget-id').value : '';
            
            // Use stored widget ID if passed one is empty
            if (!widgetId && storedWidgetId) {
                widgetId = storedWidgetId;
            }
            
            // Debug topic value to see what's happening
            console.log('Topic value:', topic, 'Length:', topic ? topic.length : 0);
            logDebug('Topic entered: "' + topic + '"');
            
            // Improved validation with whitespace trimming
            if (!topic || topic.trim() === '') {
                var alertMessage = 'Please enter a topic';
                alert(alertMessage);
                logDebug('Validation failed: ' + alertMessage);
                
                // Focus on the topic field - using class selector
                if (topicElement) {
                    topicElement.focus();
                    logDebug('Set focus to topic field');
                } else {
                    logDebug('ERROR: Could not find topic field to focus');
                }
                return;
            }
            
            // Trim the topic to remove any whitespace
            topic = topic.trim();
            logDebug('Topic after trimming: "' + topic + '"');
            
            console.log('Generating text for widget ID:', widgetId);
            
            // Show loading
            var originalText = btn.textContent;
            btn.innerHTML = '<span class="unlockafe-spinner"></span> Generating...';
            btn.disabled = true;
            
            // Build prompt from input values
            var prompt = '';
            
            // Create a structured prompt based on the topic and requirements
            prompt = `Create a well-structured web article or page content about "${topic}" that is suitable for a WordPress website. 
            
Requirements:
- Create an engaging title with proper H1 formatting
- Include 3-4 sections with descriptive H2 headings
- If relevant, use H3 subheadings for more detailed sections
- Make content easy to read with short paragraphs and bullet points where appropriate
- Include one small code example if relevant to the topic
- Maintain a ${tone} tone throughout
- Write approximately ${length === 'very-short' ? '50-100' : length === 'short' ? '100-200' : length === 'medium' ? '300-500' : '500-800'} words
- End with a brief conclusion
- Do not include generic placeholders or references
- Format the content with proper HTML tags for headings, paragraphs, and lists

${instructions ? 'Additional instructions: ' + instructions : ''}`;

            console.log('Generating content with prompt:', prompt);
            
            // Create debug info display
            var debugId = 'unlockafe-debug-' + Date.now();
            var debugContainer = document.createElement('div');
            debugContainer.id = debugId;
            debugContainer.className = 'unlockafe-debug-container';
            debugContainer.innerHTML = '<h4>Text Generator Debug <button onclick="this.parentElement.parentElement.remove()" style="float:right;background:none;border:none;cursor:pointer;font-size:12px;color:#999;">Close</button></h4><div class="debug-content"></div>';
            debugContainer.style.display = 'none'; // Hide by default
            document.body.appendChild(debugContainer);
            
            // Set debug mode (always show for troubleshooting)
            var isDebugMode = true; // Force debug mode to be always on for troubleshooting
            
            function logDebug(message) {
                console.log(message);
                var content = document.querySelector('#' + debugId + ' .debug-content');
                if (content) {
                    content.innerHTML += '<div>' + message + '</div>';
                    debugContainer.scrollTop = debugContainer.scrollHeight;
                    
                    // Show the debug container only if in debug mode
                    if (isDebugMode) {
                        debugContainer.style.display = 'block';
                    }
                }
            }
            
            logDebug('Starting API request');
            logDebug('Prompt: ' + prompt);
            
            // Get WordPress admin AJAX URL
            var ajaxUrl = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
            logDebug('AJAX URL: ' + ajaxUrl);
            
            // Create nonce for security
            var nonce = '<?php echo esc_js(wp_create_nonce('unlockafe_text_generator_nonce')); ?>';
            
            // Make AJAX request
            var xhr = new XMLHttpRequest();
            xhr.open('POST', ajaxUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    logDebug('Response status: ' + xhr.status);
                    
                    if (xhr.status >= 200 && xhr.status < 400) {
                        try {
                            var response = JSON.parse(xhr.responseText);
                            logDebug('Response received: ' + JSON.stringify(response));
                            
                            if (response.success) {
                                var generatedText = '';
                                
                                // Handle debug info if available
                                if (typeof response.data === 'object' && response.data.debug) {
                                    logDebug('API Provider: ' + response.data.debug.api_provider);
                                    logDebug('Model: ' + response.data.debug.model);
                                    generatedText = response.data.content;
                                } else {
                                    generatedText = response.data;
                                }
                                
                                logDebug('Text length: ' + generatedText.length);
                                logDebug('Preview: ' + generatedText.substring(0, 100) + '...');
                                
                                // Update the widget content
                                var targetWidget = document.querySelector('[data-id="' + widgetId + '"]');
                                if (targetWidget) {
                                    var textContainer = targetWidget.querySelector('.unlockafe-text-generator-content');
                                    if (textContainer) {
                                        // Format the text with proper paragraphs
                                        var formattedText = generatedText;
                                        textContainer.querySelector('.elementor-text-editor').innerHTML = formattedText;
                                        
                                        // Update Elementor model if in editor
                                        if (window.elementor) {
                                            try {
                                                var model = elementor.getContainer(widgetId).model;
                                                model.setSetting('placeholder_text', formattedText);
                                                elementor.saver.setFlagEditorChange(true);
                                                logDebug('Updated Elementor model successfully');
                                            } catch (e) {
                                                logDebug('Error updating Elementor model: ' + e.message);
                                            }
                                        }
                                    }
                                }
                                
                                // Close modal
                                closeUnlockAfeModal();
                                
                            } else {
                                logDebug('Error in response: ' + JSON.stringify(response.data));
                                alert('Error: ' + (typeof response.data === 'string' ? response.data : 'Failed to generate text'));
                            }
                        } catch (e) {
                            logDebug('Error parsing response: ' + e.message);
                            logDebug('Raw response: ' + xhr.responseText);
                            alert('Error processing response from server');
                        }
                    } else {
                        logDebug('HTTP error: ' + xhr.status);
                        alert('Server error: ' + xhr.status);
                    }
                    
                    // Reset button
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                    
                    // Remove debug info after 2 minutes
                    setTimeout(function() {
                        if (document.getElementById(debugId)) {
                            document.getElementById(debugId).remove();
                        }
                    }, 120000);
                }
            };
            
            // Prepare data
            var data = 'action=unlockafe_generate_text' + 
                      '&prompt=' + encodeURIComponent(prompt) + 
                      '&nonce=' + encodeURIComponent(nonce) + 
                      '&debug=true';
            
            logDebug('Sending data: ' + data);
            
            // Send request
            xhr.send(data);
        }
        
        function handleModalKeydown(e) {
            if (e.key === 'Escape') {
                closeUnlockAfeModal();
            } else if (e.key === 'Enter' && e.target.classList.contains('unlockafe-modal-topic')) {
                // If Enter is pressed in the topic field, submit the form
                var widgetId = document.querySelector('.unlockafe-modal-submit').getAttribute('onclick').match(/'([^']+)'/)[1];
                generateTextFromModal(document.querySelector('.unlockafe-modal-submit'), widgetId);
            }
        }
        </script>
        <?php
    }
}
