<?php

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

/**
 * Class GW_Analytics_Forms
 * 
 * Gestiona la visualización y análisis de formularios de Elementor
 */
class GW_Analytics_Forms
{
    public function __construct()
    {
        // Constructor vacío, se usará para renderizar la pestaña
    }

    /**
     * Obtiene las etiquetas CRM configuradas
     */
    private function get_crm_labels()
    {
        $default_labels = [
            ['id' => 'new', 'label' => 'Nuevo', 'color' => '#2271b1'],
            ['id' => 'contacted', 'label' => 'Contactado', 'color' => '#f59e0b'],
            ['id' => 'budget', 'label' => 'Presupuesto', 'color' => '#9333ea'],
            ['id' => 'won', 'label' => 'Ganado', 'color' => '#16a34a'],
            ['id' => 'lost', 'label' => 'Perdido', 'color' => '#dc2626']
        ];
        return get_option('efa_crm_labels', $default_labels);
    }

    /**
     * Obtiene el color semántico de un origen
     */
    private function get_origin_color($origin)
    {
        $SEMANTIC_COLORS = [
            'facebook' => '#1877F2',
            'instagram' => '#E1306C',
            'google' => '#4285F4',
            'youtube' => '#FF0000',
            'ads' => '#EA4335',
            'organic' => '#34A853',
            'organico' => '#34A853',
            'seo' => '#34A853',
            'whatsapp' => '#25D366',
            'linkedin' => '#0A66C2',
            'tiktok' => '#000000',
            'email' => '#FBBC05',
            'newsletter' => '#FBBC05',
            'chatgpt' => '#000000',
            'directo' => '#646970',
            'referral' => '#A142F4'
        ];
        
        $FALLBACK_PALETTE = ['#0d9488', '#be123c', '#d97706', '#4338ca', '#a21caf', '#15803d', '#0369a1', '#b91c1c'];
        
        if (!$origin) return '#646970';
        
        $lower = strtolower(trim($origin));
        
        // Buscar coincidencia exacta
        if (isset($SEMANTIC_COLORS[$lower])) {
            return $SEMANTIC_COLORS[$lower];
        }
        
        // Buscar coincidencia parcial
        foreach ($SEMANTIC_COLORS as $key => $color) {
            if (strpos($lower, $key) !== false) {
                return $color;
            }
        }
        
        // Hash para color fallback
        $hash = 0;
        for ($i = 0; $i < strlen($origin); $i++) {
            $hash = ord($origin[$i]) + (($hash << 5) - $hash);
        }
        
        return $FALLBACK_PALETTE[abs($hash % count($FALLBACK_PALETTE))];
    }

    /**
     * Obtiene el color de un formulario (usando la misma lógica que orígenes)
     */
    private function get_form_color($form_name)
    {
        return $this->get_origin_color($form_name);
    }

    /**
     * Normaliza el nombre del origen (elimina .com, .es, capitaliza, etc)
     */
    private function normalize_origin($origin)
    {
        if (empty($origin)) {
            return 'Organico';
        }
        
        // Convertir a minúsculas primero
        $origin = strtolower(trim($origin));
        
        // Reemplazos específicos
        $replacements = [
            'organico' => 'Organico',
            'directo' => 'Directo',
            'google' => 'Google',
            'facebook' => 'Facebook',
            'instagram' => 'Instagram',
            'twitter' => 'Twitter',
            'linkedin' => 'LinkedIn',
            'youtube' => 'Youtube',
            'bing' => 'Bing',
            'yahoo' => 'Yahoo',
            'pinterest' => 'Pinterest',
            'tiktok' => 'TikTok',
        ];
        
        // Eliminar extensiones comunes (.com, .es, .net, etc)
        $origin = preg_replace('/\.(com|es|net|org|co|uk|io|mx|ar|cl|pe|ve|uy|py|bo|ec|gt|hn|ni|cr|pa|do|cu|pr|sv)$/i', '', $origin);
        
        // Eliminar www.
        $origin = str_replace('www.', '', $origin);
        
        // Verificar si hay un reemplazo específico
        if (isset($replacements[$origin])) {
            return $replacements[$origin];
        }
        
        // Capitalizar la primera letra
        return ucfirst($origin);
    }

    /**
     * Verifica si un email está en la lista blanca
     */
    private function is_whitelisted($email)
    {
        $email_lower = strtolower(trim($email));
        $whitelist_str = get_option('efa_whitelist_emails', '');

        if (empty($whitelist_str))
            return false;

        $whitelist_arr = array_map('trim', explode(',', $whitelist_str));

        foreach ($whitelist_arr as $allowed) {
            if (empty($allowed))
                continue;
            $allowed = strtolower($allowed);

            // Si empieza por '@' es un dominio
            if (strpos($allowed, '@') === 0) {
                if (substr($email_lower, -strlen($allowed)) === $allowed)
                    return true;
            }
            // Si no, es un email exacto
            elseif ($allowed === $email_lower) {
                return true;
            }
        }
        return false;
    }

    /**
     * Verifica si un email está bloqueado por TLD o lista negra
     */
    private function is_hard_banned($email)
    {
        $email_lower = strtolower(trim($email));

        // Verificar TLDs bloqueados
        $tlds_str = get_option('efa_spam_tlds', '.ru, .cn, .pl');
        $tlds_arr = array_map('trim', explode(',', $tlds_str));
        foreach ($tlds_arr as $tld) {
            if (empty($tld))
                continue;
            if (stripos($email_lower, strtolower($tld)) !== false)
                return true;
        }

        // Verificar lista negra de emails
        $blocked_emails_str = get_option('efa_spam_emails', '');
        $blocked_emails_arr = array_map('trim', explode(',', $blocked_emails_str));
        foreach ($blocked_emails_arr as $blocked_email) {
            if (strtolower($blocked_email) === $email_lower)
                return true;
        }

        return false;
    }

    /**
     * Detecta riesgo de spam basándose en texto, nombre y email
     */
    private function detect_spam_risk($text, $name, $email)
    {
        if (preg_match('/[0-9_]/', $name))
            return 2;
        if (strpos($name, 'http') !== false || strpos($name, 'www.') !== false)
            return 2;
        if (str_word_count($name) > 5)
            return 2;
        if (empty($text))
            return 0;
        if (preg_match('/[\x{0400}-\x{04FF}]/u', $text) || preg_match('/[\x{4E00}-\x{9FBF}]/u', $text)) {
            return 2;
        }

        $keywords_str = get_option('efa_spam_keywords', 'crypto, investment, wallet, forex, casino, bitcoin');
        $keywords_arr = array_map('trim', explode(',', $keywords_str));

        foreach ($keywords_arr as $word) {
            if (empty($word))
                continue;
            if (stripos($text, $word) !== false)
                return 2;
        }

        return 0;
    }

    /**
     * Obtiene todos los formularios
     */
    private function get_all_forms()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'e_submissions';
        $forms = $wpdb->get_col("SELECT DISTINCT form_name FROM $table WHERE status != 'trash' ORDER BY form_name ASC");
        return $forms;
    }

    /**
     * Calcula el spam de un formulario procesando cada submission
     */
    private function calculate_spam_count($form_name, $date_from = null, $date_to = null)
    {
        global $wpdb;
        $submissions_table = $wpdb->prefix . 'e_submissions';
        $values_table = $wpdb->prefix . 'e_submissions_values';
        
        // Construir filtro de fecha
        $date_filter = '';
        if ($date_from && $date_to) {
            $date_filter = $wpdb->prepare(" AND s.created_at >= %s AND s.created_at <= %s", $date_from, $date_to);
        }
        
        // Obtener todos los IDs del formulario
        $submission_ids = $wpdb->get_col($wpdb->prepare("
            SELECT s.id 
            FROM $submissions_table s
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $date_filter
        ", $form_name));
        
        if (empty($submission_ids)) {
            return 0;
        }
        
        $spam_count = 0;
        
        // Procesar en lotes de 100
        $chunks = array_chunk($submission_ids, 100);
        
        foreach ($chunks as $chunk_ids) {
            $ids_placeholder = implode(',', array_fill(0, count($chunk_ids), '%d'));
            $chunk_values = $wpdb->get_results($wpdb->prepare("
                SELECT submission_id, `key`, `value` 
                FROM $values_table 
                WHERE submission_id IN ($ids_placeholder)
            ", $chunk_ids));
            
            // Agrupar valores por submission_id
            $submissions_data = [];
            foreach ($chunk_values as $cv) {
                $submissions_data[$cv->submission_id][] = $cv;
            }
            
            foreach ($chunk_ids as $sid) {
                if (!isset($submissions_data[$sid]))
                    continue;
                
                $vals = $submissions_data[$sid];
                $name = '';
                $email = '';
                $full_text = '';
                $spam_override = null;
                
                foreach ($vals as $v) {
                    $k_lower = strtolower($v->key);
                    if (strpos($k_lower, 'name') !== false || strpos($k_lower, 'nombre') !== false)
                        $name = $v->value;
                    if (strpos($k_lower, 'email') !== false || strpos($k_lower, 'correo') !== false)
                        $email = $v->value;
                    if ($v->key === 'efa_spam_override')
                        $spam_override = $v->value;
                    
                    $full_text .= ' ' . $v->value;
                }
                
                $risk_score = 0;
                
                // 0. Whitelist
                if ($this->is_whitelisted($email)) {
                    $risk_score = 0;
                }
                // 1. Hard Ban
                elseif ($this->is_hard_banned($email)) {
                    $risk_score = 2;
                }
                // 2. Override
                elseif ($spam_override !== null) {
                    $risk_score = ($spam_override == '1' || $spam_override == '2') ? 2 : 0;
                }
                // 3. Auto Detect
                else {
                    $risk_score = $this->detect_spam_risk($full_text, $name, $email);
                }
                
                if ($risk_score === 2) {
                    $spam_count++;
                }
            }
        }
        
        return $spam_count;
    }

    /**
     * Obtiene datos de tendencia por origen para un formulario (estilo Dashboard)
     */
    private function get_form_trend_data($form_name, $date_from = null, $date_to = null)
    {
        global $wpdb;
        $submissions_table = $wpdb->prefix . 'e_submissions';
        $values_table = $wpdb->prefix . 'e_submissions_values';
        
        // Determinar rango de fechas
        $date_filter = '';
        if ($date_from && $date_to) {
            $date_filter = $wpdb->prepare(" AND s.created_at >= %s AND s.created_at <= %s", $date_from, $date_to);
        } else {
            // Si no hay filtro de fecha, obtener la fecha más antigua y la más reciente de este formulario
            $date_range = $wpdb->get_row($wpdb->prepare("
                SELECT 
                    MIN(created_at) as min_date,
                    MAX(created_at) as max_date
                FROM $submissions_table
                WHERE form_name = %s
                AND status != 'trash'
            ", $form_name));
            
            if ($date_range && $date_range->min_date && $date_range->max_date) {
                $date_from = $date_range->min_date;
                $date_to = $date_range->max_date;
            } else {
                // Fallback si no hay datos
                $date_to = date('Y-m-d 23:59:59');
                $date_from = date('Y-m-d 00:00:00', strtotime('-30 days'));
            }
        }
        
        // Construir el filtro de fecha para la query
        if (!$date_filter && $date_from && $date_to) {
            $date_filter = $wpdb->prepare(" AND s.created_at >= %s AND s.created_at <= %s", $date_from, $date_to);
        }
        
        // Filtro para excluir spam
        $spam_filter = " AND s.id NOT IN (
            SELECT submission_id FROM $values_table 
            WHERE `key` = 'efa_spam_override' AND value IN ('1', '2')
        )";
        
        // Calcular días en el rango para decidir agrupación
        $start_ts = strtotime($date_from);
        $end_ts = strtotime($date_to);
        $days_diff = ($end_ts - $start_ts) / 86400;
        
        // Si son más de 90 días, agrupar por semana; si no, por día
        $group_by_week = $days_diff > 90;
        
        if ($group_by_week) {
            // Agrupar por semana (YEARWEEK)
            $trend_data = $wpdb->get_results($wpdb->prepare("
                SELECT 
                    DATE(DATE_SUB(s.created_at, INTERVAL WEEKDAY(s.created_at) DAY)) as date,
                    COALESCE(v.value, 'Organico') as origin,
                    COUNT(*) as count
                FROM $submissions_table s
                LEFT JOIN $values_table v ON s.id = v.submission_id AND v.key IN ('origen', 'origin')
                WHERE s.form_name = %s
                AND s.status != 'trash'
                $spam_filter
                $date_filter
                GROUP BY YEARWEEK(s.created_at), v.value
                ORDER BY date ASC
            ", $form_name));
        } else {
            // Agrupar por día
            $trend_data = $wpdb->get_results($wpdb->prepare("
                SELECT 
                    DATE(s.created_at) as date,
                    COALESCE(v.value, 'Organico') as origin,
                    COUNT(*) as count
                FROM $submissions_table s
                LEFT JOIN $values_table v ON s.id = v.submission_id AND v.key IN ('origen', 'origin')
                WHERE s.form_name = %s
                AND s.status != 'trash'
                $spam_filter
                $date_filter
                GROUP BY DATE(s.created_at), v.value
                ORDER BY date ASC
            ", $form_name));
        }
        
        // Procesar datos: crear series por origen y normalizar
        $series_data = [];
        $all_dates = [];
        $origin_colors = [];
        
        // Asegurar que $date_from y $date_to estén definidos y formateados correctamente
        if (!$date_from || !$date_to) {
            return ['labels' => [], 'series' => [], 'colors' => []];
        }
        
        // Extraer solo la parte de fecha (sin hora) para crear el rango
        $start = new DateTime(date('Y-m-d', strtotime($date_from)));
        $end = new DateTime(date('Y-m-d', strtotime($date_to)));
        
        if ($group_by_week) {
            // Crear fechas semanales (lunes de cada semana)
            $interval = new DateInterval('P7D');
            
            // Ajustar inicio al lunes de esa semana
            $day_of_week = $start->format('N'); // 1 (lunes) a 7 (domingo)
            if ($day_of_week != 1) {
                $start->modify('-' . ($day_of_week - 1) . ' days');
            }
            
            $period = new DatePeriod($start, $interval, $end->modify('+7 days'));
            foreach ($period as $date) {
                $all_dates[] = $date->format('Y-m-d');
            }
        } else {
            // Crear fechas diarias
            $interval = new DateInterval('P1D');
            $period = new DatePeriod($start, $interval, $end->modify('+1 day'));
            foreach ($period as $date) {
                $all_dates[] = $date->format('Y-m-d');
            }
        }
        
        // Agrupar datos por origen normalizado
        foreach ($trend_data as $row) {
            $origin_raw = trim($row->origin);
            if (empty($origin_raw) || $origin_raw === 'NULL') {
                $origin_raw = 'Organico';
            }
            
            $origin_normalized = $this->normalize_origin($origin_raw);
            
            if (!isset($series_data[$origin_normalized])) {
                $series_data[$origin_normalized] = [];
                $origin_colors[$origin_normalized] = $this->get_origin_color($origin_normalized);
                
                // Inicializar todas las fechas con 0
                foreach ($all_dates as $date) {
                    $series_data[$origin_normalized][$date] = 0;
                }
            }
            
            $series_data[$origin_normalized][$row->date] += $row->count;
        }
        
        // Limitar a los 5 orígenes más importantes
        $origin_totals = [];
        foreach ($series_data as $origin => $dates) {
            $origin_totals[$origin] = array_sum($dates);
        }
        arsort($origin_totals);
        $top_origins = array_slice(array_keys($origin_totals), 0, 5);
        
        // Filtrar solo los top orígenes
        $filtered_series = [];
        foreach ($top_origins as $origin) {
            $filtered_series[$origin] = $series_data[$origin];
        }
        
        return [
            'labels' => $all_dates,
            'series' => $filtered_series,
            'colors' => $origin_colors,
            'grouped_by_week' => $group_by_week
        ];
    }

    /**
     * Obtiene métricas detalladas de un formulario específico
     */
    private function get_form_metrics($form_name, $date_from = null, $date_to = null)
    {
        global $wpdb;
        
        $submissions_table = $wpdb->prefix . 'e_submissions';
        $values_table = $wpdb->prefix . 'e_submissions_values';
        
        // Construir filtro de fecha
        $date_filter = '';
        if ($date_from && $date_to) {
            $date_filter = $wpdb->prepare(" AND s.created_at >= %s AND s.created_at <= %s", $date_from, $date_to);
        }
        
        // Total de envíos (sin filtro de spam todavía)
        $total = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM $submissions_table s
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $date_filter
        ", $form_name));
        
        // Calcular spam con las reglas completas
        $spam_count = $this->calculate_spam_count($form_name, $date_from, $date_to);
        
        // Filtro para excluir spam en las siguientes consultas
        $spam_filter = " AND s.id NOT IN (
            SELECT submission_id FROM $values_table 
            WHERE `key` = 'efa_spam_override' AND value IN ('1', '2')
        )";
        
        // Envíos de los últimos 30 días (excluyendo spam)
        $last_30_days = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM $submissions_table s
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            AND s.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            $date_filter
        ", $form_name));
        
        // Tasa de lectura (excluyendo spam)
        $read_count = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM $submissions_table s
            INNER JOIN $values_table v ON s.id = v.submission_id
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            AND v.key = 'efa_read_status'
            AND v.value = '1'
            $date_filter
        ", $form_name));
        
        // Distribución por origen (normalizado, excluyendo spam)
        $origins_raw = $wpdb->get_results($wpdb->prepare("
            SELECT 
                COALESCE(v.value, 'Organico') as origin,
                COUNT(*) as count
            FROM $submissions_table s
            LEFT JOIN $values_table v ON s.id = v.submission_id AND v.key IN ('origen', 'origin')
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            $date_filter
            GROUP BY v.value
            ORDER BY count DESC
        ", $form_name));
        
        // Normalizar orígenes
        $origins_grouped = [];
        foreach ($origins_raw as $origin_row) {
            $origin_value = trim($origin_row->origin);
            if (empty($origin_value) || $origin_value === 'NULL') {
                $origin_value = 'Organico';
            }
            
            $normalized = $this->normalize_origin($origin_value);
            if (!isset($origins_grouped[$normalized])) {
                $origins_grouped[$normalized] = 0;
            }
            $origins_grouped[$normalized] += $origin_row->count;
        }
        
        // Convertir a array de objetos con colores
        $origins = [];
        foreach ($origins_grouped as $origin_name => $count) {
            $origins[] = (object) [
                'origin' => $origin_name,
                'count' => $count,
                'color' => $this->get_origin_color($origin_name)
            ];
        }
        usort($origins, function($a, $b) {
            return $b->count - $a->count;
        });
        $origins = array_slice($origins, 0, 5);
        
        // Distribución por estado CRM (excluyendo spam)
        $crm_states_raw = $wpdb->get_results($wpdb->prepare("
            SELECT 
                COALESCE(v.value, 'new') as state,
                COUNT(*) as count
            FROM $submissions_table s
            LEFT JOIN $values_table v ON s.id = v.submission_id AND v.key = 'efa_crm_status'
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            $date_filter
            GROUP BY state
        ", $form_name));
        
        // Mapear estados a etiquetas visibles
        $crm_labels_map = [];
        $crm_labels = $this->get_crm_labels();
        foreach ($crm_labels as $label) {
            $crm_labels_map[$label['id']] = [
                'label' => $label['label'],
                'color' => $label['color']
            ];
        }
        
        // Crear array de estados con etiquetas visibles
        $crm_states = [];
        foreach ($crm_states_raw as $state_row) {
            $state_id = $state_row->state;
            $label_info = isset($crm_labels_map[$state_id]) ? $crm_labels_map[$state_id] : ['label' => ucfirst($state_id), 'color' => '#646970'];
            
            $crm_states[] = (object) [
                'state' => $label_info['label'],
                'state_id' => $state_id,
                'color' => $label_info['color'],
                'count' => $state_row->count
            ];
        }
        
        // Últimos 7 días (excluyendo spam)
        $last_7_days = $wpdb->get_results($wpdb->prepare("
            SELECT 
                DATE(s.created_at) as date,
                COUNT(*) as count
            FROM $submissions_table s
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            AND s.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
            $date_filter
            GROUP BY DATE(s.created_at)
            ORDER BY date ASC
        ", $form_name));
        
        // Páginas más populares (excluyendo spam)
        $top_pages = $wpdb->get_results($wpdb->prepare("
            SELECT 
                v.value as page,
                COUNT(*) as count
            FROM $submissions_table s
            INNER JOIN $values_table v ON s.id = v.submission_id
            WHERE s.form_name = %s
            AND s.status != 'trash'
            $spam_filter
            AND v.key = 'current_url'
            $date_filter
            GROUP BY v.value
            ORDER BY count DESC
            LIMIT 3
        ", $form_name));
        
        // Total excluyendo spam
        $total_clean = $total - $spam_count;
        
        return [
            'total' => $total_clean,
            'total_with_spam' => $total,
            'last_30_days' => $last_30_days,
            'spam_count' => $spam_count,
            'spam_rate' => $total > 0 ? round(($spam_count / $total) * 100, 1) : 0,
            'read_count' => $read_count,
            'read_rate' => $total_clean > 0 ? round(($read_count / $total_clean) * 100, 1) : 0,
            'origins' => $origins,
            'crm_states' => $crm_states,
            'last_7_days' => $last_7_days,
            'top_pages' => $top_pages,
            'avg_daily' => $last_30_days > 0 ? round($last_30_days / 30, 1) : 0
        ];
    }

    /**
     * Renderiza la pestaña de formularios
     */
    public function render_tab()
    {
        $all_forms = $this->get_all_forms();
        
        // Obtener filtros
        $selected_forms = isset($_POST['gw_forms_filter']) ? (array) $_POST['gw_forms_filter'] : [];
        $date_range = isset($_POST['gw_date_range']) ? sanitize_text_field($_POST['gw_date_range']) : 'last_month';
        $date_from_custom = isset($_POST['gw_date_from']) ? sanitize_text_field($_POST['gw_date_from']) : '';
        $date_to_custom = isset($_POST['gw_date_to']) ? sanitize_text_field($_POST['gw_date_to']) : '';

        // Calcular rango de fechas
        $date_from = null;
        $date_to = null;
        
        if ($date_range === 'custom' && !empty($date_from_custom) && !empty($date_to_custom)) {
            $date_from = $date_from_custom . ' 00:00:00';
            $date_to = $date_to_custom . ' 23:59:59';
        } elseif ($date_range !== 'all') {
            $date_to = date('Y-m-d 23:59:59');
            switch ($date_range) {
                case 'last_7_days':
                    $date_from = date('Y-m-d 00:00:00', strtotime('-7 days'));
                    break;
                case 'last_month':
                    $date_from = date('Y-m-d 00:00:00', strtotime('-30 days'));
                    break;
                case 'last_3_months':
                    $date_from = date('Y-m-d 00:00:00', strtotime('-3 months'));
                    break;
                case 'last_6_months':
                    $date_from = date('Y-m-d 00:00:00', strtotime('-6 months'));
                    break;
                case 'last_year':
                    $date_from = date('Y-m-d 00:00:00', strtotime('-1 year'));
                    break;
            }
        }

        // Filtrar formularios
        $forms_to_display = empty($selected_forms) ? $all_forms : array_intersect($all_forms, $selected_forms);

        // Calcular totales generales
        $total_submissions = 0;
        $total_spam = 0;
        $total_clean = 0;
        
        foreach ($forms_to_display as $form_name) {
            $metrics = $this->get_form_metrics($form_name, $date_from, $date_to);
            $total_submissions += $metrics['total_with_spam'];
            $total_spam += $metrics['spam_count'];
            $total_clean += $metrics['total'];
        }
        
        ?>
        <div class="gw-forms-container">
            
            <!-- Header mejorado -->
            <div class="gw-forms-header">
                <div class="gw-header-content">
                    <div class="gw-header-text">
                        <h1 class="gw-main-title">
                            <span class="gw-icon-wrapper">
                                <span class="dashicons dashicons-feedback"></span>
                            </span>
                            Análisis de Formularios
                        </h1>
                        <p class="gw-header-description">Métricas detalladas de rendimiento para cada formulario de Elementor instalado en tu sitio.</p>
                    </div>
                    <div class="gw-header-stats">
                        <div class="gw-stat-item">
                            <div class="gw-stat-value"><?php echo count($all_forms); ?></div>
                            <div class="gw-stat-label">Formularios</div>
                        </div>
                        <div class="gw-stat-item">
                            <div class="gw-stat-value"><?php echo $total_clean; ?></div>
                            <div class="gw-stat-label">Total Envíos</div>
                        </div>
                        <div class="gw-stat-item gw-stat-danger">
                            <div class="gw-stat-value"><?php echo $total_spam; ?></div>
                            <div class="gw-stat-label">Spam Detectado</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Filtros -->
            <div class="gw-card gw-forms-filters">
                <h3 class="gw-card-title">
                    <span class="dashicons dashicons-filter"></span>
                    Filtros
                </h3>
                <form method="POST" action="" class="filters-form" id="gw-forms-filter-form">
                    
                    <!-- Selector de formularios con checkboxes -->
                    <div class="efa-multiselect-wrapper" id="gw-form-wrapper">
                        <button type="button" class="efa-select-sm efa-multiselect-btn" id="gw-form-btn">
                            <span><?php echo empty($selected_forms) ? 'Formularios: Todos' : 'Formularios: ' . count($selected_forms); ?></span>
                            <span class="dashicons dashicons-arrow-down-alt2" style="font-size:12px; margin-left:5px;"></span>
                        </button>
                        <div class="efa-multiselect-dropdown" id="gw-form-dropdown">
                            <label class="efa-ms-option all">
                                <input type="checkbox" id="gw-form-all" <?php echo empty($selected_forms) ? 'checked' : ''; ?>> 
                                <strong>Seleccionar Todos</strong>
                            </label>
                            <div class="efa-ms-separator"></div>
                            <?php if (empty($all_forms)): ?>
                                <div style="padding:10px; color:#999; font-size:11px;">No hay formularios.</div>
                            <?php else:
                                foreach ($all_forms as $f): ?>
                                    <label class="efa-ms-option">
                                        <input type="checkbox" class="gw-form-check" name="gw_forms_filter[]" value="<?php echo esc_attr($f); ?>"
                                            <?php echo (empty($selected_forms) || in_array($f, $selected_forms)) ? 'checked' : ''; ?>>
                                        <?php echo esc_html($f); ?>
                                    </label>
                                <?php endforeach; 
                            endif; ?>
                        </div>
                    </div>

                    <!-- Selector de período (estilo multiselect) -->
                    <input type="hidden" name="gw_date_range" id="gw-date-range-value" value="<?php echo esc_attr($date_range); ?>">
                    <div class="efa-multiselect-wrapper" id="gw-date-wrapper">
                        <button type="button" class="efa-select-sm efa-multiselect-btn" id="gw-date-btn">
                            <span id="gw-date-label">
                                <?php 
                                $date_labels = [
                                    'last_7_days' => 'Últimos 7 días',
                                    'last_month' => 'Último mes',
                                    'last_3_months' => 'Últimos 3 meses',
                                    'last_6_months' => 'Últimos 6 meses',
                                    'last_year' => 'Último año',
                                    'all' => 'Todo el tiempo',
                                    'custom' => 'Personalizado'
                                ];
                                echo $date_labels[$date_range] ?? 'Todo el tiempo';
                                ?>
                            </span>
                            <span class="dashicons dashicons-arrow-down-alt2" style="font-size:12px; margin-left:5px;"></span>
                        </button>
                        <div class="efa-multiselect-dropdown" id="gw-date-dropdown">
                            <label class="efa-ms-option" data-value="last_7_days">
                                <input type="radio" name="date_range_radio" value="last_7_days" <?php checked($date_range, 'last_7_days'); ?>>
                                Últimos 7 días
                            </label>
                            <label class="efa-ms-option" data-value="last_month">
                                <input type="radio" name="date_range_radio" value="last_month" <?php checked($date_range, 'last_month'); ?>>
                                Último mes
                            </label>
                            <label class="efa-ms-option" data-value="last_3_months">
                                <input type="radio" name="date_range_radio" value="last_3_months" <?php checked($date_range, 'last_3_months'); ?>>
                                Últimos 3 meses
                            </label>
                            <label class="efa-ms-option" data-value="last_6_months">
                                <input type="radio" name="date_range_radio" value="last_6_months" <?php checked($date_range, 'last_6_months'); ?>>
                                Últimos 6 meses
                            </label>
                            <label class="efa-ms-option" data-value="last_year">
                                <input type="radio" name="date_range_radio" value="last_year" <?php checked($date_range, 'last_year'); ?>>
                                Último año
                            </label>
                            <label class="efa-ms-option" data-value="all">
                                <input type="radio" name="date_range_radio" value="all" <?php checked($date_range, 'all'); ?>>
                                Todo el tiempo
                            </label>
                            <div class="efa-ms-separator"></div>
                            <label class="efa-ms-option" data-value="custom">
                                <input type="radio" name="date_range_radio" value="custom" <?php checked($date_range, 'custom'); ?>>
                                Personalizado
                            </label>
                        </div>
                    </div>

                    <!-- Fechas personalizadas -->
                    <div id="gw-custom-dates" class="efa-filters" style="<?php echo $date_range === 'custom' ? 'display:flex;' : 'display:none;'; ?>">
                        <input type="date" name="gw_date_from" id="gw-start-date" value="<?php echo esc_attr($date_from_custom); ?>">
                        <span>a</span>
                        <input type="date" name="gw_date_to" id="gw-end-date" value="<?php echo esc_attr($date_to_custom); ?>">
                    </div>

                    <button type="submit" class="efa-btn efa-btn-sm">🔍 Aplicar Filtros</button>
                </form>
            </div>

            <?php $this->render_forms_grid($forms_to_display, $date_from, $date_to); ?>

        </div>

        <?php
        $this->render_styles();
        $this->render_scripts();
    }

    /**
     * Renderiza el grid de formularios
     */
    private function render_forms_grid($forms_to_display, $date_from, $date_to)
    {
        // Obtener métricas
        $forms_with_metrics = [];
        foreach ($forms_to_display as $form_name) {
            $metrics = $this->get_form_metrics($form_name, $date_from, $date_to);
            $trend_data = $this->get_form_trend_data($form_name, $date_from, $date_to);
            
            // Determinar performance
            $performance = 'low';
            if ($metrics['avg_daily'] >= 2) {
                $performance = 'high';
            } elseif ($metrics['avg_daily'] >= 0.5) {
                $performance = 'medium';
            }
            
            $forms_with_metrics[] = [
                'name' => $form_name,
                'metrics' => $metrics,
                'trend_data' => $trend_data,
                'performance' => $performance
            ];
        }

        // Mostrar formularios
        if (!empty($forms_with_metrics)):
        ?>
            <div class="gw-forms-grid">
                <?php foreach ($forms_with_metrics as $form_data): 
                    $form_name = $form_data['name'];
                    $metrics = $form_data['metrics'];
                    $performance = $form_data['performance'];
                    
                    $performance_icons = [
                        'high' => '🔥',
                        'medium' => '⚡',
                        'low' => '💤'
                    ];
                    
                    $performance_labels = [
                        'high' => 'Alto Rendimiento',
                        'medium' => 'Rendimiento Medio',
                        'low' => 'Bajo Rendimiento'
                    ];
                    
                    // Obtener color del formulario
                    $form_color = $this->get_form_color($form_name);
                ?>
                    <div class="form-card <?php echo $performance; ?>" style="border-left-color: <?php echo $form_color; ?>;">
                        <!-- Layout horizontal: Info a la izquierda, gráfica a la derecha -->
                        <div class="form-card-layout">
                            <!-- Columna izquierda: Info compacta -->
                            <div class="form-info-column">
                                <!-- Header -->
                                <div class="form-card-header">
                                    <div class="form-title-section">
                                        <h3 class="form-name" title="<?php echo esc_attr($form_name); ?>">
                                            <?php echo esc_html($form_name); ?>
                                        </h3>
                                        <div class="performance-badge <?php echo $performance; ?>">
                                            <?php echo $performance_icons[$performance]; ?> <?php echo $performance_labels[$performance]; ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Métricas principales (compactas) -->
                                <div class="form-metrics-compact">
                                    <div class="metric-compact primary">
                                        <div class="metric-value"><?php echo $metrics['total']; ?></div>
                                        <div class="metric-label">Total</div>
                                    </div>
                                    <div class="metric-compact">
                                        <div class="metric-value"><?php echo $metrics['avg_daily']; ?></div>
                                        <div class="metric-label">Promedio/día</div>
                                    </div>
                                    <div class="metric-compact">
                                        <div class="metric-value"><?php echo $metrics['last_30_days']; ?></div>
                                        <div class="metric-label">Últimos 30d</div>
                                    </div>
                                </div>

                                <!-- Indicadores compactos -->
                                <div class="compact-indicators">
                                    <div class="compact-indicator">
                                        <span class="indicator-icon">✅</span>
                                        <span class="indicator-text">Leídos: <strong><?php echo $metrics['read_count']; ?></strong></span>
                                    </div>
                                    <div class="compact-indicator spam-indicator">
                                        <span class="indicator-icon">🛡️</span>
                                        <span class="indicator-text">Spam: <strong><?php echo $metrics['spam_rate']; ?>%</strong></span>
                                    </div>
                                </div>

                                <!-- Estados CRM (compacto) -->
                                <?php if (!empty($metrics['crm_states'])): ?>
                                    <div class="compact-section">
                                        <div class="section-title-sm">🎯 Estados CRM</div>
                                        <div class="crm-pills-compact">
                                            <?php foreach (array_slice($metrics['crm_states'], 0, 3) as $state): ?>
                                                <div class="state-pill-sm" style="background: <?php echo $state->color; ?>20; border-color: <?php echo $state->color; ?>; color: <?php echo $state->color; ?>;">
                                                    <?php echo esc_html($state->state); ?>: <?php echo $state->count; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Columna derecha: Gráfica grande -->
                            <div class="form-chart-column">
                                <?php 
                                $trend_data = $form_data['trend_data'];
                                if (!empty($trend_data['series'])): 
                                    $chart_id = 'form-trend-' . sanitize_title($form_name);
                                ?>
                                    <div class="form-trend-chart-wide">
                                        <div class="chart-header">
                                            <span class="chart-title">📊 Tendencia por Origen</span>
                                            <?php if (!empty($metrics['origins'])): ?>
                                                <div class="chart-origins-compact">
                                                    <?php foreach (array_slice($metrics['origins'], 0, 3) as $origin): ?>
                                                        <div class="compact-item">
                                                            <span class="origin-dot" style="background-color: <?php echo $origin->color; ?>;"></span>
                                                            <span class="item-name"><?php echo esc_html($origin->origin); ?></span>
                                                            <span class="item-count"><?php echo $origin->count; ?></span>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <canvas id="<?php echo $chart_id; ?>" height="200"></canvas>
                                        <script type="application/json" class="trend-chart-data" data-chart-id="<?php echo $chart_id; ?>">
                                            <?php echo json_encode($trend_data); ?>
                                        </script>
                                    </div>
                                <?php else: ?>
                                    <div class="no-chart-message">
                                        <span style="font-size: 48px; opacity: 0.3;">📊</span>
                                        <p style="color: #9ca3af; font-size: 14px; margin: 10px 0 0 0;">Sin datos suficientes para gráfica</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <span class="empty-icon">🔍</span>
                <h3>No se encontraron formularios</h3>
                <p>Intenta ajustar los filtros o crear un nuevo formulario en Elementor.</p>
            </div>
        <?php endif;
    }

    /**
     * Renderiza los estilos CSS
     */
    private function render_styles()
    {
        ?>
        <style>
            /* Container principal */
            .gw-forms-container {
                max-width: 1600px;
                margin: 0 auto;
                padding: 15px 20px 30px 20px;
            }

            /* Header mejorado - Coherente con Informes y Ajustes */
            .gw-forms-header {
                margin-bottom: 30px;
                padding-bottom: 20px;
                border-bottom: 2px solid #e5e7eb;
            }

            .gw-header-content {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                gap: 30px;
                flex-wrap: wrap;
            }

            .gw-header-text {
                flex: 1;
                min-width: 300px;
            }

            .gw-main-title {
                font-size: 32px;
                font-weight: 700;
                margin: 0 0 8px 0;
                color: #1f2937;
                display: flex;
                align-items: center;
                gap: 15px;
            }

            .gw-icon-wrapper {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 48px;
                height: 48px;
                background: #e01d75;
                border-radius: 12px;
                color: white;
                flex-shrink: 0;
            }

            .gw-icon-wrapper .dashicons {
                font-size: 24px;
                width: 24px;
                height: 24px;
            }

            .gw-header-description {
                font-size: 16px;
                color: #6b7280;
                margin: 0;
                line-height: 1.6;
            }

            /* Stats en el header */
            .gw-header-stats {
                display: flex;
                gap: 24px;
                align-items: center;
            }

            .gw-stat-item {
                text-align: center;
                padding: 12px 24px;
                background: #f9fafb;
                border-radius: 12px;
                border: 2px solid #e5e7eb;
                min-width: 120px;
            }

            .gw-stat-item.gw-stat-danger {
                border-color: #fee2e2;
                background: #fef2f2;
            }

            .gw-stat-value {
                font-size: 28px;
                font-weight: 700;
                color: #1f2937;
                margin-bottom: 4px;
            }

            .gw-stat-item.gw-stat-danger .gw-stat-value {
                color: #dc2626;
            }

            .gw-stat-label {
                font-size: 12px;
                color: #6b7280;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                font-weight: 600;
            }

            /* Cards mejoradas - Coherente con Informes y Ajustes */
            .gw-card {
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 24px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
                margin-bottom: 24px;
            }

            .gw-card:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                transform: translateY(-2px);
            }

            .gw-card-title {
                font-size: 18px;
                font-weight: 600;
                margin: 0 0 20px 0;
                color: #1f2937;
                display: flex;
                align-items: center;
                gap: 10px;
                padding-bottom: 16px;
                border-bottom: 2px solid #f3f4f6;
            }

            .gw-card-title .dashicons {
                font-size: 20px;
                width: 20px;
                height: 20px;
                color: #e01d75;
            }

            /* Filtros */
            .gw-forms-filters {
                margin-bottom: 30px;
                position: relative;
                z-index: 50;
            }

            .filters-form {
                display: flex;
                gap: 15px;
                flex-wrap: wrap;
                align-items: center;
            }

            /* Multiselect styles (copied from emails page) */
            .efa-multiselect-wrapper {
                position: relative;
                display: inline-block;
                z-index: 100;
            }

            .efa-multiselect-wrapper.active {
                z-index: 1001;
            }

            .efa-multiselect-btn {
                padding: 10px 15px;
                background: white;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 14px;
                font-weight: 500;
                transition: all 0.2s;
                min-width: 200px;
                justify-content: space-between;
                color: #1f2937;
            }

            .efa-multiselect-btn:hover {
                border-color: #e01d75;
                background: #f9fafb;
            }

            .efa-multiselect-dropdown {
                display: none;
                position: absolute;
                top: 100%;
                left: 0;
                margin-top: 8px;
                background: white;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 10px 25px rgba(0,0,0,0.15);
                min-width: 100%;
                max-height: 400px;
                overflow-y: auto;
                z-index: 1002;
                padding: 8px 0;
            }

            #gw-date-dropdown {
                min-width: 220px;
            }

            .efa-multiselect-wrapper.active .efa-multiselect-dropdown {
                display: block;
            }

            .efa-ms-option {
                display: flex;
                align-items: center;
                padding: 10px 15px;
                cursor: pointer;
                font-size: 14px;
                transition: background 0.2s;
            }

            .efa-ms-option:hover {
                background: #f3f4f6;
            }

            .efa-ms-option input[type="checkbox"],
            .efa-ms-option input[type="radio"] {
                margin-right: 10px;
                cursor: pointer;
            }

            .efa-ms-option.all {
                background: #f9fafb;
                font-weight: 600;
            }

            .efa-ms-separator {
                height: 1px;
                background: #e5e7eb;
                margin: 8px 0;
            }

            .efa-select-sm {
                padding: 10px 15px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 14px;
                background: white;
                cursor: pointer;
                transition: all 0.2s;
            }

            .efa-select-sm:focus {
                outline: none;
                border-color: #e01d75;
                box-shadow: 0 0 0 3px rgba(224,29,117,0.1);
            }

            .efa-filters {
                display: flex;
                gap: 10px;
                align-items: center;
            }

            .efa-filters input[type="date"] {
                padding: 10px 15px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                font-size: 14px;
                transition: all 0.2s;
                background: white;
                font-weight: 500;
                color: #1f2937;
            }

            .efa-filters input[type="date"]:focus {
                outline: none;
                border-color: #e01d75;
                box-shadow: 0 0 0 3px rgba(224,29,117,0.1);
            }

            .efa-filters span {
                color: #6b7280;
                font-weight: 500;
            }

            .efa-btn {
                padding: 10px 20px;
                background: #e01d75;
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s;
            }

            .efa-btn:hover {
                background: #c41866;
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(224,29,117,0.3);
            }

            .efa-btn-sm {
                padding: 10px 20px;
            }

            /* Grid de formularios - Una columna */
            .gw-forms-grid {
                display: flex;
                flex-direction: column;
                gap: 20px;
                position: relative;
                z-index: 1;
            }

            /* Card de formulario - Layout horizontal */
            .form-card {
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-left: 4px solid;
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
                transition: all 0.3s ease;
                position: relative;
                overflow: hidden;
            }

            .form-card:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                transform: translateY(-2px);
            }

            /* Layout horizontal principal */
            .form-card-layout {
                display: flex;
                gap: 30px;
                align-items: stretch;
            }

            /* Columna izquierda - Info compacta (ancho fijo) */
            .form-info-column {
                width: 320px;
                flex-shrink: 0;
                display: flex;
                flex-direction: column;
                gap: 16px;
            }

            /* Columna derecha - Gráfica (ocupa todo el espacio disponible) */
            .form-chart-column {
                flex: 1;
                min-width: 0;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            /* Header compacto */
            .form-card-header {
                margin-bottom: 0;
            }

            .form-title-section {
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap: 10px;
            }

            .form-name {
                font-size: 18px;
                font-weight: 700;
                margin: 0;
                color: #1f2937;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                flex: 1;
            }

            .performance-badge {
                padding: 4px 10px;
                border-radius: 12px;
                font-size: 11px;
                font-weight: 700;
                white-space: nowrap;
                flex-shrink: 0;
            }

            .performance-badge.high {
                background: #dcfce7;
                color: #166534;
            }

            .performance-badge.medium {
                background: #fef3c7;
                color: #92400e;
            }

            .performance-badge.low {
                background: #f3f4f6;
                color: #4b5563;
            }

            /* Métricas compactas */
            .form-metrics-compact {
                display: flex;
                gap: 8px;
            }

            .metric-compact {
                flex: 1;
                background: #f9fafb;
                border-radius: 8px;
                padding: 10px 8px;
                text-align: center;
            }

            .metric-compact.primary {
                background: #e01d75;
                color: white;
            }

            .metric-compact .metric-value {
                font-size: 20px;
                font-weight: 700;
                margin-bottom: 4px;
            }

            .metric-compact .metric-label {
                font-size: 10px;
                opacity: 0.7;
                text-transform: uppercase;
                letter-spacing: 0.3px;
            }

            /* Indicadores compactos - Horizontal */
            .compact-indicators {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }

            .compact-indicator {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                padding: 8px 12px;
                background: #f9fafb;
                border-radius: 6px;
                font-size: 12px;
                flex: 1;
                white-space: nowrap;
            }

            .compact-indicator .indicator-icon {
                font-size: 16px;
            }

            .compact-indicator .indicator-text {
                color: #6b7280;
            }

            .compact-indicator strong {
                color: #1f2937;
            }

            .compact-indicator.spam-indicator {
                background: #faeded;
            }

            /* Secciones compactas */
            .compact-section {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }

            .section-title-sm {
                font-size: 11px;
                font-weight: 700;
                color: #6b7280;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                margin-bottom: 2px;
            }

            /* Contenedor de items en horizontal */
            .compact-section .compact-items-container {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }

            .compact-item {
                display: flex;
                align-items: center;
                gap: 6px;
                padding: 6px 10px;
                background: #f9fafb;
                border-radius: 6px;
                font-size: 12px;
                flex: 0 0 auto;
            }

            .origin-dot {
                width: 10px;
                height: 10px;
                border-radius: 50%;
                flex-shrink: 0;
            }

            .compact-item .item-name {
                color: #6b7280;
                font-weight: 500;
                white-space: nowrap;
            }

            .compact-item .item-count {
                font-weight: 700;
                color: #1f2937;
                font-size: 11px;
            }

            /* Estados CRM compactos */
            .crm-pills-compact {
                display: flex;
                flex-wrap: wrap;
                gap: 6px;
            }

            .state-pill-sm {
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 10px;
                font-weight: 600;
                border: 1.5px solid;
                white-space: nowrap;
            }

            /* Gráfica ancha */
            .form-trend-chart-wide {
                width: 100%;
                height: 100%;
                background: #f9fafb;
                padding: 20px 20px 0 20px;
                border-radius: 10px;
                display: flex;
                flex-direction: column;
            }

            .chart-header {
                margin-bottom: 15px;
                display: flex;
                flex-direction: column;
                gap: 12px;
            }

            .chart-title {
                font-size: 14px;
                font-weight: 700;
                color: #4b5563;
                text-transform: uppercase;
                letter-spacing: 0.5px;
            }

            .chart-origins-compact {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }

            .form-trend-chart-wide canvas {
                flex: 1;
                max-height: 200px;
            }

            /* Mensaje sin gráfica */
            .no-chart-message {
                text-align: center;
                padding: 40px;
                width: 100%;
            }

            /* Empty state */
            .empty-state {
                text-align: center;
                padding: 80px 20px;
                background: white;
                border-radius: 12px;
                border: 2px dashed #e5e7eb;
            }

            .empty-icon {
                font-size: 64px;
                display: block;
                margin-bottom: 20px;
            }

            .empty-state h3 {
                font-size: 24px;
                font-weight: 700;
                color: #1f2937;
                margin: 0 0 10px 0;
            }

            .empty-state p {
                font-size: 16px;
                color: #6b7280;
                margin: 0;
            }

            /* Responsive */
            @media (max-width: 1400px) {
                .form-info-column {
                    width: 280px;
                }
            }

            @media (max-width: 1200px) {
                .gw-header-content {
                    flex-direction: column;
                }

                .gw-header-stats {
                    width: 100%;
                    justify-content: space-between;
                }

                .form-card-layout {
                    flex-direction: column;
                }

                .form-info-column {
                    width: 100%;
                }

                .form-chart-column {
                    min-height: 250px;
                }
            }

            @media (max-width: 768px) {
                .gw-forms-header {
                    flex-direction: column;
                    text-align: center;
                }

                .gw-main-title {
                    font-size: 24px;
                }

                .gw-header-stats {
                    flex-direction: column;
                    gap: 12px;
                    width: 100%;
                }

                .gw-stat-item {
                    width: 100%;
                }

                .filters-form {
                    flex-direction: column;
                    gap: 12px;
                }

                .filters-form > * {
                    width: 100%;
                }

                .form-metrics-compact {
                    flex-direction: column;
                }

                .form-card {
                    padding: 15px;
                }
            }

            /* Dark Mode - Coherente con Informes y Ajustes */
            body.efa-dark-mode .gw-main-title {
                color: #e4e7eb !important;
            }

            body.efa-dark-mode .gw-header-description {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .gw-forms-header {
                border-bottom-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-card {
                background: #1f2940 !important;
                border-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-card-title {
                color: #e4e7eb !important;
                border-bottom-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-stat-item {
                background: #2a3a52 !important;
                border-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-stat-value {
                color: #e4e7eb !important;
            }

            body.efa-dark-mode .gw-stat-item.gw-stat-danger {
                background: #2a2a3e !important;
                border-color: #4a3a3e !important;
            }

            body.efa-dark-mode .gw-stat-label {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .efa-multiselect-btn,
            body.efa-dark-mode .efa-select-sm,
            body.efa-dark-mode .efa-filters input[type="date"] {
                background: #2a3a52;
                border-color: #3a3a4e;
                color: #e5e7eb;
            }

            body.efa-dark-mode .efa-multiselect-dropdown {
                background: #1f2940;
                border-color: #3a3a4e;
            }

            body.efa-dark-mode .efa-ms-option:hover {
                background: #2a3a52;
            }

            body.efa-dark-mode .efa-ms-option.all {
                background: #2a3a52;
            }

            body.efa-dark-mode .efa-filters input[type="date"] {
                background: #2a3a52 !important;
                border-color: #3a3a4e !important;
                color: #e5e7eb !important;
            }

            body.efa-dark-mode .efa-filters span {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .form-card {
                background: #1f2940;
                border-color: #3a3a4e;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            }

            body.efa-dark-mode .form-card:hover {
                box-shadow: 0 12px 40px rgba(0,0,0,0.5);
            }

            body.efa-dark-mode .form-name {
                color: #e5e7eb;
            }

            body.efa-dark-mode .metric-compact {
                background: #2a3a52;
            }

            body.efa-dark-mode .metric-compact .metric-value {
                color: #e5e7eb;
            }

            body.efa-dark-mode .metric-compact .metric-label {
                color: #9ca3af;
            }

            body.efa-dark-mode .compact-indicators {
                /* No hay estilos especiales para dark mode aquí */
            }

            body.efa-dark-mode .compact-indicator {
                background: #2a3a52;
            }

            body.efa-dark-mode .compact-indicator .indicator-text {
                color: #9ca3af;
            }

            body.efa-dark-mode .compact-indicator strong {
                color: #e5e7eb;
            }

            body.efa-dark-mode .compact-indicator.spam-indicator {
                background: #4a1f2a;
                border: 1px solid #8b2e44;
            }

            body.efa-dark-mode .section-title-sm {
                color: #9ca3af;
            }

            body.efa-dark-mode .compact-items-container {
                /* No hay estilos especiales para dark mode aquí */
            }

            body.efa-dark-mode .compact-item {
                background: #2a3a52;
            }

            body.efa-dark-mode .compact-item .item-name {
                color: #9ca3af;
            }

            body.efa-dark-mode .compact-item .item-count {
                color: #e5e7eb;
            }

            body.efa-dark-mode .form-trend-chart-wide {
                background: #2a3a52 !important;
            }

            body.efa-dark-mode .chart-title {
                color: #e5e7eb;
            }

            body.efa-dark-mode .chart-origins-compact {
                /* No hay estilos especiales para dark mode aquí */
            }

            body.efa-dark-mode .no-chart-message p {
                color: #6b7280 !important;
            }

            body.efa-dark-mode .empty-state {
                background: #1f2940 !important;
                color: #9ca3af !important;
                border-color: #3a3a4e !important;
            }

            body.efa-dark-mode .empty-state h3 {
                color: #e4e7eb !important;
            }

            @media (max-width: 768px) {
                .gw-forms-grid {
                    grid-template-columns: 1fr;
                }

                .gw-main-title {
                    font-size: 24px;
                }

                .gw-header-stats {
                    flex-direction: column;
                    gap: 12px;
                }

                .gw-stat-item {
                    width: 100%;
                }

                .filters-form {
                    flex-direction: column;
                    gap: 12px;
                }

                .filters-form > * {
                    width: 100%;
                }
            }
        </style>
        <?php
    }

    /**
     * Renderiza los scripts JavaScript
     */
    private function render_scripts()
    {
        ?>
        <script>
        jQuery(document).ready(function($) {
            // Funcionalidad de multiselects (formularios y fecha)
            $('#gw-form-btn').on('click', function(e) {
                e.stopPropagation();
                $('#gw-date-wrapper').removeClass('active');
                $('#gw-form-wrapper').toggleClass('active');
            });

            $('#gw-date-btn').on('click', function(e) {
                e.stopPropagation();
                $('#gw-form-wrapper').removeClass('active');
                $('#gw-date-wrapper').toggleClass('active');
            });

            $(document).on('click', function(e) {
                if (!$(e.target).closest('.efa-multiselect-wrapper').length) {
                    $('.efa-multiselect-wrapper').removeClass('active');
                }
            });

            // Seleccionar/Deseleccionar todos
            $('#gw-form-all').on('change', function() {
                const isChecked = $(this).is(':checked');
                $('.gw-form-check').prop('checked', isChecked);
                updateFormButtonText();
            });

            $('.gw-form-check').on('change', function() {
                const allChecked = $('.gw-form-check:checked').length === $('.gw-form-check').length;
                $('#gw-form-all').prop('checked', allChecked);
                updateFormButtonText();
            });

            function updateFormButtonText() {
                const checkedCount = $('.gw-form-check:checked').length;
                const totalCount = $('.gw-form-check').length;
                
                let text = 'Formularios: ';
                if (checkedCount === 0) {
                    text += 'Ninguno';
                } else if (checkedCount === totalCount) {
                    text += 'Todos';
                } else {
                    text += checkedCount;
                }
                
                $('#gw-form-btn span:first').text(text);
            }

            // Manejar selección de período
            $('input[name="date_range_radio"]').on('change', function() {
                const value = $(this).val();
                const labels = {
                    'last_7_days': 'Últimos 7 días',
                    'last_month': 'Último mes',
                    'last_3_months': 'Últimos 3 meses',
                    'last_6_months': 'Últimos 6 meses',
                    'last_year': 'Último año',
                    'all': 'Todo el tiempo',
                    'custom': 'Personalizado'
                };
                
                // Actualizar el input oculto
                $('#gw-date-range-value').val(value);
                
                // Actualizar el texto del botón
                $('#gw-date-label').text(labels[value]);
                
                // Mostrar/ocultar fechas personalizadas
                if (value === 'custom') {
                    $('#gw-custom-dates').show();
                } else {
                    $('#gw-custom-dates').hide();
                }
                
                // Cerrar el dropdown
                $('#gw-date-wrapper').removeClass('active');
            });

            // Animación de entrada
            $('.form-card').each(function(i) {
                $(this).css({
                    'opacity': '0',
                    'transform': 'translateY(20px)'
                });
                
                setTimeout(() => {
                    $(this).css({
                        'opacity': '1',
                        'transform': 'translateY(0)',
                        'transition': 'all 0.5s ease'
                    });
                }, i * 50);
            });

            // Inicializar gráficas de tendencia
            if (typeof Chart !== 'undefined') {
                $('.trend-chart-data').each(function() {
                    const chartId = $(this).data('chart-id');
                    const chartData = JSON.parse($(this).text());
                    
                    if (!chartData || !chartData.series || Object.keys(chartData.series).length === 0) {
                        return;
                    }
                    
                    const ctx = document.getElementById(chartId);
                    if (!ctx) return;
                    
                    // Preparar datasets para Chart.js
                    const datasets = [];
                    for (const [origin, data] of Object.entries(chartData.series)) {
                        const color = chartData.colors[origin] || '#646970';
                        datasets.push({
                            label: origin,
                            data: Object.values(data),
                            borderColor: color,
                            backgroundColor: color + '20',
                            borderWidth: 2,
                            fill: true,
                            tension: 0.4,
                            pointRadius: 3,
                            pointHoverRadius: 5
                        });
                    }
                    
                    // Formatear etiquetas de fechas
                    const isWeekly = chartData.grouped_by_week || false;
                    const labels = chartData.labels.map(date => {
                        const d = new Date(date);
                        if (isWeekly) {
                            // Para vistas semanales, mostrar "Sem. DD/MM"
                            return 'Sem. ' + d.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
                        } else {
                            // Para vistas diarias, solo "DD/MM"
                            return d.toLocaleDateString('es-ES', { day: 'numeric', month: 'short' });
                        }
                    });
                    
                    // Crear gráfica
                    const chart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: labels,
                            datasets: datasets
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    display: true,
                                    position: 'bottom',
                                    labels: {
                                        boxWidth: 12,
                                        padding: 10,
                                        font: {
                                            size: 11
                                        },
                                        color: $('body').hasClass('efa-dark-mode') ? '#e5e7eb' : '#4b5563'
                                    }
                                },
                                tooltip: {
                                    mode: 'index',
                                    intersect: false,
                                    backgroundColor: $('body').hasClass('efa-dark-mode') ? '#1f2940' : '#ffffff',
                                    titleColor: $('body').hasClass('efa-dark-mode') ? '#e5e7eb' : '#1f2937',
                                    bodyColor: $('body').hasClass('efa-dark-mode') ? '#9ca3af' : '#6b7280',
                                    borderColor: $('body').hasClass('efa-dark-mode') ? '#3a3a4e' : '#e5e7eb',
                                    borderWidth: 1,
                                    padding: 12,
                                    displayColors: true,
                                    callbacks: {
                                        label: function(context) {
                                            return context.dataset.label + ': ' + context.parsed.y + ' envíos';
                                        }
                                    }
                                }
                            },
                            scales: {
                                x: {
                                    grid: {
                                        display: false
                                    },
                                    ticks: {
                                        font: {
                                            size: 10
                                        },
                                        color: $('body').hasClass('efa-dark-mode') ? '#9ca3af' : '#6b7280',
                                        maxRotation: 45,
                                        minRotation: 0
                                    }
                                },
                                y: {
                                    beginAtZero: true,
                                    grid: {
                                        color: $('body').hasClass('efa-dark-mode') ? '#374151' : '#e5e7eb'
                                    },
                                    ticks: {
                                        font: {
                                            size: 10
                                        },
                                        color: $('body').hasClass('efa-dark-mode') ? '#9ca3af' : '#6b7280',
                                        precision: 0
                                    }
                                }
                            },
                            interaction: {
                                mode: 'nearest',
                                axis: 'x',
                                intersect: false
                            }
                        }
                    });
                });
            }
        });
        </script>
        <?php
    }
}
