<?php
if (!defined('ABSPATH')) {
    exit;
}

class GW_Elementor_Plugin
{

    private static $instance = null;
    public $dashboard_instance = null;
    public $emails_instance = null; // Nueva propiedad para la gestión de correos
    public $forms_instance = null; // NUEVA PROPIEDAD - Formularios
    public $reports_instance = null; // NUEVA PROPIEDAD - Informes
    public $settings_instance = null; // NUEVA PROPIEDAD
    public $email_settings_instance = null; // NUEVA PROPIEDAD - Configuración de Correo
    public $license_instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        $this->license_instance = new GW_Elementor_License();

        // Hooks de Admin
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_general_assets']);
        add_action('admin_head', [$this, 'custom_menu_icon_color']);

        // Registramos la acción del Cron
        add_action('gw_daily_spam_cleanup', [$this, 'run_daily_cleanup']);

        // Si no está programado, lo programamos para mañana
        if (!wp_next_scheduled('gw_daily_spam_cleanup')) {
            wp_schedule_event(time(), 'daily', 'gw_daily_spam_cleanup');
        }

        // INTERCEPTOR DE SPAM (Lista Negra -> Papelera)
        add_action('elementor_pro/forms/new_record', [$this, 'intercept_spam_submission'], 10, 2);

        // ---------------------------------------

        // CARGAMOS SI TIENE LICENCIA REAL *O* SI ESTÁ EN PERIODO DE PRUEBA
        if ($this->license_instance->is_active()) {
            new GW_Elementor_Tracker();
            if (is_admin()) {
                $this->dashboard_instance = GW_Analytics_Dashboard::get_instance();
                // Instanciamos la nueva clase de gestión de correos
                $this->emails_instance = GW_Analytics_Emails::get_instance();
                // INSTANCIAR FORMULARIOS
                $this->forms_instance = new GW_Analytics_Forms();
                // INSTANCIAR INFORMES
                $this->reports_instance = new GW_Analytics_Reports();
                // INSTANCIAR AJUSTES AQUÍ
                $this->settings_instance = new GW_Analytics_Settings();
                // INSTANCIAR CONFIGURACIÓN DE CORREO
                $this->email_settings_instance = new GW_Analytics_Email_Settings();
            }
        }
    }

    /**
     * Inyecta estilos del icono y el PRE-CARGADOR del Dark Mode para evitar parpadeos.
     */
    public function custom_menu_icon_color()
    {
        ?>
        <style>
            /* Estado Normal: Icono Fuxia */
            #toplevel_page_gw-elementor .wp-menu-image::before {
                color: #ff00ff !important;
            }

            /* Estado Hover/Activo: Blanco */
            #toplevel_page_gw-elementor:hover .wp-menu-image::before,
            #toplevel_page_gw-elementor.wp-has-current-submenu .wp-menu-image::before {
color: #fff !important;
            }

            /* Pre-cargador Full Width Mode - Evita parpadeo */
            body.gw-fullwidth-mode #wpcontent {
                margin-left: 0 !important;
                padding-left: 0 !important;
            }

            body.gw-fullwidth-mode #adminmenuback,
            body.gw-fullwidth-mode #adminmenuwrap {
                display: none !important;
            }

            body.gw-fullwidth-mode .gw-nav-tab-wrapper {
                top: 0;
                margin: 0;
                border-radius: 0;
            }

            body.gw-fullwidth-mode .wrap {
                margin: 0 !important;
                padding: 0 20px 20px 20px;
            }
            
            /* Pre-cargador Dark Mode - Estilos críticos inline para evitar flash */
            <?php
            // Verificar si está en modo oscuro desde localStorage (usando JavaScript inline)
            ?>
        </style>
        <script>
            // Aplicar estilos del menú inmediatamente si está en modo oscuro (síncrono)
            try {
                if (localStorage.getItem('efa_theme') === 'dark') {
                    var menuDarkCss = '#adminmenuback, #adminmenuwrap, #adminmenu, #adminmenu li { background-color: #1d2327 !important; } #adminmenu a, #adminmenu .wp-submenu a { color: #b4b9be !important; } #adminmenu .wp-submenu { background-color: #1d2327 !important; } #adminmenu li:hover, #adminmenu li.opensub { background-color: #2c3338 !important; } #adminmenu li.current { background-color: #2271b1 !important; } #adminmenu li.current a { color: #fff !important; }';
                    document.write('<style>' + menuDarkCss + '</style>');
                }
            } catch(e) {}
        </script>

        <script>
            (function () {
                // --- PRE-CARGADOR FULL WIDTH MODE (Anti-Flash) ---
                try {
                    if (localStorage.getItem('gw_fullwidth_mode') === '1') {
                        // Aplicar estilos críticos inmediatamente con document.write (síncrono)
                        var fullWidthCss = '';
                        fullWidthCss += 'body.gw-fullwidth-mode #wpcontent { margin-left: 0 !important; padding-left: 0 !important; }';
                        fullWidthCss += 'body.gw-fullwidth-mode #adminmenuback, body.gw-fullwidth-mode #adminmenuwrap { display: none !important; visibility: hidden !important; }';
                        fullWidthCss += 'body.gw-fullwidth-mode .gw-nav-tab-wrapper { top: 0; margin: 0; border-radius: 0; }';
                        fullWidthCss += 'body.gw-fullwidth-mode .wrap { margin: 0 !important; padding: 0 20px 20px 20px; }';
                        
                        // Inyectar estilos de forma síncrona
                        document.write('<style>' + fullWidthCss + '</style>');
                        
                        // Aplicar clase al body cuando esté disponible
                        if (document.body) {
                            document.body.classList.add('gw-fullwidth-mode');
                        } else {
                            // Usar evento inmediato cuando el body esté listo
                            (function checkBody() {
                                if (document.body) {
                                    document.body.classList.add('gw-fullwidth-mode');
                                } else {
                                    setTimeout(checkBody, 0);
                                }
                            })();
                        }
                    }
                } catch (e) { }
                
                // --- PRE-CARGADOR DARK MODE (Anti-Flash Completo) ---
                try {
                    var localTheme = localStorage.getItem('efa_theme');
                    if (localTheme === 'dark') {
                        // 1. Clase Global en HTML y BODY inmediatamente
                        document.documentElement.classList.add('efa-dark-mode');
                        
                        // Aplicar clase al body cuando esté disponible (recursivo para asegurar)
                        (function checkBody() {
                            if (document.body) {
                                document.body.classList.add('efa-dark-mode');
                            } else {
                                setTimeout(checkBody, 0);
                            }
                        })();

                        // 2. Estilos Críticos Instantáneos (SOLO si tiene la clase html.efa-dark-mode)
                        var darkCss = '';

                        // Fondo principal y Textos
                        darkCss += 'html.efa-dark-mode body, html.efa-dark-mode body.toplevel_page_gw-elementor, html.efa-dark-mode body[class*="page_gw-elementor"] { background-color: #141b2d !important; color: #e0e0e0; }';

                        // Menú lateral de WordPress (evitar flash blanco) - PRIORIDAD MÁXIMA
                        darkCss += '#adminmenuback, #adminmenuwrap { background-color: #1d2327 !important; }';
                        darkCss += '#adminmenu { background-color: #1d2327 !important; }';
                        darkCss += '#adminmenu li { background-color: #1d2327 !important; }';
                        darkCss += '#adminmenu a { color: #b4b9be !important; }';
                        darkCss += '#adminmenu .wp-submenu { background-color: #1d2327 !important; }';
                        darkCss += '#adminmenu .wp-submenu a { color: #b4b9be !important; }';
                        darkCss += '#adminmenu li:hover, #adminmenu li.opensub { background-color: #2c3338 !important; }';
                        darkCss += '#adminmenu li.current { background-color: #2271b1 !important; }';
                        darkCss += '#adminmenu li.current a { color: #fff !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenuback, html.efa-dark-mode #adminmenuwrap { background-color: #1d2327 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu { background-color: #1d2327 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu li { background-color: #1d2327 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu a { color: #b4b9be !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu .wp-submenu { background-color: #1d2327 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu .wp-submenu a { color: #b4b9be !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu li:hover, html.efa-dark-mode #adminmenu li.opensub { background-color: #2c3338 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu li.current { background-color: #2271b1 !important; }';
                        darkCss += 'html.efa-dark-mode #adminmenu li.current a { color: #fff !important; }';

                        // Menú superior del plugin
                        darkCss += 'html.efa-dark-mode .gw-nav-tab-wrapper { background-color: #1f2940 !important; border-bottom: 1px solid #3a3a5e !important; }';
                        darkCss += 'html.efa-dark-mode .gw-nav-tab { color: #a0a0c0 !important; }';

                        // Títulos
                        darkCss += 'html.efa-dark-mode .gw-settings-header h2, html.efa-dark-mode .gw-tutorial-hero h2, html.efa-dark-mode .efa-page-title-row h2, html.efa-dark-mode h2, html.efa-dark-mode h3 { color: #ffffff !important; }';

                        // Widgets y Contenedores (Aquí estaba el problema, ahora tiene el prefijo)
                        var widgets = '.gw-card, .efa-card, .gw-step-card, .efa-kpi-card, .gw-tutorial-hero, .efa-history-wide, .efa-month-card, .efa-table-wrapper';
                        // Convertimos la lista de widgets para que cada uno tenga el prefijo html.efa-dark-mode
                        var scopedWidgets = widgets.split(', ').map(function (sel) { return 'html.efa-dark-mode ' + sel; }).join(', ');

                        darkCss += scopedWidgets + ' { background-color: #1f2940 !important; border-color: #3a3a5e !important; color: #a0a0c0 !important; }';

                        // Inyectar
                        document.write('<style>' + darkCss + '</style>');
                    }
                } catch (e) { }
            })();
        </script>
        <?php
    }

    public function enqueue_admin_general_assets($hook)
    {
        if (strpos($hook, 'gw-elementor') === false)
            return;
        // Actualizamos versión para forzar recarga de caché en navegadores
        $ver = '2.2.1';

        // Carga de estilos generales y script terminator
        wp_enqueue_style('gw-admin-main', GW_PLUGIN_URL . 'assets/css/admin-main.css', [], $ver);
        wp_enqueue_style('gw-admin-terminator', GW_PLUGIN_URL . 'assets/css/admin-terminator.css', [], $ver);
        wp_enqueue_script('gw-admin-terminator-js', GW_PLUGIN_URL . 'assets/js/admin-terminator.js', [], $ver, true);

        // Encolar jQuery UI Sortable para reordenar bloques
        wp_enqueue_script('jquery-ui-sortable', false, ['jquery', 'jquery-ui-core'], false, true);
        
        // Encolar media uploader para subir logos en ajustes
        wp_enqueue_media();
    }

    public function register_menu()
    {
        // Recuperamos el rol guardado en ajustes (por defecto admin)
        $role = get_option('efa_access_role', 'manage_options');
        $hide_tutorial = get_option('efa_hide_tutorial', '0');

        add_menu_page('GW Analytics', 'GW Analytics', $role, 'gw-elementor', [$this, 'render_main_page'], 'dashicons-chart-pie', 50);

        add_submenu_page('gw-elementor', 'Dashboard', 'Dashboard', $role, 'gw-elementor', [$this, 'render_main_page']);
        
        // Badge FULL en el menú si la licencia es FULL
        $license_type = get_option('gw_license_type', 'trial');
        $license_menu_title = 'Licencia';
        if ($license_type === 'full') {
            $license_menu_title = 'Licencia <span class="gw-full-badge">FULL</span>';
        }
        
        add_submenu_page('gw-elementor', 'Licencia', $license_menu_title, $role, 'gw-elementor-license', [$this, 'render_license_page']);
        
        // Agregar Tutorial al menú lateral solo si no está oculto
        if ($hide_tutorial !== '1') {
            add_submenu_page('gw-elementor', 'Tutorial', 'Tutorial', $role, 'gw-elementor-tutorial', [$this, 'render_tutorial_page']);
        }
        
        // Estilos para el badge FULL en el menú
        if ($license_type === 'full') {
            add_action('admin_head', function() {
                echo '<style>
                    .gw-full-badge {
                        display: inline-block;
                        background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
                        color: white;
                        padding: 2px 8px;
                        border-radius: 10px;
                        font-size: 10px;
                        font-weight: 700;
                        letter-spacing: 0.5px;
                        margin-left: 6px;
                        vertical-align: middle;
                        box-shadow: 0 2px 8px rgba(124, 58, 237, 0.4);
                        animation: gwBadgePulse 2s ease-in-out infinite;
                    }
                    
                    @keyframes gwBadgePulse {
                        0%, 100% { 
                            box-shadow: 0 2px 8px rgba(124, 58, 237, 0.4); 
                        }
                        50% { 
                            box-shadow: 0 4px 12px rgba(124, 58, 237, 0.6);
                        }
                    }
                </style>';
            });
        }
    }

    public function render_tutorial_page()
    {
        $_GET['tab'] = 'tutorial';
        $this->render_main_page();
    }

    public function render_license_page()
    {
        $_GET['tab'] = 'license';
        $this->render_main_page();
    }


    public function render_main_page()
    {
        $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'dashboard';
        $logo_url = GW_PLUGIN_URL . 'assets/img/logo.png';

        // Recuperamos la preferencia de ocultar tutorial
        $hide_tutorial = get_option('efa_hide_tutorial', '0');

        if (!$this->license_instance->is_active()) {
            $active_tab = 'license';
        }
        ?>

        <div class="wrap" style="margin:0 20px 0 0;">

            <?php
            // Banner de trial eliminado - La información se muestra en la página de Licencias
            ?>

            <div class="gw-nav-tab-wrapper">
                <div class="gw-nav-left">
                    <div class="gw-logo-container">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="GW Analytics" class="gw-logo">
                    </div>
                    
                    <?php if ($this->license_instance->is_active()): ?>
                        <nav class="gw-nav-menu">
                            <a href="?page=gw-elementor&tab=dashboard"
                                class="gw-nav-item <?php echo $active_tab == 'dashboard' ? 'gw-nav-active' : ''; ?>">
                                <span class="gw-nav-icon">
                                    <span class="dashicons dashicons-chart-bar"></span>
                                </span>
                                <span class="gw-nav-text">Dashboard</span>
                            </a>
                            <a href="?page=gw-elementor&tab=emails"
                                class="gw-nav-item <?php echo $active_tab == 'emails' ? 'gw-nav-active' : ''; ?>">
                                <span class="gw-nav-icon">
                                    <span class="dashicons dashicons-email"></span>
                                </span>
                                <span class="gw-nav-text">Correos</span>
                            </a>
                            <a href="?page=gw-elementor&tab=forms"
                                class="gw-nav-item <?php echo $active_tab == 'forms' ? 'gw-nav-active' : ''; ?>">
                                <span class="gw-nav-icon">
                                    <span class="dashicons dashicons-list-view"></span>
                                </span>
                                <span class="gw-nav-text">Formularios</span>
                            </a>
                            <a href="?page=gw-elementor&tab=reports"
                                class="gw-nav-item <?php echo $active_tab == 'reports' ? 'gw-nav-active' : ''; ?>">
                                <span class="gw-nav-icon">
                                    <span class="dashicons dashicons-media-document"></span>
                                </span>
                                <span class="gw-nav-text">Informes</span>
                            </a>

                            <div class="gw-nav-item gw-nav-item-dropdown <?php echo $active_tab == 'settings' ? 'gw-nav-active' : ''; ?>">
                                <a href="?page=gw-elementor&tab=settings&section=spam" class="gw-nav-link">
                                    <span class="gw-nav-icon">
                                        <span class="dashicons dashicons-admin-generic"></span>
                                    </span>
                                    <span class="gw-nav-text">Ajustes</span>
                                    <span class="dashicons dashicons-arrow-down-alt2" style="font-size: 12px; margin-left: 4px; transition: transform 0.3s ease;"></span>
                                </a>
                                <div class="gw-nav-dropdown">
                                    <a href="?page=gw-elementor&tab=settings&section=spam" class="gw-nav-dropdown-item <?php echo (isset($_GET['section']) && $_GET['section'] == 'spam') ? 'active' : ''; ?>">
                                        <span class="dashicons dashicons-shield" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        <span>Spam</span>
                                    </a>
                                    <a href="?page=gw-elementor&tab=settings&section=notas" class="gw-nav-dropdown-item <?php echo (isset($_GET['section']) && $_GET['section'] == 'notas') ? 'active' : ''; ?>">
                                        <span class="dashicons dashicons-tag" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        <span>Estados</span>
                                    </a>
                                    <a href="?page=gw-elementor&tab=settings&section=marketing" class="gw-nav-dropdown-item <?php echo (isset($_GET['section']) && $_GET['section'] == 'marketing') ? 'active' : ''; ?>">
                                        <span class="dashicons dashicons-chart-line" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        <span>Marketing</span>
                                    </a>
                                    <a href="?page=gw-elementor&tab=settings&section=correo" class="gw-nav-dropdown-item <?php echo (isset($_GET['section']) && $_GET['section'] == 'correo') ? 'active' : ''; ?>">
                                        <span class="dashicons dashicons-email-alt" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        <span>Correo</span>
                                    </a>
                                    <a href="?page=gw-elementor&tab=settings&section=otros" class="gw-nav-dropdown-item <?php echo (isset($_GET['section']) && $_GET['section'] == 'otros') ? 'active' : ''; ?>">
                                        <span class="dashicons dashicons-admin-settings" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        <span>Otros</span>
                                    </a>
                                </div>
                            </div>
                        </nav>
                    <?php endif; ?>
                </div>

                <div class="gw-nav-right">
                    <button class="gw-nav-action-btn" id="gw-fullwidth-toggle" title="Modo Pantalla Completa">
                        <span class="dashicons dashicons-editor-expand"></span>
                        <span class="gw-nav-action-text">Pantalla Completa</span>
                    </button>
                    <button class="gw-nav-action-btn efa-theme-switcher gw-theme-icon-btn" id="efa-theme-toggle" title="Cambiar Tema">
                        <span class="dashicons dashicons-lightbulb"></span>
                    </button>
                </div>
            </div>

            <div class="gw-content-area">
                <?php settings_errors('gw_license'); ?>

                <?php if ($active_tab === 'license'): ?>
                    <?php $this->license_instance->render_tab(); ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'dashboard'): ?>
                    <?php
                    if ($this->dashboard_instance) {
                        $this->dashboard_instance->render_admin_view();
                    }
                    ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'emails'): ?>
                    <?php
                    if ($this->emails_instance) {
                        $this->emails_instance->render_emails_view();
                    }
                    ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'forms'): ?>
                    <?php
                    if ($this->forms_instance) {
                        $this->forms_instance->render_tab();
                    }
                    ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'reports'): ?>
                    <?php
                    if ($this->reports_instance) {
                        $this->reports_instance->render_reports_view();
                    }
                    ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'tutorial' && $hide_tutorial !== '1'): ?>
                    <?php $this->render_tutorial(); ?>

                <?php elseif ($this->license_instance->is_active() && $active_tab === 'settings'): ?>
                    <?php
                    if ($this->settings_instance) {
                        $this->settings_instance->render_settings_view();
                    }
                    ?>

                <?php else: ?>
                    <?php if (!$this->license_instance->is_active()): ?>
                        <div class="notice notice-error inline" style="margin-top:20px; padding:20px;">
                            <h3>🔒 Periodo de prueba finalizado</h3>
                            <p>Para seguir viendo tus estadísticas y bloqueando spam, por favor activa una licencia válida.</p>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>

        <style>
            /* Menú Superior Rediseñado - Profesional y Moderno */
            .gw-nav-tab-wrapper {
                background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
                border-bottom: 2px solid #e5e7eb;
                padding: 0;
                margin: -20px -20px 30px -20px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
                position: sticky;
                top: 32px;
                z-index: 1000;
                transition: all 0.3s ease;
            }

            .gw-nav-left {
                display: flex;
                align-items: center;
                gap: 0;
                flex: 1;
            }

            .gw-logo-container {
                padding: 16px 24px;
                border-right: 1px solid #e5e7eb;
                background: rgba(255, 255, 255, 0.5);
            }

            .gw-logo {
                height: 50px;
                width: auto;
                display: block;
                transition: transform 0.3s ease;
            }

            .gw-logo:hover {
                transform: scale(1.05);
            }

            .gw-nav-menu {
                display: flex;
                align-items: center;
                gap: 4px;
                padding: 0 16px;
            }

            .gw-nav-item {
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 14px 20px;
                text-decoration: none;
                color: #6b7280;
                font-size: 14px;
                font-weight: 600;
                border-radius: 8px;
                transition: all 0.3s ease;
                position: relative;
                white-space: nowrap;
            }

            .gw-nav-item:hover {
                background: #f3f4f6;
                color: #1f2937;
                transform: translateY(-1px);
            }

            .gw-nav-item.gw-nav-active {
                background: linear-gradient(135deg, #ff1e76 0%, #cb2f86 100%);
                color: #ffffff;
                box-shadow: 0 4px 12px rgba(255, 30, 118, 0.3);
            }

            .gw-nav-icon {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .gw-nav-icon .dashicons {
                font-size: 20px;
                width: 20px;
                height: 20px;
            }

            .gw-nav-text {
                font-weight: 600;
            }

            /* Dropdown de Ajustes */
            .gw-nav-item-dropdown {
                position: relative;
                display: flex;
                align-items: center;
                gap: 10px;
                padding: 14px 20px;
                text-decoration: none;
                color: #6b7280;
                font-size: 14px;
                font-weight: 600;
                border-radius: 8px;
                transition: all 0.3s ease;
                white-space: nowrap;
            }

            .gw-nav-item-dropdown:hover {
                background: #f3f4f6;
                color: #1f2937;
                transform: translateY(-1px);
            }

            .gw-nav-item-dropdown.gw-nav-active {
                background: linear-gradient(135deg, #ff1e76 0%, #cb2f86 100%);
                color: #ffffff;
                box-shadow: 0 4px 12px rgba(255, 30, 118, 0.3);
            }

            .gw-nav-item-dropdown .gw-nav-link {
                display: flex;
                align-items: center;
                gap: 10px;
                text-decoration: none;
                color: inherit;
                width: 100%;
            }

            .gw-nav-item-dropdown:hover .gw-nav-link .dashicons-arrow-down-alt2 {
                transform: rotate(180deg);
            }

            .gw-nav-dropdown {
                position: absolute;
                top: 100%;
                left: 0;
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
                min-width: 200px;
                opacity: 0;
                visibility: hidden;
                transform: translateY(-10px);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                z-index: 1000;
                margin-top: 8px;
                padding: 8px 0;
                overflow: hidden;
            }

            .gw-nav-item-dropdown:hover .gw-nav-dropdown {
                opacity: 1;
                visibility: visible;
                transform: translateY(0);
            }

            .gw-nav-dropdown-item {
                display: flex;
                align-items: center;
                gap: 12px;
                padding: 12px 20px;
                text-decoration: none;
                color: #6b7280;
                font-size: 13px;
                font-weight: 500;
                transition: all 0.2s ease;
                border-left: 3px solid transparent;
            }

            .gw-nav-dropdown-item:hover {
                background: linear-gradient(90deg, rgba(255, 30, 118, 0.1) 0%, rgba(255, 30, 118, 0.05) 100%);
                color: #ff1e76;
                border-left-color: #ff1e76;
                padding-left: 24px;
            }

            .gw-nav-dropdown-item.active {
                background: linear-gradient(90deg, rgba(255, 30, 118, 0.15) 0%, rgba(255, 30, 118, 0.08) 100%);
                color: #ff1e76;
                border-left-color: #ff1e76;
                font-weight: 600;
            }

            .gw-nav-dropdown-item .dashicons {
                color: inherit;
                transition: all 0.2s ease;
            }

            .gw-nav-dropdown-item:hover .dashicons {
                transform: scale(1.1);
            }

            /* Dark Mode para dropdown */
            body.efa-dark-mode .gw-nav-dropdown {
                background: #1f2940;
                border-color: #3a3a4e;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
            }

            body.efa-dark-mode .gw-nav-dropdown-item {
                color: #9ca3af;
            }

            body.efa-dark-mode .gw-nav-dropdown-item:hover {
                background: linear-gradient(90deg, rgba(255, 30, 118, 0.2) 0%, rgba(255, 30, 118, 0.1) 100%);
                color: #ff6ba8;
            }

            body.efa-dark-mode .gw-nav-dropdown-item.active {
                background: linear-gradient(90deg, rgba(255, 30, 118, 0.25) 0%, rgba(255, 30, 118, 0.15) 100%);
                color: #ff6ba8;
            }

            .gw-nav-right {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 0 20px;
                border-left: 1px solid #e5e7eb;
            }

            .gw-nav-action-btn {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 10px 16px;
                background: transparent;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                color: #6b7280;
                font-size: 13px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                text-decoration: none;
            }

            .gw-nav-action-btn:hover {
                background: #f3f4f6;
                border-color: #cbd5e1;
                color: #1f2937;
                transform: translateY(-1px);
            }

            .gw-nav-action-btn .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
            }

            .gw-nav-action-text {
                display: inline-block;
            }

            /* Botón de tema solo con icono - sin texto */
            .gw-theme-icon-btn {
                padding: 10px !important;
                min-width: 40px !important;
                max-width: 40px !important;
                width: 40px !important;
                justify-content: center !important;
                gap: 0 !important;
            }

            /* Estilos base para el icono del tema - siempre bombilla */
            .gw-theme-icon-btn .dashicons {
                font-size: 20px !important;
                width: 20px !important;
                height: 20px !important;
                line-height: 20px !important;
                margin: 0 !important;
                display: inline-block !important;
            }

            /* Bombilla en modo claro - gris oscuro para que sea visible */
            .gw-theme-icon-btn .dashicons.dashicons-lightbulb {
                color: #4b5563 !important;
            }

            .gw-theme-icon-btn:hover .dashicons.dashicons-lightbulb {
                color: #1f2937 !important;
            }

            /* Bombilla en modo oscuro - amarillo/dorado (bombilla encendida) */
            body.efa-dark-mode .gw-theme-icon-btn .dashicons.dashicons-lightbulb,
            html.efa-dark-mode .gw-theme-icon-btn .dashicons.dashicons-lightbulb {
                color: #fbbf24 !important; /* Amarillo/dorado para bombilla en modo oscuro */
            }

            body.efa-dark-mode .gw-theme-icon-btn:hover .dashicons.dashicons-lightbulb,
            html.efa-dark-mode .gw-theme-icon-btn:hover .dashicons.dashicons-lightbulb {
                color: #fcd34d !important;
            }

            /* Ocultar cualquier texto en el botón de tema */
            .gw-theme-icon-btn .gw-nav-action-text,
            .gw-theme-icon-btn span:not(.dashicons) {
                display: none !important;
                visibility: hidden !important;
                width: 0 !important;
                height: 0 !important;
                overflow: hidden !important;
            }


            /* Modo Full Width */
            body.gw-fullwidth-mode {
                overflow-x: hidden;
            }

            body.gw-fullwidth-mode #wpcontent {
                margin-left: 0 !important;
                padding-left: 0 !important;
            }

            body.gw-fullwidth-mode #wpadminbar {
                z-index: 1001;
            }

            body.gw-fullwidth-mode #adminmenuback,
            body.gw-fullwidth-mode #adminmenuwrap {
                display: none !important;
            }

            body.gw-fullwidth-mode .gw-nav-tab-wrapper {
                top: 0;
                margin: 0;
                border-radius: 0;
            }

            body.gw-fullwidth-mode .wrap {
                margin: 0 !important;
                padding: 0 20px 20px 20px;
            }

            /* Estado activo del botón full width */
            .gw-nav-action-btn.gw-fullwidth-active {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: #ffffff;
                border-color: #667eea;
            }

            .gw-nav-action-btn.gw-fullwidth-active:hover {
                background: linear-gradient(135deg, #5568d3 0%, #6b46c1 100%);
            }

            /* Dark Mode para el menú */
            body.efa-dark-mode .gw-nav-tab-wrapper {
                background: linear-gradient(135deg, #1f2940 0%, #252b3a 100%);
                border-bottom-color: #3a3a4e;
            }

            body.efa-dark-mode .gw-logo-container {
                border-right-color: #3a3a4e;
                background: rgba(31, 41, 64, 0.5);
            }

            body.efa-dark-mode .gw-nav-menu {
                border-color: #3a3a4e;
            }

            body.efa-dark-mode .gw-nav-item {
                color: #9ca3af;
            }

            body.efa-dark-mode .gw-nav-item:hover {
                background: #2a2a3e;
                color: #e4e7eb;
            }

            body.efa-dark-mode .gw-nav-item.gw-nav-active {
                background: linear-gradient(135deg, #ff1e76 0%, #cb2f86 100%);
                color: #ffffff;
            }

            body.efa-dark-mode .gw-nav-right {
                border-left-color: #3a3a4e;
            }

            body.efa-dark-mode .gw-nav-action-btn {
                border-color: #3a3a4e;
                color: #9ca3af;
            }

            body.efa-dark-mode .gw-nav-action-btn:hover {
                background: #2a2a3e;
                border-color: #4a4a6a;
                color: #e4e7eb;
            }

            /* Responsive */
            @media (max-width: 1200px) {
                .gw-nav-action-text {
                    display: none;
                }

                .gw-nav-action-btn {
                    padding: 10px;
                }
            }

            @media (max-width: 768px) {
                .gw-nav-menu {
                    gap: 2px;
                    padding: 0 8px;
                }

                .gw-nav-item {
                    padding: 12px 12px;
                    font-size: 12px;
                }

                .gw-nav-text {
                    display: none;
                }

                .gw-logo {
                    height: 40px;
                }

                .gw-logo-container {
                    padding: 12px 16px;
                }
            }
        </style>

        <script>
        jQuery(document).ready(function($) {
            // Toggle Full Width Mode
            $('#gw-fullwidth-toggle').on('click', function(e) {
                e.preventDefault();
                $('body').toggleClass('gw-fullwidth-mode');
                
                const isFullWidth = $('body').hasClass('gw-fullwidth-mode');
                $(this).toggleClass('gw-fullwidth-active', isFullWidth);
                
                // Cambiar icono
                const icon = $(this).find('.dashicons');
                if (isFullWidth) {
                    icon.removeClass('dashicons-editor-expand').addClass('dashicons-editor-contract');
                    $(this).find('.gw-nav-action-text').text('Salir Pantalla Completa');
                } else {
                    icon.removeClass('dashicons-editor-contract').addClass('dashicons-editor-expand');
                    $(this).find('.gw-nav-action-text').text('Pantalla Completa');
                }
                
                // Guardar preferencia
                localStorage.setItem('gw_fullwidth_mode', isFullWidth ? '1' : '0');
            });

            // Restaurar estado full width si estaba activo
            if (localStorage.getItem('gw_fullwidth_mode') === '1') {
                $('body').addClass('gw-fullwidth-mode');
                $('#gw-fullwidth-toggle').addClass('gw-fullwidth-active');
                $('#gw-fullwidth-toggle .dashicons').removeClass('dashicons-editor-expand').addClass('dashicons-editor-contract');
                $('#gw-fullwidth-toggle .gw-nav-action-text').text('Salir Pantalla Completa');
            }

            // El icono del tema se maneja en admin-dashboard.js para evitar conflictos
        });
        </script>
        <?php
    }

    // --- FUNCIÓN TUTORIAL LIMPIA (SIN CABECERA DUPLICADA) ---
    public function render_tutorial()
    {
        $img_path = GW_PLUGIN_URL . 'assets/img/tutorial/';
        ?>
        <div class="gw-tutorial-wrap">

            <div class="gw-tutorial-hero" style="margin-top: 0;">
                <h2>Configuración en 4 Pasos</h2>
                <p>Para que el Dashboard analice tus datos, necesitamos conectar tus formularios de Elementor con el sistema.
                    Solo tienes que hacerlo una vez.</p>
            </div>

            <div class="gw-step-card">
                <div class="gw-step-header">
                    <div class="gw-step-badge">1</div>
                    <div class="gw-step-title">
                        <h3>Abre tu Formulario</h3>
                        <p>Entra en el editor de Elementor, haz clic sobre tu formulario y despliega la sección
                            <strong>Contenido > Campos del formulario</strong>.
                        </p>
                    </div>
                </div>
                <div class="gw-step-image">
                    <img src="<?php echo $img_path; ?>step-1-edit.png" alt="Editar formulario Elementor"
                        class="gw-img-placeholder">
                </div>
            </div>

            <div class="gw-step-card">
                <div class="gw-step-header">
                    <div class="gw-step-badge">2</div>
                    <div class="gw-step-title">
                        <h3>Añade los Campos de Rastreo</h3>
                        <p>Debes añadir <strong>4 campos nuevos</strong>. Asegúrate de seleccionar el Tipo: <strong>Hidden
                                (Oculto)</strong> para que el usuario no los vea.</p>
                    </div>
                </div>
                <div class="gw-step-image">
                    <img src="<?php echo $img_path; ?>step-2-fields.png" alt="Añadir campos ocultos" class="gw-img-placeholder">
                </div>
            </div>

            <div class="gw-step-card">
                <div class="gw-step-header">
                    <div class="gw-step-badge">3</div>
                    <div class="gw-step-title">
                        <h3>Asigna los IDs (CRUCIAL)</h3>
                        <p>Para que el plugin sepa qué guardar, debes ir a la pestaña <strong>AVANZADO</strong> de cada campo y
                            cambiar el <strong>ID</strong> copiando exactamente los textos de esta tabla:</p>
                        <div class="gw-table-container">
                            <table class="gw-field-table">
                                <thead>
                                    <tr>
                                        <th>Campo</th>
                                        <th>Tipo Requerido</th>
                                        <th>ID (Copiar y Pegar)</th>
                                        <th>¿Qué hace?</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><strong>Origen</strong></td>
                                        <td>Hidden</td>
                                        <td><code class="gw-code">origen</code></td>
                                        <td>Captura si vienen de Google, Facebook o tráfico directo.</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Landing URL</strong></td>
                                        <td>Hidden</td>
                                        <td><code class="gw-code">landing_url</code></td>
                                        <td>Guarda la primera página que visitaron.</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Prev URL</strong></td>
                                        <td>Hidden</td>
                                        <td><code class="gw-code">prev_url</code></td>
                                        <td>Guarda la página anterior al formulario.</td>
                                    </tr>
                                    <tr>
                                        <td><strong>Current URL</strong></td>
                                        <td>Hidden</td>
                                        <td><code class="gw-code">current_url</code></td>
                                        <td>Guarda la página donde se ha realizado la conversión.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="gw-step-image">
                    <img src="<?php echo $img_path; ?>step-3-ids.png" alt="Configurar ID en avanzado"
                        class="gw-img-placeholder">
                </div>
            </div>

            <div class="gw-step-card">
                <div class="gw-step-header">
                    <div class="gw-step-badge">4</div>
                    <div class="gw-step-title">
                        <h3>¿Aceptación Comercial? (Opcional)</h3>
                        <p>Si necesitas que el usuario acepte explícitamente recibir publicidad para cumplir con el RGPD, añade
                            un campo visible.</p>
                        <div class="gw-note">
                            <strong>Configuración:</strong> Crea un campo tipo <strong>Aceptación (Acceptance)</strong> y en la
                            pestaña Avanzado pon el ID: <code class="gw-code">comercial</code>.
                        </div>
                    </div>
                </div>
                <div class="gw-step-image">
                    <img src="<?php echo $img_path; ?>step-4-commercial.png" alt="Campo comercial" class="gw-img-placeholder">
                </div>
            </div>

            <div class="gw-how-it-works-section">
                <div class="gw-hiw-header">
                    <h3>¿Y cómo funciona la magia? 🔮</h3>
                    <p>El proceso es totalmente invisible para tus usuarios, pero increíblemente potente para tu negocio.</p>
                </div>
                <div class="gw-process-grid">
                    <div class="gw-process-card">
                        <div class="gw-icon-circle"><span class="dashicons dashicons-megaphone"></span></div>
                        <h4>1. El Origen</h4>
                        <p>Cuando alguien llega desde un anuncio (Google/FB), detectamos la etiqueta <code>utm_source</code> al
                            instante.</p>
                    </div>
                    <div class="gw-process-card">
                        <div class="gw-icon-circle"><span class="dashicons dashicons-visibility"></span></div>
                        <h4>2. La Memoria</h4>
                        <p>El plugin "recuerda" ese origen mientras el usuario navega por tu web, sin usar cookies invasivas.
                        </p>
                    </div>
                    <div class="gw-process-card">
                        <div class="gw-icon-circle"><span class="dashicons dashicons-upload"></span></div>
                        <h4>3. El Envío</h4>
                        <p>Al rellenar el formulario, <strong>inyectamos</strong> esos datos en los campos ocultos
                            automáticamente.</p>
                    </div>
                    <div class="gw-process-card">
                        <div class="gw-icon-circle"><span class="dashicons dashicons-chart-pie"></span></div>
                        <h4>4. El Resultado</h4>
                        <p>Elementor guarda los datos y GW Analytics los convierte en las gráficas bonitas de tu Dashboard.</p>
                    </div>
                </div>
            </div>

            <div class="gw-tutorial-hero" style="margin-top: 0; padding: 30px; background: #f0f6fc; border: 1px solid #cce5ff;">
                <h3 style="margin-top:0;">¡Todo listo!</h3>
                <p style="font-size:16px;">Guarda los cambios en Elementor y limpia la caché de tu web. El sistema empezará a
                    rastrear datos automáticamente.</p>
            </div>
        </div>
        <?php
    }
    /**
     * INTERCEPTOR: Comprueba si el nuevo envío es de un email bloqueado.
     * Si es así, lo mueve directamente a la papelera.
     */
    public function intercept_spam_submission($record, $handler)
    {
        $raw_fields = $record->get('fields');
        $email = '';

        // Buscar campo email
        foreach ($raw_fields as $id => $field) {
            if (strpos(strtolower($id), 'email') !== false || strpos(strtolower($field['title']), 'email') !== false) {
                $email = $field['value'];
                break;
            }
            // Fallback: check value format
            if (is_email($field['value'])) {
                $email = $field['value'];
            }
        }

        if (empty($email))
            return;

        // Comprobar lista negra
        $blacklist_str = get_option('efa_spam_emails', '');
        if (empty($blacklist_str))
            return;

        $blacklist_arr = array_map('trim', explode(',', $blacklist_str));
        $is_blacklisted = false;
        $email_lower = strtolower(trim($email));

        foreach ($blacklist_arr as $blocked) {
            if (strtolower(trim($blocked)) === $email_lower) {
                $is_blacklisted = true;
                break;
            }
        }

        if ($is_blacklisted) {
            global $wpdb;
            $table = $wpdb->prefix . 'e_submissions';
            $table_values = $wpdb->prefix . 'e_submissions_values';

            // Buscamos el último ID insertado que coincida con este email
            // Esperamos un poco por si acaso la DB no ha terminado de escribir (aunque new_record suele ser post-write)
            // Pero PHP es síncrono.
            $submission_id = $wpdb->get_var($wpdb->prepare(
                "SELECT submission_id FROM $table_values 
                 WHERE value = %s 
                 ORDER BY id DESC LIMIT 1",
                $email
            ));

            if ($submission_id) {
                $wpdb->update($table, ['status' => 'trash'], ['id' => $submission_id]);
            }
        }
    }

    /**
     * TAREA AUTOMÁTICA: Limpieza de Spam/Papelera
     * Se ejecuta una vez al día por el WP-Cron.
     */
    public function run_daily_cleanup()
    {
        // 1. Recuperamos la configuración
        $days = (int) get_option('efa_autodelete_spam_days', 0);

        // Si es 0, está desactivado. No hacemos nada.
        if ($days <= 0)
            return;

        global $wpdb;
        $table_submissions = $wpdb->prefix . 'e_submissions';
        $table_values = $wpdb->prefix . 'e_submissions_values';

        // 2. Buscamos IDs que estén en la 'papelera' y sean viejos
        // status = 'trash' es donde van los emails cuando pulsas "Borrar Spam" o "Eliminar"
        $old_spam_ids = $wpdb->get_col($wpdb->prepare(
            "SELECT id FROM $table_submissions
           WHERE status = 'trash'
           AND created_at < DATE_SUB(NOW(), INTERVAL %d DAY)
           LIMIT 1000", // Límite de seguridad por si hay millones
            $days
        ));

        if (!empty($old_spam_ids)) {
            $ids_string = implode(',', array_map('intval', $old_spam_ids));

            // 3. Borramos sus valores (meta data)
            $wpdb->query("DELETE FROM $table_values WHERE submission_id IN ($ids_string)");

            // 4. Borramos los envíos principales
            $wpdb->query("DELETE FROM $table_submissions WHERE id IN ($ids_string)");
        }
    }

}
