<?php
/**
 * Gestión de configuración del plugin
 *
 * Maneja el registro y renderizado de opciones del plugin
 *
 * @package BravesChat
 * @since 1.0.0
 * @version 1.2.2
 */

namespace BravesChat;

use function defined;
use function add_action;
use function get_option;
use function is_array;
use function is_bool;
use function esc_attr;
use function add_menu_page;
use function __;
use function _e;
use function add_submenu_page;
use function file_exists;
use function file_get_contents;
use function base64_encode;
use function add_settings_section;
use function register_setting;
use function add_settings_field;
use function checked;
use function printf;
use function esc_url_raw;
use function sanitize_text_field;
use function esc_textarea;
use function selected;
use function esc_html;
use function get_pages;
use function in_array;
use function wp_enqueue_style;
use function wp_enqueue_script;
use function current_user_can;
use function timezone_identifiers_list;
use function preg_match;
use function array_map;
use function wp_enqueue_media;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Clase Settings
 *
 * Gestiona la configuración y opciones del plugin en WordPress
 *
 * @since 1.0.0
 */
class Settings {

    /**
     * Instancia única (patrón Singleton)
     *
     * @since 1.0.0
     * @var Settings|null
     */
    private static $instance = null;

    /**
     * Prefijo para las opciones de WordPress
     *
     * @since 1.0.0
     * @var string
     */
    private $option_prefix = 'braves_chat_';

    /**
     * Obtener instancia única
     *
     * @since 1.0.0
     * @return Settings Instancia única de la clase
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor privado (patrón Singleton)
     *
     * Inicializa hooks de WordPress
     *
     * @since 1.0.0
     */
    private function __construct() {
        // NOTE: Menu is now handled by Admin_Controller class (v1.2.0)
        // add_action('admin_menu', array($this, 'add_settings_page'));
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
        add_action('admin_enqueue_scripts', array($this, 'add_menu_icon_styles'), 20);
        add_action('wp_ajax_braves_save_auth_type', array($this, 'ajax_save_auth_type'));
    }

    /**
     * Guarda el tipo de autenticación vía AJAX (sin recargar la página)
     *
     * @since 2.3.0
     * @return void
     */
    public function ajax_save_auth_type() {
        check_ajax_referer('braves_save_auth_type', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Unauthorized.', 'braveschat')));
        }

        $allowed = array('none', 'header', 'basic');
        $type    = sanitize_text_field(wp_unslash($_POST['auth_type'] ?? ''));

        if (!in_array($type, $allowed, true)) {
            wp_send_json_error(array('message' => __('Invalid authentication type.', 'braveschat')));
        }

        update_option($this->option_prefix . 'n8n_auth_type', $type);
        wp_send_json_success();
    }

    /**
     * Renderizar campos ocultos para preservar opciones no mostradas
     *
     * @param array $exclude_fields Campos a excluir (los que están visibles en el formulario)
     * @return void
     */
    public function render_hidden_fields($exclude_fields = array()) {
        $all_fields = array(
            'global_enable',
            'webhook_url',
            'n8n_auth_type',
            'n8n_auth_token',
            'n8n_auth_header',
            'header_title',
            'header_subtitle',
            'welcome_message',
            'typing_speed',
            'position',
            'display_mode',
            'chat_icon',
            'icon_color',
            'bubble_tooltip',
            'bubble_color',
            'primary_color',
            'background_color',
            'text_color',
            'excluded_pages',
            'availability_enabled',
            'availability_start',
            'availability_end',
            'availability_timezone',
            'availability_message',
            'gdpr_enabled',
            'gdpr_message',
            'gdpr_accept_text',
            'chat_skin',
            'bubble_image',
            'bubble_text',
            'header_status_text',
            'stats_webhook_url',
            'stats_api_key',
            'agent_name',
        );

        foreach ($all_fields as $field) {
            if (in_array($field, $exclude_fields)) {
                continue; // Saltar campos visibles
            }

            $option_name = $this->option_prefix . $field;
            $value = get_option($option_name);

            if (is_array($value)) {
                // Para arrays como excluded_pages
                foreach ($value as $item) {
                    echo '<input type="hidden" name="' . esc_attr($option_name) . '[]" value="' . esc_attr($item) . '">';
                }
            } elseif (is_bool($value) || $value === '1' || $value === '0') {
                // Para checkboxes
                echo '<input type="hidden" name="' . esc_attr($option_name) . '" value="' . esc_attr( $value ? '1' : '0' ) . '">';
            } else {
                // Para campos de texto normales
                echo '<input type="hidden" name="' . esc_attr($option_name) . '" value="' . esc_attr($value) . '">';
            }
        }
    }

    /**
     * Agregar menú principal en el admin de WordPress
     *
     * DEPRECATED: Ahora se maneja desde Admin_Controller (v1.2.0)
     *
     * @since 1.0.0
     * @deprecated 1.2.0 Usar Admin_Controller en su lugar
     * @return void
     */
    public function add_settings_page() {
        // Determinar la ruta del icono (SVG o PNG)
        $icon_url = $this->get_menu_icon();

        // Agregar página principal del menú
        add_menu_page(
            __('BravesChat iA', 'braveschat'),           // page_title
            __('BravesChat iA', 'braveschat'),           // menu_title
            'manage_options',                             // capability
            'braves-chat-ia',                              // menu_slug
            array($this, 'render_settings_page'),         // callback
            $icon_url,                                    // icon_url
            58                                            // position (después de Apariencia=60, antes de Plugins=65)
        );

        // Agregar submenú "Dashboard" (renombra el primer item)
        add_submenu_page(
            'braves-chat-ia',                              // parent_slug
            __('Dashboard', 'braveschat'),                // page_title
            __('Dashboard', 'braveschat'),                // menu_title
            'manage_options',                             // capability
            'braves-chat-ia',                              // menu_slug (mismo que parent para ser el primero)
            array($this, 'render_settings_page')          // callback
        );

        // Agregar submenú "Ajustes"
        add_submenu_page(
            'braves-chat-ia',                              // parent_slug
            __('Settings', 'braveschat'),                  // page_title
            __('Settings', 'braveschat'),                  // menu_title
            'manage_options',                             // capability
            'braves-chat-settings',                        // menu_slug
            array($this, 'render_settings_page')          // callback
        );
    }

    /**
     * Obtener URL del icono del menú
     *
     * Busca primero SVG, luego PNG, sino usa dashicon por defecto
     *
     * @since 1.0.0
     * @return string URL del icono o dashicon
     */
    private function get_menu_icon() {
        // Intentar cargar SVG
        $svg_path = BRAVES_CHAT_PLUGIN_DIR . 'assets/media/menu-icon.svg';
        if (file_exists($svg_path)) {
            $svg_content = file_get_contents($svg_path);
            // Codificar SVG como data URI
            return 'data:image/svg+xml;base64,' . base64_encode($svg_content);
        }

        // Intentar cargar PNG
        $png_url = BRAVES_CHAT_PLUGIN_URL . 'assets/media/menu-icon.png';
        $png_path = BRAVES_CHAT_PLUGIN_DIR . 'assets/media/menu-icon.png';
        if (file_exists($png_path)) {
            return $png_url;
        }

        // Fallback a dashicon
        return 'dashicons-format-chat';
    }

    /**
     * Estilos personalizados para el icono del menú
     *
     * Agrega estilos CSS inline para el icono del menú de WordPress
     *
     * @since 1.0.0
     * @return void
     */
    public function add_menu_icon_styles() {
        $css = '
            #toplevel_page_braveschat .wp-menu-image img {
                width: 20px;
                height: 20px;
                padding: 6px 0;
                opacity: 0.6;
                transition: opacity 0.2s ease;
            }
            #toplevel_page_braveschat:hover .wp-menu-image img,
            #toplevel_page_braveschat.current .wp-menu-image img,
            #toplevel_page_braveschat.wp-has-current-submenu .wp-menu-image img {
                opacity: 1;
            }
            #toplevel_page_braveschat .wp-menu-image svg {
                width: 20px;
                height: 20px;
                fill: #a7aaad;
                transition: fill 0.2s ease;
            }
            #toplevel_page_braveschat:hover .wp-menu-image svg {
                fill: #00a0d2;
            }
            #toplevel_page_braveschat.wp-has-current-submenu .wp-menu-image svg,
            #toplevel_page_braveschat.current .wp-menu-image svg {
                fill: #ffffff !important;
            }
            #toplevel_page_braveschat .update-plugins {
                background-color: #00a0d2;
            }
        ';
        wp_register_style( 'braves-menu-icon', false, array(), BRAVES_CHAT_VERSION );
        wp_enqueue_style( 'braves-menu-icon' );
        wp_add_inline_style( 'braves-menu-icon', $css );
    }

    /**
     * Registrar todas las opciones del plugin en WordPress
     *
     * Registra secciones y campos de configuración usando Settings API
     *
     * @since 1.0.0
     * @since 1.2.2 Añadido campo token N8N
     * @return void
     */
    public function register_settings() {
        // ==================== SECCIÓN GENERAL ====================
        add_settings_section(
            'braves_chat_general_section',
            __('General Settings', 'braveschat'),
            array($this, 'general_section_callback'),
            'braves_chat_settings'
        );
        
        // Global Enable
        register_setting('braves_chat_settings', $this->option_prefix . 'global_enable', array(
            'type' => 'boolean',
            'sanitize_callback' => array($this, 'sanitize_checkbox'),
            'default' => false
        ));
        
        add_settings_field(
            'global_enable',
            __('Show across the entire website', 'braveschat'),
            array($this, 'global_enable_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Webhook URL
        register_setting('braves_chat_settings', $this->option_prefix . 'webhook_url', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => 'https://flow.braveslab.com/webhook/1427244e-a23c-4184-a536-d02622f36325/chat'
        ));
        
        add_settings_field(
            'webhook_url',
            __('Webhook URL', 'braveschat'),
            array($this, 'webhook_url_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // ========== TAREA 2A: CAMPO TOKEN DE AUTENTICACIÓN N8N ==========
        register_setting('braves_chat_settings', $this->option_prefix . 'n8n_auth_token', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => ''
        ));

        register_setting('braves_chat_settings', $this->option_prefix . 'n8n_auth_type', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'header',
        ));

        register_setting('braves_chat_settings', $this->option_prefix . 'n8n_auth_header', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => 'X-N8N-Auth',
        ));
        
        add_settings_field(
            'n8n_auth_token',
            __('N8N Authentication Token', 'braveschat'),
            array($this, 'n8n_auth_token_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        // ========== FIN TAREA 2A ==========

        // Typing Speed
        register_setting('braves_chat_settings', $this->option_prefix . 'typing_speed', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 30
        ));

        add_settings_field(
            'typing_speed',
            __('Typing Speed', 'braveschat'),
            array($this, 'typing_speed_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Header Title
        register_setting('braves_chat_settings', $this->option_prefix . 'header_title', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => __('BravesLab AI Assistant', 'braveschat')
        ));
        
        add_settings_field(
            'header_title',
            __('Header Title', 'braveschat'),
            array($this, 'header_title_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );

        // Header Status Text
        register_setting('braves_chat_settings', $this->option_prefix . 'header_status_text', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => __('Chatting with Charlie', 'braveschat')
        ));
        
        add_settings_field(
            'header_status_text',
            __('Header Status Text', 'braveschat'),
            array($this, 'header_status_text_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Header Subtitle
        register_setting('braves_chat_settings', $this->option_prefix . 'header_subtitle', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => __('Artificial Intelligence Marketing Agency', 'braveschat')
        ));
        
        add_settings_field(
            'header_subtitle',
            __('Header Subtitle', 'braveschat'),
            array($this, 'header_subtitle_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Welcome Message
        register_setting('braves_chat_settings', $this->option_prefix . 'welcome_message', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_textarea_field',
            'default' => __('Hello! I\'m the BravesLab assistant, your Artificial Intelligence Marketing Agency. We integrate AI into businesses to multiply results. How can we help you?', 'braveschat')
        ));
        
        add_settings_field(
            'welcome_message',
            __('Welcome Message', 'braveschat'),
            array($this, 'welcome_message_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Position
        register_setting('braves_chat_settings', $this->option_prefix . 'position', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_position'),
            'default' => 'bottom-right'
        ));
        
        add_settings_field(
            'position',
            __('Chat Position', 'braveschat'),
            array($this, 'position_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );
        
        // Display Mode
        register_setting('braves_chat_settings', $this->option_prefix . 'display_mode', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_display_mode'),
            'default' => 'modal'
        ));
        
        add_settings_field(
            'display_mode',
            __('Display Mode', 'braveschat'),
            array($this, 'display_mode_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );

        // Chat Icon
        register_setting('braves_chat_settings', $this->option_prefix . 'chat_icon', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_chat_icon'),
            'default' => 'robot-chat'
        ));

        // Icon Color
        register_setting('braves_chat_settings', $this->option_prefix . 'icon_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
            'default' => '#f2f2f2'
        ));

        // Bubble Tooltip
        register_setting('braves_chat_settings', $this->option_prefix . 'bubble_tooltip', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => __('Chat with our AI assistant', 'braveschat')
        ));

        // Bubble Color
        register_setting('braves_chat_settings', $this->option_prefix . 'bubble_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
            'default' => '#01B7AF'
        ));

        // Primary Color
        register_setting('braves_chat_settings', $this->option_prefix . 'primary_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
            'default' => '#01B7AF'
        ));

        // Background Color
        register_setting('braves_chat_settings', $this->option_prefix . 'background_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
            'default' => '#FFFFFF'
        ));

        // Text Color
        register_setting('braves_chat_settings', $this->option_prefix . 'text_color', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
            'default' => '#333333'
        ));

        // Chat Skin
        register_setting('braves_chat_settings', $this->option_prefix . 'chat_skin', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'default'
        ));

        // Bubble Image
        register_setting('braves_chat_settings', $this->option_prefix . 'bubble_image', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => ''
        ));

        // Bubble Text
        register_setting('braves_chat_settings', $this->option_prefix . 'bubble_text', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'Voice chat' // translators: default label for voice bubble text
        ));

        add_settings_field(
            'bubble_text',
            __('Bubble Text', 'braveschat'),
            array($this, 'bubble_text_callback'),
            'braves_chat_settings',
            'braves_chat_general_section'
        );

        
        // ==================== SECCIÓN PÁGINAS EXCLUIDAS ====================
        add_settings_section(
            'braves_chat_exclusions_section',
            __('Excluded Pages', 'braveschat'),
            array($this, 'exclusions_section_callback'),
            'braves_chat_settings'
        );
        
        register_setting('braves_chat_settings', $this->option_prefix . 'excluded_pages', array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_excluded_pages'),
            'default' => array()
        ));
        
        add_settings_field(
            'excluded_pages',
            __('Pages where chat should NOT be shown', 'braveschat'),
            array($this, 'excluded_pages_callback'),
            'braves_chat_settings',
            'braves_chat_exclusions_section'
        );
        
        // ==================== SECCIÓN DISPONIBILIDAD ====================
        add_settings_section(
            'braves_chat_availability_section',
            __('Availability Schedule', 'braveschat'),
            array($this, 'availability_section_callback'),
            'braves_chat_settings'
        );
        
        // Availability Enabled
        register_setting('braves_chat_settings', $this->option_prefix . 'availability_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => array($this, 'sanitize_checkbox'),
            'default' => false
        ));
        
        add_settings_field(
            'availability_enabled',
            __('Enable Schedule', 'braveschat'),
            array($this, 'availability_enabled_callback'),
            'braves_chat_settings',
            'braves_chat_availability_section'
        );
        
        // Availability Start
        register_setting('braves_chat_settings', $this->option_prefix . 'availability_start', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_time'),
            'default' => '09:00'
        ));
        
        add_settings_field(
            'availability_start',
            __('Start Time', 'braveschat'),
            array($this, 'availability_start_callback'),
            'braves_chat_settings',
            'braves_chat_availability_section'
        );
        
        // Availability End
        register_setting('braves_chat_settings', $this->option_prefix . 'availability_end', array(
            'type' => 'string',
            'sanitize_callback' => array($this, 'sanitize_time'),
            'default' => '18:00'
        ));
        
        add_settings_field(
            'availability_end',
            __('End Time', 'braveschat'),
            array($this, 'availability_end_callback'),
            'braves_chat_settings',
            'braves_chat_availability_section'
        );
        
        // Availability Timezone
        register_setting('braves_chat_settings', $this->option_prefix . 'availability_timezone', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'Europe/Madrid'
        ));
        
        add_settings_field(
            'availability_timezone',
            __('Timezone', 'braveschat'),
            array($this, 'availability_timezone_callback'),
            'braves_chat_settings',
            'braves_chat_availability_section'
        );
        
        // Availability Message
        register_setting('braves_chat_settings', $this->option_prefix . 'availability_message', array(
            'type' => 'string',
            'sanitize_callback' => 'wp_kses_post',
            'default' => __('Our business hours are from 9:00 to 18:00. Leave us your message and we will get back to you as soon as possible.', 'braveschat')
        ));
        
        add_settings_field(
            'availability_message',
            __('Offline Message', 'braveschat'),
            array($this, 'availability_message_callback'),
            'braves_chat_settings',
            'braves_chat_availability_section'
        );

        // ==================== SECCIÓN GDPR/COOKIES ====================
        add_settings_section(
            'braves_chat_gdpr_section',
            __('GDPR / Cookies Compliance', 'braveschat'),
            array($this, 'gdpr_section_callback'),
            'braves_chat_settings'
        );

        // GDPR Enabled
        register_setting('braves_chat_settings', $this->option_prefix . 'gdpr_enabled', array(
            'type' => 'boolean',
            'sanitize_callback' => array($this, 'sanitize_checkbox'),
            'default' => false
        ));

        add_settings_field(
            'gdpr_enabled',
            __('Enable GDPR Banner', 'braveschat'),
            array($this, 'gdpr_enabled_callback'),
            'braves_chat_settings',
            'braves_chat_gdpr_section'
        );

        // GDPR Message
        register_setting('braves_chat_settings', $this->option_prefix . 'gdpr_message', array(
            'type' => 'string',
            'sanitize_callback' => 'wp_kses_post',
            'default' => __('This site uses cookies to improve your experience and provide a personalized chat service. By continuing to browse, you accept our cookie policy.', 'braveschat')
        ));

        add_settings_field(
            'gdpr_message',
            __('Banner Message', 'braveschat'),
            array($this, 'gdpr_message_callback'),
            'braves_chat_settings',
            'braves_chat_gdpr_section'
        );

        // GDPR Accept Text
        register_setting('braves_chat_settings', $this->option_prefix . 'gdpr_accept_text', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => __('Accept', 'braveschat')
        ));

        add_settings_field(
            'gdpr_accept_text',
            __('Accept Button Text', 'braveschat'),
            array($this, 'gdpr_accept_text_callback'),
            'braves_chat_settings',
            'braves_chat_gdpr_section'
        );

        // ==================== ESTADÍSTICAS ====================
        register_setting('braves_chat_settings', $this->option_prefix . 'stats_webhook_url', array(
            'type'              => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default'           => '',
        ));

        register_setting('braves_chat_settings', $this->option_prefix . 'stats_api_key', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ));

        register_setting('braves_chat_settings', $this->option_prefix . 'agent_name', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ));
    }
    
    // ==================== CALLBACKS DE SECCIONES ====================

    /**
     * Callback para sección General
     *
     * @since 1.0.0
     * @return void
     */
    public function general_section_callback() {
        echo '<p>' . esc_html__('Configure general chat settings.', 'braveschat') . '</p>';
    }

    /**
     * Callback para sección Exclusiones
     *
     * @since 1.0.0
     * @return void
     */
    public function exclusions_section_callback() {
        echo '<p>' . esc_html__('Select the pages where you do NOT want to show the chat widget.', 'braveschat') . '</p>';
    }

    /**
     * Callback para sección Disponibilidad
     *
     * @since 1.0.0
     * @return void
     */
    public function availability_section_callback() {
        echo '<p>' . esc_html__('Configure chat availability schedule.', 'braveschat') . '</p>';
    }

    /**
     * Callback para sección GDPR
     *
     * @since 1.1.0
     * @return void
     */
    public function gdpr_section_callback() {
        echo '<p>' . esc_html__('Configure the cookie consent banner to comply with GDPR regulations. The system uses persistent cookies with browser fingerprinting to uniquely identify users.', 'braveschat') . '</p>';
    }
    
    // ==================== CALLBACKS DE CAMPOS ====================
    
    public function global_enable_callback() {
        $value = get_option($this->option_prefix . 'global_enable', false);
        printf(
            '<label><input type="checkbox" name="%s" value="1" %s /> %s</label>',
            esc_attr($this->option_prefix . 'global_enable'),
            checked(1, $value, false),
            esc_html__('Show the chat on all pages of the site', 'braveschat')
        );
    }

    public function webhook_url_callback() {
        $value = get_option($this->option_prefix . 'webhook_url');
        printf(
            '<input type="url" name="%s" value="%s" class="regular-text" placeholder="https://flow.braveslab.com/webhook/..." /><p class="description">%s</p>',
            esc_attr($this->option_prefix . 'webhook_url'),
            esc_attr($value),
            esc_html__('N8N webhook URL to process messages.', 'braveschat')
        );
    }

    /**
     * ========== TAREA 2A: CALLBACK PARA TOKEN N8N ==========
     */
    public function n8n_auth_token_callback() {
        $value = get_option($this->option_prefix . 'n8n_auth_token', '');
        ?>
        <input 
            type="password" 
            name="<?php echo esc_attr($this->option_prefix . 'n8n_auth_token'); ?>" 
            value="<?php echo esc_attr($value); ?>" 
            class="regular-text"
            autocomplete="new-password"
            placeholder="••••••••••••••••"
        />
        <p class="description">
            <?php esc_html_e('Secret token to authenticate requests to the N8N webhook (Header Auth X-N8N-Auth). Leave empty if you do not use authentication.', 'braveschat'); ?>
        </p>
        <p class="description">
            <strong><?php esc_html_e('Important:', 'braveschat'); ?></strong>
            <?php esc_html_e('This token will be sent in every webhook request to verify it comes from the plugin.', 'braveschat'); ?>
        </p>
        <?php
    }
    
    public function header_title_callback() {
        $value = get_option($this->option_prefix . 'header_title');
        printf(
            '<input type="text" name="%s" value="%s" class="regular-text" />',
            esc_attr($this->option_prefix . 'header_title'),
            esc_attr($value)
        );
    }
    
    public function header_subtitle_callback() {
        $value = get_option($this->option_prefix . 'header_subtitle');
        printf(
            '<input type="text" name="%s" value="%s" class="regular-text" />',
            esc_attr($this->option_prefix . 'header_subtitle'),
            esc_attr($value)
        );
    }

    public function header_status_text_callback() {
        $value = get_option($this->option_prefix . 'header_status_text');
        printf(
            '<input type="text" name="%s" value="%s" class="regular-text" placeholder="%s" /><p class="description">%s</p>',
            esc_attr($this->option_prefix . 'header_status_text'),
            esc_attr($value),
            esc_attr__('Ex: Chatting with Charlie', 'braveschat'),
            esc_html__('Text displayed with animation next to the avatar.', 'braveschat')
        );
    }
    
    public function welcome_message_callback() {
        $value = get_option($this->option_prefix . 'welcome_message');
        printf(
            '<textarea name="%s" rows="4" class="large-text">%s</textarea>',
            esc_attr($this->option_prefix . 'welcome_message'),
            esc_textarea($value)
        );
    }
    
    public function position_callback() {
        $value = get_option($this->option_prefix . 'position');
        $positions = array(
            'bottom-right' => __('Bottom Right', 'braveschat'),
            'bottom-left' => __('Bottom Left', 'braveschat'),
            'center' => __('Center', 'braveschat')
        );
        
        echo '<select name="' . esc_attr($this->option_prefix . 'position') . '">';
        foreach ($positions as $key => $label) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($key),
                selected($value, $key, false),
                esc_html($label)
            );
        }
        echo '</select>';
    }
    
    public function display_mode_callback() {
        $value = get_option($this->option_prefix . 'display_mode');
        $modes = array(
            'modal' => __('Modal (Popup)', 'braveschat'),
            'fullscreen' => __('Fullscreen', 'braveschat')
        );
        
        echo '<select name="' . esc_attr($this->option_prefix . 'display_mode') . '">';
        foreach ($modes as $key => $label) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($key),
                selected($value, $key, false),
                esc_html($label)
            );
        }
        echo '</select>';
    }
    
    public function bubble_text_callback() {
        $value = get_option($this->option_prefix . 'bubble_text', __('Voice chat', 'braveschat'));
        printf(
            '<input type="text" name="%s" value="%s" class="regular-text" placeholder="%s" />',
            esc_attr($this->option_prefix . 'bubble_text'),
            esc_attr($value),
            esc_attr(__('Voice chat', 'braveschat'))
        );
        echo '<p class="description">' . esc_html__('Text displayed next to the bubble image (for Braves skin only).', 'braveschat') . '</p>';
    }
    
    public function excluded_pages_callback() {
        $excluded = get_option($this->option_prefix . 'excluded_pages', array());
        $pages = get_pages();
        
        echo '<select name="' . esc_attr($this->option_prefix . 'excluded_pages') . '[]" multiple size="10" style="width: 300px;">';
        foreach ($pages as $page) {
            printf(
                '<option value="%d" %s>%s</option>',
                esc_attr($page->ID),
                in_array($page->ID, (array)$excluded) ? 'selected' : '',
                esc_html($page->post_title)
            );
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('Hold Ctrl (Cmd on Mac) to select multiple pages.', 'braveschat') . '</p>';
    }
    
    public function availability_enabled_callback() {
        $value = get_option($this->option_prefix . 'availability_enabled', false);
        printf(
            '<label><input type="checkbox" name="%s" value="1" %s /> %s</label>',
            esc_attr($this->option_prefix . 'availability_enabled'),
            checked(1, $value, false),
            esc_html__('Enable schedule restriction', 'braveschat')
        );
    }

    public function availability_start_callback() {
        $value = get_option($this->option_prefix . 'availability_start');
        printf(
            '<input type="time" name="%s" value="%s" />',
            esc_attr($this->option_prefix . 'availability_start'),
            esc_attr($value)
        );
    }
    
    public function availability_end_callback() {
        $value = get_option($this->option_prefix . 'availability_end');
        printf(
            '<input type="time" name="%s" value="%s" />',
            esc_attr($this->option_prefix . 'availability_end'),
            esc_attr($value)
        );
    }
    
    public function availability_timezone_callback() {
        $value = get_option($this->option_prefix . 'availability_timezone');
        $timezones = timezone_identifiers_list();
        
        echo '<select name="' . esc_attr($this->option_prefix . 'availability_timezone') . '">';
        foreach ($timezones as $timezone) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($timezone),
                selected($value, $timezone, false),
                esc_html($timezone)
            );
        }
        echo '</select>';
    }
    
    public function availability_message_callback() {
        $value = get_option($this->option_prefix . 'availability_message');
        printf(
            '<textarea name="%s" rows="4" class="large-text">%s</textarea>',
            esc_attr($this->option_prefix . 'availability_message'),
            esc_textarea($value)
        );
    }

    public function gdpr_enabled_callback() {
        $value = get_option($this->option_prefix . 'gdpr_enabled', false);
        printf(
            '<label><input type="checkbox" name="%s" value="1" %s /> %s</label><p class="description">%s</p>',
            esc_attr($this->option_prefix . 'gdpr_enabled'),
            checked(1, $value, false),
            esc_html__('Show cookie consent banner', 'braveschat'),
            esc_html__('When enabled, a consent banner will be shown before creating cookies. Consent is saved in localStorage.', 'braveschat')
        );
    }

    public function gdpr_message_callback() {
        $value = get_option($this->option_prefix . 'gdpr_message');
        printf(
            '<textarea name="%s" rows="4" class="large-text">%s</textarea><p class="description">%s</p>',
            esc_attr($this->option_prefix . 'gdpr_message'),
            esc_textarea($value),
            esc_html__('Message displayed in the cookie banner. Explain the use of cookies for the chat session.', 'braveschat')
        );
    }

    public function gdpr_accept_text_callback() {
        $value = get_option($this->option_prefix . 'gdpr_accept_text');
        printf(
            '<input type="text" name="%s" value="%s" class="regular-text" /><p class="description">%s</p>',
            esc_attr($this->option_prefix . 'gdpr_accept_text'),
            esc_attr($value),
            esc_html__('Button text to accept cookies (e.g., "Accept", "Got it", "I agree").', 'braveschat')
        );
    }

    // ==================== FUNCIONES DE SANITIZACIÓN ====================

    /**
     * Sanitizar campo de posición del chat
     *
     * @since 1.0.0
     * @param string $value Valor a sanitizar
     * @return string Valor sanitizado
     */
    public function sanitize_position($value) {
        $allowed = array('bottom-right', 'bottom-left', 'center');
        return in_array($value, $allowed) ? $value : 'bottom-right';
    }





    /**
     * Sanitizar modo de visualización
     *
     * @since 1.0.0
     * @param string $value Valor a sanitizar
     * @return string Valor sanitizado
     */
    public function sanitize_display_mode($value) {
        $allowed = array('modal', 'fullscreen', 'mixed');
        return in_array($value, $allowed) ? $value : 'modal';
    }

    /**
     * Sanitizar icono del chat
     *
     * @since 1.2.3
     * @param string $value Valor a sanitizar
     * @return string Icono sanitizado
     */
    public function sanitize_chat_icon($value) {
        $allowed = array('robot-chat', 'chat-circle', 'chat-happy', 'chat-burbble');
        return in_array($value, $allowed) ? $value : 'robot-chat';
    }

    /**
     * Sanitizar páginas excluidas
     *
     * @since 1.0.0
     * @param array|mixed $value Valor a sanitizar
     * @return array Array de IDs de páginas sanitizados
     */
    public function sanitize_excluded_pages($value) {
        if (!is_array($value)) {
            return array();
        }
        return array_map('absint', $value);
    }

    /**
     * Sanitizar checkbox (convertir a 1 o 0)
     *
     * @since 1.0.0
     * @param mixed $value Valor a sanitizar
     * @return int 1 si está marcado, 0 en caso contrario
     */
    public function sanitize_checkbox($value) {
        return $value == 1 ? 1 : 0;
    }

    /**
     * Sanitizar hora en formato HH:MM
     *
     * @since 1.0.0
     * @param string $value Hora a sanitizar
     * @return string Hora sanitizada en formato HH:MM
     */
    public function sanitize_time($value) {
        if (preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $value)) {
            return $value;
        }
        return '09:00';
    }
    
    // ==================== RENDERIZADO DE PÁGINA ====================

    /**
     * Renderizar página de ajustes
     *
     * Carga el template de ajustes con diseño Bentō
     *
     * @since 1.0.0
     * @return void
     */
    public function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Cargar template de settings con diseño Bentō
        require_once BRAVES_CHAT_PLUGIN_DIR . 'includes/admin/templates/settings.php';
    }

    /**
     * Encolar assets CSS y JS del admin
     *
     * Carga estilos y scripts solo en páginas de BravesChat
     *
     * @since 1.0.0
     * @param string $hook Identificador de la página actual del admin
     * @return void
     */
    public function enqueue_admin_assets($hook) {
        // Load on both dashboard and settings pages
        // NOTA: Ajustamos los slugs para coincidir con el registro actual
        if (!in_array($hook, array('toplevel_page_braves-chat-ia', 'braveschat-ia_page_braves-chat-settings'))) {
            // Nota: Al cambiar 'wland-chat-ia' a 'braves-chat-ia', el hook cambia.
            // Para ser seguros, incluimos ambos o el nuevo.
            // El hook 'toplevel_page_braves-chat-ia' se genera automáticamente.
            // Si el slug era 'wland-chat-ia', era 'toplevel_page_wland-chat-ia'.
            // Ahora 'braves-chat-ia' -> 'toplevel_page_braves-chat-ia'.
        }
        
        // Mejor lógica: verificar si contiene nuestro slug
        if (strpos($hook, 'braveschat') === false) {
             return;
        }

        // Enqueue WordPress components styles
        wp_enqueue_style('wp-components');

        // Enqueue nuevo sistema CSS modular (v1.2.0)
        wp_enqueue_style(
            'braves-admin-variables',
            BRAVES_CHAT_PLUGIN_URL . 'assets/css/admin/variables.css',
            array(),
            BRAVES_CHAT_VERSION
        );

        wp_enqueue_style(
            'braves-admin-base',
            BRAVES_CHAT_PLUGIN_URL . 'assets/css/admin/base.css',
            array('braves-admin-variables'),
            BRAVES_CHAT_VERSION
        );

        wp_enqueue_style(
            'braves-admin-components',
            BRAVES_CHAT_PLUGIN_URL . 'assets/css/admin/components.css',
            array('braves-admin-base'),
            BRAVES_CHAT_VERSION
        );

        wp_enqueue_style(
            'braves-admin-dashboard',
            BRAVES_CHAT_PLUGIN_URL . 'assets/css/admin/dashboard.css',
            array('braves-admin-components'),
            BRAVES_CHAT_VERSION
        );

        // Enqueue admin settings script (for all plugin pages)
        wp_enqueue_script(
            'braves-admin-settings',
            BRAVES_CHAT_PLUGIN_URL . 'assets/js/admin_settings.js',
            array(),
            BRAVES_CHAT_VERSION,
            true
        );

        // Enqueue media uploader para todas las páginas de Braves Chat
        if (strpos($hook, 'braveschat') !== false) {
            wp_enqueue_media();
            wp_enqueue_script(
                'braves-admin-media-uploader',
                BRAVES_CHAT_PLUGIN_URL . 'assets/js/admin_media_uploader.js',
                array('jquery'),
                BRAVES_CHAT_VERSION,
                true
            );
        }

        // Enqueue settings-specific styles
        if (strpos($hook, 'braveschat-settings') !== false) {
            wp_enqueue_style(
                'braves-admin-settings',
                BRAVES_CHAT_PLUGIN_URL . 'assets/css/admin/settings.css',
                array('braves-admin-dashboard'),
                BRAVES_CHAT_VERSION
            );
        }

        // Keep existing admin script if needed
        if (file_exists(BRAVES_CHAT_PLUGIN_DIR . 'assets/js/admin.js')) {
            wp_enqueue_script(
                'braves-chat-admin',
                BRAVES_CHAT_PLUGIN_URL . 'assets/js/admin.js',
                array('jquery', 'wp-i18n'),
                BRAVES_CHAT_VERSION,
                true
            );
            wp_set_script_translations( 'braves-chat-admin', 'braveschat', BRAVES_CHAT_PLUGIN_DIR . 'languages' );
        }

        // Auth type toggle script (previously inline in settings.php template)
        if (strpos($hook, 'braveschat-settings') !== false) {
            $auth_config = array(
                'nonce'   => wp_create_nonce( 'braves_save_auth_type' ),
                'fieldId' => 'braves_chat_n8n_auth_type',
                'labels'  => array(
                    'none'   => array(
                        'show'        => false,
                        'headerLabel' => '',
                        'headerHelp'  => '',
                        'tokenLabel'  => '',
                        'tokenHelp'   => '',
                    ),
                    'header' => array(
                        'show'        => true,
                        'headerLabel' => __( 'Header name', 'braveschat' ),
                        'headerHelp'  => __( 'E.g., X-N8N-Auth. Must match the "Header Name" configured in N8N → Header Auth.', 'braveschat' ),
                        'tokenLabel'  => __( 'Token value', 'braveschat' ),
                        'tokenHelp'   => __( 'Secret token sent as the header value.', 'braveschat' ),
                    ),
                    'basic'  => array(
                        'show'        => true,
                        'headerLabel' => __( 'Username', 'braveschat' ),
                        'headerHelp'  => __( 'Must match the "User" field in N8N → Basic Auth.', 'braveschat' ),
                        'tokenLabel'  => __( 'Password', 'braveschat' ),
                        'tokenHelp'   => __( 'Must match the "Password" field in N8N → Basic Auth.', 'braveschat' ),
                    ),
                ),
            );
            wp_add_inline_script(
                'braves-admin-settings',
                'var bravesAuthConfig = ' . wp_json_encode( $auth_config ) . ';',
                'before'
            );
            wp_add_inline_script(
                'braves-admin-settings',
                '(function() {
    var authNonce = bravesAuthConfig.nonce;
    var labels    = bravesAuthConfig.labels;

    function bravesUpdateAuthLabels(type) {
        var l    = labels[type] || labels.header;
        var card = document.getElementById(\'braves-auth-credentials-card\');

        if (card) card.closest(\'.braves-card\').style.display = l.show ? \'\' : \'none\';

        var el = function(id) { return document.getElementById(id); };
        if (el(\'braves-auth-header-label\')) el(\'braves-auth-header-label\').textContent = l.headerLabel;
        if (el(\'braves-auth-header-help\'))  el(\'braves-auth-header-help\').textContent  = l.headerHelp;
        if (el(\'braves-auth-token-label\'))  el(\'braves-auth-token-label\').textContent  = l.tokenLabel;
        if (el(\'braves-auth-token-help\'))   el(\'braves-auth-token-help\').textContent   = l.tokenHelp;

        fetch(ajaxurl, {
            method: \'POST\',
            headers: { \'Content-Type\': \'application/x-www-form-urlencoded\' },
            body: new URLSearchParams({
                action:    \'braves_save_auth_type\',
                nonce:     authNonce,
                auth_type: type
            })
        });
    }

    window.bravesUpdateAuthLabels = bravesUpdateAuthLabels;

    document.addEventListener(\'DOMContentLoaded\', function() {
        var sel = document.getElementById(bravesAuthConfig.fieldId);
        if (sel) bravesUpdateAuthLabels(sel.value);
    });
})();'
            );
        }
    }
}
