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

class GW_Analytics_Reports
{

    public function __construct()
    {
        add_action('admin_init', [$this, 'save_report_settings']);
        add_action('wp_ajax_efa_generate_report', [$this, 'ajax_generate_filtered_report']); // Legacy
        add_action('wp_ajax_gw_generate_report_data', [$this, 'ajax_generate_report_data']); // New one
    }

    public function save_report_settings()
    {
        if (!isset($_POST['gw_save_report_settings']))
            return;
        if (!check_admin_referer('gw_report_settings_nonce'))
            return;

        $role = get_option('efa_access_role', 'manage_options');
        if (!current_user_can($role))
            return;

        // Guardar configuración de bloques de informe
        update_option('efa_report_show_kpis', isset($_POST['efa_report_show_kpis']) ? '1' : '0');
        update_option('efa_report_show_timeline', isset($_POST['efa_report_show_timeline']) ? '1' : '0');
        update_option('efa_report_show_forms', isset($_POST['efa_report_show_forms']) ? '1' : '0');
        update_option('efa_report_show_origins', isset($_POST['efa_report_show_origins']) ? '1' : '0');
        update_option('efa_report_show_crm', isset($_POST['efa_report_show_crm']) ? '1' : '0');
        update_option('efa_report_show_read', isset($_POST['efa_report_show_read']) ? '1' : '0');
        update_option('efa_report_show_spam', isset($_POST['efa_report_show_spam']) ? '1' : '0');
        update_option('efa_report_blocks_order', isset($_POST['efa_report_blocks_order']) ? sanitize_text_field($_POST['efa_report_blocks_order']) : 'kpis,origins,timeline,spam,forms,crm,read');

        // Guardar filtros seleccionados de orígenes y formularios
        $selected_origins = isset($_POST['selected_origins']) ? sanitize_text_field($_POST['selected_origins']) : '';
        $selected_forms = isset($_POST['selected_forms']) ? sanitize_text_field($_POST['selected_forms']) : '';
        update_option('efa_report_selected_origins', $selected_origins);
        update_option('efa_report_selected_forms', $selected_forms);

        $redirect_url = add_query_arg(['page' => 'gw-elementor', 'tab' => 'reports', 'updated' => 'true'], admin_url('admin.php'));
        error_log('GW Reports: Redirect URL = ' . $redirect_url);
        wp_redirect($redirect_url);
        exit;
    }

    /**
     * AJAX: Generar PDF con filtros (retorna datos para el modal)
     */
    public function ajax_generate_filtered_report()
    {
        check_ajax_referer('efa_nonce', 'nonce');

        $start_date = isset($_POST['start_date']) ? sanitize_text_field($_POST['start_date']) : '';
        $end_date = isset($_POST['end_date']) ? sanitize_text_field($_POST['end_date']) : '';
        $origins = isset($_POST['origins']) && is_array($_POST['origins']) ? array_map('sanitize_text_field', $_POST['origins']) : [];
        $forms = isset($_POST['forms']) && is_array($_POST['forms']) ? array_map('sanitize_text_field', $_POST['forms']) : [];

        // Obtener datos filtrados
        $filtered_data = $this->get_filtered_data($start_date, $end_date, $origins, $forms);

        // Retornar datos para que el frontend genere el modal con gráficas
        wp_send_json_success([
            'data' => $filtered_data,
            'total' => count($filtered_data),
            'start_date' => $start_date,
            'end_date' => $end_date,
            'start_date_formatted' => date_i18n(get_option('date_format'), strtotime($start_date)),
            'end_date_formatted' => date_i18n(get_option('date_format'), strtotime($end_date))
        ]);
    }

    /**
     * Obtener datos filtrados de la base de datos
     */
    private function get_filtered_data($start_date, $end_date, $origins, $forms, $all_origins = false, $all_forms = false)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'e_submissions';
        $table_values = $wpdb->prefix . 'e_submissions_values';
        $table_meta = $wpdb->prefix . 'e_submissions_meta';

        // Base Query
        $query = "
            SELECT s.id, s.created_at, s.form_name as form,
                   v_origin.value as origin,
                   v_spam.value as spam_override,
                   m_crm.value as crm_status,
                   m_read.value as read_status,
                   v_email.value as email,
                   COALESCE(v_name.value, v_nombre.value) as nombre
            FROM $table s
            LEFT JOIN $table_values v_origin ON (s.id = v_origin.submission_id AND v_origin.key = 'origen')
            LEFT JOIN $table_values v_spam ON (s.id = v_spam.submission_id AND v_spam.key = 'efa_spam_override')
            LEFT JOIN $table_values m_crm ON (s.id = m_crm.submission_id AND m_crm.key = 'efa_crm_status')
            LEFT JOIN $table_values m_read ON (s.id = m_read.submission_id AND m_read.key = 'efa_read_status')
            LEFT JOIN $table_values v_email ON (s.id = v_email.submission_id AND v_email.key = 'email')
            LEFT JOIN $table_values v_name ON (s.id = v_name.submission_id AND v_name.key = 'name')
            LEFT JOIN $table_values v_nombre ON (s.id = v_nombre.submission_id AND v_nombre.key = 'nombre')
            WHERE s.status != 'trash'
        ";

        $params = [];

        // Date Filter
        if (!empty($start_date) && !empty($end_date)) {
            $query .= " AND s.created_at >= %s AND s.created_at <= %s";
            $params[] = $start_date . ' 00:00:00';
            $params[] = $end_date . ' 23:59:59';
        }

        // Origin Filter - Skip if "All" is selected
        if (!$all_origins && !empty($origins)) {
            $origin_conditions = [];
            $has_organic_or_unknown = false;

            foreach ($origins as $org) {
                if ($org === 'Organico' || $org === 'Desconocido' || $org === '') {
                    $has_organic_or_unknown = true;
                } else {
                    $origin_conditions[] = $org;
                }
            }

            $sql_parts = [];

            // Si hay orígenes específicos seleccionados
            if (!empty($origin_conditions)) {
                $placeholders = implode(',', array_fill(0, count($origin_conditions), '%s'));
                $sql_parts[] = "v_origin.value IN ($placeholders)";
                $params = array_merge($params, $origin_conditions);
            }

            // Si se selecciona Orgánico/Desconocido, incluir NULLs y vacíos
            if ($has_organic_or_unknown) {
                $sql_parts[] = "(v_origin.value IS NULL OR v_origin.value = '' OR v_origin.value = 'Organico')";
            }

            if (!empty($sql_parts)) {
                $query .= " AND (" . implode(' OR ', $sql_parts) . ")";
            }
        }

        // Form Filter - Skip if "All" is selected
        if (!$all_forms && !empty($forms)) {
            // Handle Desconocido for forms
            if (in_array('Desconocido', $forms)) {
                $forms_clean = array_diff($forms, ['Desconocido']);
                $sql_parts = [];

                if (!empty($forms_clean)) {
                    $placeholders = implode(',', array_fill(0, count($forms_clean), '%s'));
                    $sql_parts[] = "s.form_name IN ($placeholders)";
                    $params = array_merge($params, $forms_clean);
                }

                $sql_parts[] = "(s.form_name IS NULL OR s.form_name = '')";

                $query .= " AND (" . implode(' OR ', $sql_parts) . ")";
            } else {
                $placeholders = implode(',', array_fill(0, count($forms), '%s'));
                $query .= " AND s.form_name IN ($placeholders)";
                $params = array_merge($params, $forms);
            }
        }

        $query .= " ORDER BY s.created_at DESC";

        if (!empty($params)) {
            $query = $wpdb->prepare($query, $params);
        }

        $submissions = $wpdb->get_results($query);

        // Process data
        $filtered_data = [];
        foreach ($submissions as $submission) {
            // Spam Logic
            $spam_probability = 0;

            // 1. Check override first
            if ($submission->spam_override === '1') {
                $spam_probability = 100;
            } elseif ($submission->spam_override === '0') {
                $spam_probability = 0;
            } else {
                // 2. Calculate score if no override
                // We need to construct a text representation for the spam check
                // In dashboard it checks name, email, and other fields. 
                // Here we have name and email.
                $text_to_check = $submission->nombre . ' ' . $submission->email . ' ' . $submission->form;
                $score = $this->get_spam_score($submission->nombre, $text_to_check);

                // Map score to probability
                if ($score >= 2) {
                    $spam_probability = 100;
                } elseif ($score == 1) {
                    $spam_probability = 50;
                } else {
                    $spam_probability = 0;
                }
            }

            // Normalize Origin
            $origin = $submission->origin;
            if (empty($origin)) {
                $origin = 'Organico'; // Default fallback
            }

            $filtered_data[] = [
                'id' => $submission->id,
                'created_at' => $submission->created_at,
                'origin' => $origin,
                'form' => $submission->form ?: 'Desconocido',
                'email' => $submission->email,
                'nombre' => $submission->nombre,
                'crm_status' => $submission->crm_status ?: 'new',
                'read_status' => $submission->read_status ?: '0',
                'spam_probability' => $spam_probability,
                'is_spam' => $spam_probability > 70
            ];
        }

        return ['data' => $filtered_data];
    }

    /**
     * Calculate Spam Score (Copied from Dashboard)
     */
    private function get_spam_score($name, $text)
    {
        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;
    }

    /**
     * Get deleted spam count (emails in trash that are spam)
     */
    private function get_deleted_spam_count($start_date, $end_date, $origins, $forms, $all_origins = false, $all_forms = false)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'e_submissions';
        $table_values = $wpdb->prefix . 'e_submissions_values';

        // Query para obtener correos en papelera
        $query = "
            SELECT s.id, s.created_at, s.form_name as form,
                   v_origin.value as origin,
                   v_spam.value as spam_override,
                   v_email.value as email,
                   COALESCE(v_name.value, v_nombre.value) as nombre
            FROM $table s
            LEFT JOIN $table_values v_origin ON (s.id = v_origin.submission_id AND v_origin.key = 'origen')
            LEFT JOIN $table_values v_spam ON (s.id = v_spam.submission_id AND v_spam.key = 'efa_spam_override')
            LEFT JOIN $table_values v_email ON (s.id = v_email.submission_id AND v_email.key = 'email')
            LEFT JOIN $table_values v_name ON (s.id = v_name.submission_id AND v_name.key = 'name')
            LEFT JOIN $table_values v_nombre ON (s.id = v_nombre.submission_id AND v_nombre.key = 'nombre')
            WHERE s.status = 'trash'
        ";

        $params = [];

        // Date Filter
        if (!empty($start_date) && !empty($end_date)) {
            $query .= " AND s.created_at >= %s AND s.created_at <= %s";
            $params[] = $start_date . ' 00:00:00';
            $params[] = $end_date . ' 23:59:59';
        }

        // Origin Filter
        if (!$all_origins && !empty($origins)) {
            $origin_conditions = [];
            $has_organic_or_unknown = false;

            foreach ($origins as $org) {
                if ($org === 'Organico' || $org === 'Desconocido' || $org === '') {
                    $has_organic_or_unknown = true;
                } else {
                    $origin_conditions[] = $org;
                }
            }

            $sql_parts = [];

            if (!empty($origin_conditions)) {
                $placeholders = implode(',', array_fill(0, count($origin_conditions), '%s'));
                $sql_parts[] = "v_origin.value IN ($placeholders)";
                $params = array_merge($params, $origin_conditions);
            }

            if ($has_organic_or_unknown) {
                $sql_parts[] = "(v_origin.value IS NULL OR v_origin.value = '' OR v_origin.value = 'Organico')";
            }

            if (!empty($sql_parts)) {
                $query .= " AND (" . implode(' OR ', $sql_parts) . ")";
            }
        }

        // Form Filter
        if (!$all_forms && !empty($forms)) {
            if (in_array('Desconocido', $forms)) {
                $forms_clean = array_diff($forms, ['Desconocido']);
                $sql_parts = [];

                if (!empty($forms_clean)) {
                    $placeholders = implode(',', array_fill(0, count($forms_clean), '%s'));
                    $sql_parts[] = "s.form_name IN ($placeholders)";
                    $params = array_merge($params, $forms_clean);
                }

                $sql_parts[] = "(s.form_name IS NULL OR s.form_name = '')";
                $query .= " AND (" . implode(' OR ', $sql_parts) . ")";
            } else {
                $placeholders = implode(',', array_fill(0, count($forms), '%s'));
                $query .= " AND s.form_name IN ($placeholders)";
                $params = array_merge($params, $forms);
            }
        }

        if (!empty($params)) {
            $query = $wpdb->prepare($query, $params);
        }

        $submissions = $wpdb->get_results($query);

        // Contar cuántos son spam
        $spam_count = 0;
        foreach ($submissions as $submission) {
            // Check override first
            if ($submission->spam_override === '1') {
                $spam_count++;
            } elseif ($submission->spam_override === '0') {
                // Not spam
                continue;
            } else {
                // Calculate spam score
                $text_to_check = $submission->nombre . ' ' . $submission->email . ' ' . $submission->form;
                $score = $this->get_spam_score($submission->nombre, $text_to_check);

                if ($score >= 2) {
                    $spam_count++;
                }
            }
        }

        return $spam_count;
    }


    /**
     * AJAX Handler para generar datos del informe
     */
    public function ajax_generate_report_data()
    {
        try {
            check_ajax_referer('efa_nonce', 'nonce');

            if (!current_user_can('manage_options')) {
                throw new Exception('No tienes permisos para realizar esta acción.');
            }

            $start_date = sanitize_text_field($_POST['start_date']);
            $end_date = sanitize_text_field($_POST['end_date']);
            $origins = isset($_POST['origins']) ? array_map('sanitize_text_field', $_POST['origins']) : [];
            $forms = isset($_POST['forms']) ? array_map('sanitize_text_field', $_POST['forms']) : [];

            $all_origins = isset($_POST['all_origins']) && $_POST['all_origins'] === 'true';
            $all_forms = isset($_POST['all_forms']) && $_POST['all_forms'] === 'true';

            // Obtener datos filtrados
            $result = $this->get_filtered_data($start_date, $end_date, $origins, $forms, $all_origins, $all_forms);
            $data = $result['data'];

            // Obtener spam borrado (en papelera)
            $deleted_spam_count = $this->get_deleted_spam_count($start_date, $end_date, $origins, $forms, $all_origins, $all_forms);

            // Retornar datos para que el frontend genere el modal con gráficas
            wp_send_json_success([
                'data' => $data,
                'total' => count($data),
                'deleted_spam_count' => $deleted_spam_count,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'start_date_formatted' => date_i18n(get_option('date_format'), strtotime($start_date)),
                'end_date_formatted' => date_i18n(get_option('date_format'), strtotime($end_date))
            ]);
        } catch (Exception $e) {
            file_put_contents(__DIR__ . '/gw_error.log', $e->getMessage() . "\n" . $e->getTraceAsString());
            wp_send_json_error($e->getMessage());
        }
    }

    /**
     * Generar PDF profesional con TCPDF
     */
    private function generate_pdf($data, $start_date, $end_date, $config, $origins_filter, $forms_filter)
    {
        // Cargar TCPDF
        require_once(dirname(__FILE__) . '/../vendor/tcpdf/tcpdf.php');

        // Crear instancia de PDF
        $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

        // Configuración del documento
        $pdf->SetCreator('GW Elementor Analytics');
        $pdf->SetAuthor('GW Analytics');
        $pdf->SetTitle('Informe de Leads - ' . $start_date . ' a ' . $end_date);
        $pdf->SetSubject('Informe Personalizado');

        // Márgenes
        $pdf->SetMargins(15, 20, 15);
        $pdf->SetAutoPageBreak(true, 15);

        // Fuentes
        $pdf->SetFont('helvetica', '', 10);

        // Añadir página
        $pdf->AddPage();

        // PORTADA
        $this->add_pdf_cover($pdf, $start_date, $end_date, count($data));

        // SECCIÓN 1: KPIs
        if ($config['show_kpis']) {
            $this->add_pdf_kpis($pdf, $data);
        }

        // SECCIÓN 2: Evolución Timeline
        if ($config['show_timeline']) {
            $this->add_pdf_timeline($pdf, $data, $start_date, $end_date);
        }

        // SECCIÓN 3: Distribución por Formularios
        if ($config['show_forms']) {
            $this->add_pdf_forms_distribution($pdf, $data);
        }

        // SECCIÓN 4: Distribución por Orígenes
        if ($config['show_origins']) {
            $this->add_pdf_origins_distribution($pdf, $data);
        }

        // SECCIÓN 5: Estados CRM
        if ($config['show_crm']) {
            $this->add_pdf_crm_distribution($pdf, $data);
        }

        // SECCIÓN 6: Estado de Lectura
        if ($config['show_read']) {
            $this->add_pdf_read_distribution($pdf, $data);
        }

        // SECCIÓN 7: Detección de Spam
        if ($config['show_spam']) {
            $this->add_pdf_spam_distribution($pdf, $data);
        }

        // SECCIÓN 8: Tabla Detallada

        // Output PDF
        $filename = 'informe-' . $start_date . '-' . $end_date . '.pdf';
        $pdf->Output($filename, 'D'); // 'D' = download
    }

    public function render_reports_view()
    {
        global $wpdb;

        // Asegurar que SweetAlert2 esté cargado para el modal de éxito
        wp_enqueue_style('sweetalert2-css', 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css', [], '11.0.0');
        wp_enqueue_script('sweetalert2-js', 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js', [], '11.0.0', true);

        // Enqueue Chart.js for report modal graphs
        wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js', [], '4.4.0', true);

        // Obtener configuración actual
        $report_show_kpis = get_option('efa_report_show_kpis', '1');
        $report_show_timeline = get_option('efa_report_show_timeline', '1');
        $report_show_forms = get_option('efa_report_show_forms', '1');
        $report_show_origins = get_option('efa_report_show_origins', '1');
        $report_show_crm = get_option('efa_report_show_crm', '1');
        $report_show_read = get_option('efa_report_show_read', '1');
        $report_show_spam = get_option('efa_report_show_spam', '1');

        // Obtener filtros guardados
        $saved_origins = get_option('efa_report_selected_origins', '');
        $saved_forms = get_option('efa_report_selected_forms', '');
        $selected_origins_array = !empty($saved_origins) ? explode(',', $saved_origins) : [];
        $selected_forms_array = !empty($saved_forms) ? explode(',', $saved_forms) : [];

        // Obtener orígenes únicos desde tabla de valores (key = 'origen')
        $origins_query = "SELECT DISTINCT v.value 
                          FROM {$wpdb->prefix}e_submissions_values v
                          INNER JOIN {$wpdb->prefix}e_submissions s ON v.submission_id = s.id
                          WHERE v.`key` = 'origen' 
                          AND v.value IS NOT NULL 
                          AND v.value != '' 
                          AND s.status != 'trash'
                          ORDER BY v.value";
        $origins = $wpdb->get_col($origins_query);

        // Obtener formularios únicos desde tabla submissions (columna form_name)
        $forms_query = "SELECT DISTINCT form_name 
                        FROM {$wpdb->prefix}e_submissions 
                        WHERE status != 'trash' 
                        AND form_name IS NOT NULL 
                        AND form_name != '' 
                        ORDER BY form_name";
        $forms = $wpdb->get_col($forms_query);

        // Debug: Si no hay datos, mostrar mensaje
        if (empty($origins)) {
            $origins = ['No se encontraron orígenes'];
        }
        if (empty($forms)) {
            $forms = ['No se encontraron formularios'];
        }

        // Calcular mes anterior por defecto
        $default_start = date('Y-m-01', strtotime('first day of last month'));
        $default_end = date('Y-m-t', strtotime('last day of last month'));

        if (isset($_GET['updated'])) {
            echo '<div class="notice notice-success is-dismissible inline" style="margin-top:20px;"><p><strong>¡Configuración guardada!</strong> Los ajustes del informe se han actualizado correctamente.</p></div>';
        }
        ?>
        <div class="gw-reports-container">
            <!-- Header mejorado -->
            <div class="gw-reports-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-media-document"></span>
                            </span>
                            Generador de Informes
                        </h1>
                        <p class="gw-header-description">Configure los filtros y elementos que desea incluir en su informe PDF personalizado.</p>
                    </div>
                </div>
            </div>

            <div class="gw-reports-layout">
                <!-- COLUMNA IZQUIERDA: FILTROS -->
                <div class="gw-reports-filters">
                    <!-- Botón de generar informe destacado (fijo al hacer scroll) -->
                    <div class="gw-generate-card gw-generate-card-sticky">
                        <div class="gw-generate-content">
                            <div class="gw-generate-icon">
                                <span class="dashicons dashicons-media-document"></span>
                            </div>
                            <h3 class="gw-generate-title">¿Listo para generar tu informe?</h3>
                            <p class="gw-generate-description">Selecciona el rango de fechas y genera el informe con los filtros y configuración actuales.</p>
                            
                            <!-- Rango de Fechas dentro del bloque de generar informe -->
                            <div class="gw-generate-date-section">
                                <div class="gw-input-group">
                                    <label class="gw-label">Periodo</label>
                                    <select id="efa-report-date-preset" class="gw-select">
                                        <option value="last_month" selected>Mes Anterior</option>
                                        <option value="last_7">Últimos 7 días</option>
                                        <option value="last_30">Últimos 30 días</option>
                                        <option value="this_month">Este Mes</option>
                                        <option value="custom">Personalizado</option>
                                    </select>
                                </div>

                                <div id="efa-report-custom-dates" class="gw-input-group" style="display:none; margin-top:15px;">
                                    <label class="gw-label">Desde</label>
                                    <input type="date" id="efa-report-start-date" class="gw-input"
                                        value="<?php echo $default_start; ?>">

                                    <label class="gw-label" style="margin-top:10px;">Hasta</label>
                                    <input type="date" id="efa-report-end-date" class="gw-input" value="<?php echo $default_end; ?>">
                                </div>

                                <div class="gw-date-preview"
                                    style="margin-top:15px; padding:10px; background:#f0f6fc; border-left:3px solid #2271b1; font-size:13px; border-radius:6px;">
                                    <strong>Periodo seleccionado:</strong><br>
                                    <span
                                        id="efa-report-date-display"><?php echo date('d/m/Y', strtotime($default_start)) . ' - ' . date('d/m/Y', strtotime($default_end)); ?></span>
                                </div>
                            </div>

                            <button id="efa-btn-generate-report" class="gw-generate-button">
                                <span class="gw-button-icon">
                                    <span class="dashicons dashicons-download"></span>
                                </span>
                                <span class="gw-button-text">Generar Informe PDF</span>
                            </button>
                            <div class="gw-generate-info">
                                <span class="dashicons dashicons-info"></span>
                                <span>El informe se abrirá en una nueva ventana para revisión</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- COLUMNA DERECHA: CONFIGURACIÓN -->
                <div class="gw-reports-config">
                    <form method="post" action="" style="position: sticky; bottom: 0; z-index: 100;">
                        <?php wp_nonce_field('gw_report_settings_nonce'); ?>

                        <div class="gw-card">
                            <h3 class="gw-card-title"><span class="dashicons dashicons-admin-settings"></span> Configuración de
                                Bloques</h3>
                            <p class="gw-card-desc">Personaliza qué elementos aparecen en el informe y su orden.</p>

                            <?php
                            // Definir bloques disponibles
                            $available_blocks = [
                                'kpis' => ['label' => '📊 KPIs Generales', 'desc' => 'Muestra métricas clave: total de leads, promedio diario, día pico, tendencia y origen principal', 'option' => 'efa_report_show_kpis', 'value' => $report_show_kpis],
                                'timeline' => ['label' => '📈 Evolución de Leads', 'desc' => 'Gráfico con total de leads por día, promedio diario, día de mayor actividad y velocidad', 'option' => 'efa_report_show_timeline', 'value' => $report_show_timeline],
                                'forms' => ['label' => '📝 Distribución por Formularios', 'desc' => 'Análisis visual de leads recibidos por cada formulario con porcentajes y cantidades', 'option' => 'efa_report_show_forms', 'value' => $report_show_forms],
                                'origins' => ['label' => '🌍 Distribución por Orígenes', 'desc' => 'Desglose de leads por fuente de tráfico (Google Ads, Facebook, SEO, etc.)', 'option' => 'efa_report_show_origins', 'value' => $report_show_origins],
                                'crm' => ['label' => '🏷️ Estados CRM', 'desc' => 'Distribución de leads por estado: nuevos, interesados, ganados, perdidos, etc.', 'option' => 'efa_report_show_crm', 'value' => $report_show_crm],
                                'read' => ['label' => '👁️ Correos Leídos/No Leídos', 'desc' => 'Porcentaje y cantidad de correos que han sido revisados vs. pendientes', 'option' => 'efa_report_show_read', 'value' => $report_show_read],
                                'spam' => ['label' => '🛡️ Detección de Spam', 'desc' => 'Análisis de calidad: tasa de leads limpios, spam detectado y ratio de limpieza', 'option' => 'efa_report_show_spam', 'value' => $report_show_spam],
                            ];

                            $saved_order = get_option('efa_report_blocks_order', 'kpis,origins,timeline,spam,forms,crm,read');
                            $order_array = explode(',', $saved_order);

                            foreach (array_keys($available_blocks) as $block_key) {
                                if (!in_array($block_key, $order_array)) {
                                    $order_array[] = $block_key;
                                }
                            }
                            $order_array = array_intersect($order_array, array_keys($available_blocks));
                            ?>

                            <input type="hidden" name="efa_report_blocks_order" id="efa_report_blocks_order"
                                value="<?php echo esc_attr(implode(',', $order_array)); ?>">

                            <div class="gw-report-blocks-list" id="gw-report-blocks-sortable">
                                <?php foreach ($order_array as $block_key):
                                    $block = $available_blocks[$block_key];
                                    ?>
                                    <div class="gw-report-block-item" data-id="<?php echo $block_key; ?>">
                                        <div class="block-drag-handle">
                                            <span class="dashicons dashicons-menu"></span>
                                        </div>

                                        <div class="block-info">
                                            <div class="block-label"><?php echo $block['label']; ?></div>
                                            <div class="block-desc"><?php echo $block['desc']; ?></div>
                                        </div>

                                        <div class="block-toggle">
                                            <label class="gw-toggle">
                                                <input type="checkbox" name="<?php echo $block['option']; ?>" value="1" <?php checked($block['value'], '1'); ?>>
                                                <span class="gw-slider"></span>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <input type="hidden" name="selected_origins" id="selected_origins" value="">
                        <input type="hidden" name="selected_forms" id="selected_forms" value="">

                    <div class="gw-card">
                        <h3 class="gw-card-title"><span class="dashicons dashicons-admin-site"></span> Orígenes</h3>
                        <p class="gw-card-desc">Selecciona los orígenes de tráfico a incluir en el informe.</p>

                        <div class="gw-checkbox-list">
                            <label class="gw-checkbox-item">
                                <input type="checkbox" id="efa-report-origins-all" checked>
                                <strong>Seleccionar todos</strong>
                            </label>
                            <?php foreach ($origins as $origin):
                                $is_checked = empty($selected_origins_array) || in_array($origin, $selected_origins_array);
                                ?>
                                <label class="gw-checkbox-item">
                                    <input type="checkbox" class="efa-report-origin-check" value="<?php echo esc_attr($origin); ?>"
                                        <?php echo $is_checked ? 'checked' : ''; ?>>
                                    <?php echo esc_html($origin); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>

                        <div class="gw-selection-summary" style="margin-top:10px; font-size:13px; color:#666;">
                            <span id="efa-report-origins-count"><?php echo count($origins); ?></span> de
                            <?php echo count($origins); ?> seleccionados
                        </div>
                    </div>

                    <div class="gw-card">
                        <h3 class="gw-card-title"><span class="dashicons dashicons-feedback"></span> Formularios</h3>
                        <p class="gw-card-desc">Selecciona los formularios a incluir en el informe.</p>

                        <div class="gw-checkbox-list">
                            <label class="gw-checkbox-item">
                                <input type="checkbox" id="efa-report-forms-all" checked>
                                <strong>Seleccionar todos</strong>
                            </label>
                            <?php foreach ($forms as $form):
                                $is_checked = empty($selected_forms_array) || in_array($form, $selected_forms_array);
                                ?>
                                <label class="gw-checkbox-item">
                                    <input type="checkbox" class="efa-report-form-check" value="<?php echo esc_attr($form); ?>"
                                        <?php echo $is_checked ? 'checked' : ''; ?>>
                                    <?php echo esc_html($form); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>

                        <div class="gw-selection-summary" style="margin-top:10px; font-size:13px; color:#666;">
                            <span id="efa-report-forms-count"><?php echo count($forms); ?></span> de
                            <?php echo count($forms); ?> seleccionados
                        </div>
                    </div>

                        <div class="gw-save-bar">
                            <button type="submit" name="gw_save_report_settings" class="gw-btn-primary">
                                <span class="dashicons dashicons-yes-alt"></span>
                                Guardar Configuración
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <style>
            .gw-reports-container {
                max-width: 1600px;
                margin: 0 auto;
                padding: 15px 20px 30px 20px;
            }

            /* Header mejorado */
            .gw-reports-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: 20px;
            }

            .gw-header-text {
                flex: 1;
            }

            .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;
            }

            .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;
                padding-top: 0;
            }

            .gw-reports-layout {
                display: grid;
                grid-template-columns: 420px 1fr;
                gap: 30px;
                align-items: start;
                position: relative;
            }

            .gw-reports-filters {
                display: flex;
                flex-direction: column;
                gap: 24px;
                position: relative;
                z-index: 10;
                align-items: stretch;
            }

            .gw-reports-filters > *:first-child {
                margin-top: 0 !important;
            }

            .gw-generate-card-sticky {
                position: sticky;
                top: 0;
                z-index: 20;
                margin-top: 0 !important;
                align-self: flex-start;
            }

            .gw-generate-card-sticky .gw-generate-content {
                padding: 30px 24px;
            }

            .gw-generate-card-sticky .gw-generate-title {
                font-size: 20px;
            }

            .gw-generate-card-sticky .gw-generate-description {
                font-size: 14px;
                margin: 0 0 20px 0;
            }

            .gw-generate-card-sticky .gw-generate-icon {
                width: 56px;
                height: 56px;
                margin-bottom: 16px;
            }

            .gw-generate-card-sticky .gw-generate-icon .dashicons {
                font-size: 28px;
                width: 28px;
                height: 28px;
            }

            .gw-generate-card-sticky .gw-generate-button {
                padding: 16px 28px;
                font-size: 16px;
                min-width: 100%;
            }

            .gw-reports-config {
                display: flex;
                flex-direction: column;
                gap: 24px;
                position: relative;
                z-index: 10;
            }

            .gw-reports-filters *,
            .gw-reports-config * {
                pointer-events: auto;
            }

            .gw-reports-filters .gw-card,
            .gw-reports-config .gw-card {
                position: relative;
                z-index: 10;
            }

            /* Cards mejoradas */
            .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;
            }

            .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 16px 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;
            }

            .gw-card-desc {
                font-size: 14px;
                color: #6b7280;
                margin: 0 0 16px 0;
                line-height: 1.5;
            }

            .gw-checkbox-list {
                max-height: 320px;
                overflow-y: auto;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                padding: 8px;
                background: #f9fafb;
            }

            .gw-checkbox-list::-webkit-scrollbar {
                width: 8px;
            }

            .gw-checkbox-list::-webkit-scrollbar-track {
                background: #f1f1f1;
                border-radius: 4px;
            }

            .gw-checkbox-list::-webkit-scrollbar-thumb {
                background: #cbd5e1;
                border-radius: 4px;
            }

            .gw-checkbox-list::-webkit-scrollbar-thumb:hover {
                background: #94a3b8;
            }

            .gw-checkbox-item {
                display: flex;
                align-items: center;
                padding: 6px 8px;
                margin-bottom: 2px;
                cursor: pointer;
                border-radius: 6px;
                transition: all 0.2s ease;
                border: 1px solid transparent;
            }

            .gw-checkbox-item:hover {
                background: #f3f4f6;
                border-color: #e5e7eb;
            }

            .gw-checkbox-item input[type="checkbox"] {
                margin-right: 10px;
                width: 18px;
                height: 18px;
                cursor: pointer;
                pointer-events: auto !important;
                position: relative;
                z-index: 2;
            }

            .gw-checkbox-item {
                pointer-events: auto !important;
                position: relative;
                z-index: 1;
            }

            .gw-selection-summary {
                text-align: right;
                font-size: 13px;
                color: #6b7280;
                font-weight: 500;
                margin-top: 12px;
                padding-top: 12px;
                border-top: 1px solid #e5e7eb;
            }

            .gw-report-blocks-list {
                display: flex;
                flex-direction: column;
                gap: 10px;
            }

            .gw-report-block-item {
                display: flex;
                align-items: center;
                gap: 16px;
                padding: 18px;
                background: #ffffff;
                border: 2px solid #e5e7eb;
                border-radius: 10px;
                transition: all 0.3s ease;
                position: relative;
            }

            .gw-report-block-item:hover {
                border-color: #667eea;
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
                transform: translateX(4px);
            }

            .gw-report-block-item.ui-sortable-helper {
                box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
                transform: rotate(2deg);
            }

            .block-drag-handle {
                color: #9ca3af;
                cursor: move;
                padding: 8px;
                margin: -8px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 6px;
                transition: all 0.2s ease;
                z-index: 10;
                position: relative;
                flex-shrink: 0;
            }

            .block-drag-handle:hover {
                background: #f3f4f6;
                color: #667eea;
            }

            .block-drag-handle .dashicons {
                font-size: 20px;
                width: 20px;
                height: 20px;
                pointer-events: none;
            }

            .block-info {
                pointer-events: none;
            }

            .block-toggle {
                pointer-events: auto;
            }

            .block-info {
                flex: 1;
            }

            .block-label {
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 6px;
                color: #1f2937;
            }

            .block-desc {
                font-size: 13px;
                color: #6b7280;
                line-height: 1.5;
            }

            .block-toggle {
                margin: 0;
            }

            .gw-sortable-placeholder {
                border: 2px dashed #ccc;
                background: #f9f9f9;
                height: 70px;
                margin-bottom: 10px;
                border-radius: 8px;
                visibility: visible !important;
            }

            /* Report Modal Styles - Enhanced */
            .efa-report-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.75);
                z-index: 100000;
                display: none;
                justify-content: center;
                align-items: flex-start;
                overflow-y: auto;
                padding: 40px 20px;
                box-sizing: border-box;
                backdrop-filter: blur(5px);
            }

            .efa-report-overlay.open {
                display: flex;
            }

            .efa-report-modal {
                background: white;
                width: 100%;
                max-width: 1000px;
                /* Más ancho para mejor visualización */
                border-radius: 12px;
                box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
                display: flex;
                flex-direction: column;
                margin: auto;
                /* Centrado vertical */
                position: relative;
                overflow: hidden;
            }

            .efa-report-header {
                padding: 20px 30px;
                border-bottom: 1px solid #e0e0e0;
                display: flex;
                justify-content: space-between;
                align-items: center;
                background: #f8f9fa;
            }

            .efa-report-header h2 {
                margin: 0;
                font-size: 20px;
                font-weight: 600;
                color: #2c3e50;
            }

            .efa-report-actions {
                display: flex;
                gap: 12px;
            }

            .efa-report-actions .button {
                display: flex;
                align-items: center;
                gap: 5px;
            }

            .efa-report-body {
                padding: 40px;
                overflow-y: auto;
                background: #fff;
                max-height: calc(90vh - 80px);
                /* Ajuste para scroll interno */
            }

            /* Report Content Styles */
            .efa-report-page {
                font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
                color: #333;
                max-width: 900px;
                margin: 0 auto;
            }

            .efa-report-cover {
                text-align: center;
                margin-bottom: 50px;
                padding-bottom: 30px;
            }


            .efa-report-logo {
                max-height: 100px;
                margin-bottom: 20px;
                display: inline-block;
            }

            .efa-report-cover h1 {
                font-size: 32px;
                margin: 0 0 15px;
                color: #2c3e50;
                font-weight: 700;
                letter-spacing: -0.5px;
            }

            .report-period {
                font-size: 18px;
                color: #7f8c8d;
                margin: 5px 0;
            }

            .report-total {
                font-size: 20px;
                font-weight: 600;
                color: #27ae60;
                margin-top: 15px;
                display: inline-block;
                padding: 5px 15px;
                background: #eafaf1;
                border-radius: 20px;
            }

            .efa-report-section {
                margin-bottom: 50px;
                padding-top: 30px;
                page-break-inside: avoid;
                background: #fff;
                border-radius: 8px;
                border-top: 3px solid #e0e0e0;
            }

            .efa-report-section h2 {
                font-size: 22px;
                color: #2c3e50;
                padding-bottom: 15px;
                margin-bottom: 25px;
                font-weight: 600;
            }

            .efa-kpi-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
                gap: 25px;
            }

            .efa-kpi-card {
                background: #fff;
                padding: 25px;
                border-radius: 10px;
                text-align: center;
                border: 1px solid #e0e0e0;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
                transition: transform 0.2s;
            }

            .efa-kpi-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            }

            .efa-kpi-value {
                font-size: 36px;
                font-weight: 700;
                color: #2c3e50;
                display: block;
                line-height: 1.2;
            }

            .efa-kpi-label {
                font-size: 15px;
                color: #7f8c8d;
                margin-top: 8px;
                display: block;
                font-weight: 500;
            }

            /* Spectacular Spam Detection Card Styles */
            .efa-spam-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 20px;
                margin-top: 20px;
            }

            .efa-spam-card {
                position: relative;
                background: #ffffff;
                border-radius: 16px;
                padding: 30px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                overflow: hidden;
                border: 1px solid rgba(0, 0, 0, 0.05);
            }

            .efa-spam-card::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                height: 4px;
                background: linear-gradient(90deg, #667eea, #764ba2);
                opacity: 0;
                transition: opacity 0.3s;
            }

            .efa-spam-card:hover {
                transform: translateY(-4px);
                box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
            }

            .efa-spam-card:hover::before {
                opacity: 1;
            }

            .efa-spam-card-bg {
                position: absolute;
                top: 0;
                right: 0;
                width: 150px;
                height: 150px;
                background: radial-gradient(circle, rgba(99, 102, 241, 0.08) 0%, transparent 70%);
                border-radius: 50%;
                transform: translate(30%, -30%);
                pointer-events: none;
            }

            .efa-spam-card-clean .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(16, 185, 129, 0.1) 0%, transparent 70%);
            }

            .efa-spam-card-spam .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(239, 68, 68, 0.1) 0%, transparent 70%);
            }

            .efa-spam-card-ratio .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 70%);
            }

            .efa-spam-card-quality .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(251, 191, 36, 0.1) 0%, transparent 70%);
            }

            .efa-spam-card-deleted .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(139, 92, 246, 0.1) 0%, transparent 70%);
            }


            .efa-spam-card-total .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(93, 93, 250, 0.1) 0%, transparent 70%);
            }

            .efa-spam-card-read .efa-spam-card-bg {
                background: radial-gradient(circle, rgba(245, 158, 11, 0.1) 0%, transparent 70%);
            }


            .efa-spam-icon {
                width: 64px;
                height: 64px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 12px;
                margin-bottom: 20px;
                position: relative;
                z-index: 1;
            }

            .efa-spam-card-clean .efa-spam-icon {
                background: linear-gradient(135deg, #10b981, #059669);
                color: white;
                box-shadow: 0 8px 16px rgba(16, 185, 129, 0.3);
            }

            .efa-spam-card-spam .efa-spam-icon {
                background: linear-gradient(135deg, #ef4444, #dc2626);
                color: white;
                box-shadow: 0 8px 16px rgba(239, 68, 68, 0.3);
            }

            .efa-spam-card-ratio .efa-spam-icon {
                background: linear-gradient(135deg, #3b82f6, #2563eb);
                color: white;
                box-shadow: 0 8px 16px rgba(59, 130, 246, 0.3);
            }

            .efa-spam-card-quality .efa-spam-icon {
                background: linear-gradient(135deg, #fbbf24, #f59e0b);
                color: white;
                box-shadow: 0 8px 16px rgba(251, 191, 36, 0.3);
            }

            .efa-spam-card-deleted .efa-spam-icon {
                background: linear-gradient(135deg, #8b5cf6, #7c3aed);
                color: white;
                box-shadow: 0 8px 16px rgba(139, 92, 246, 0.3);
            }

            .efa-spam-card-total .efa-spam-icon {
                background: linear-gradient(135deg, #5d5dfa, #8080ff);
                color: white;
                box-shadow: 0 8px 16px rgba(93, 93, 250, 0.3);
            }

            .efa-spam-card-read .efa-spam-icon {
                background: linear-gradient(135deg, #f59e0b, #fbbf24);
                color: white;
                box-shadow: 0 8px 16px rgba(245, 158, 11, 0.3);
            }

            .efa-spam-content {
                position: relative;
                z-index: 1;
            }

            .efa-spam-label {
                font-size: 14px;
                font-weight: 600;
                color: #64748b;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                margin-bottom: 12px;
            }

            .efa-spam-value {
                font-size: 48px;
                font-weight: 800;
                line-height: 1;
                margin-bottom: 8px;
                background: linear-gradient(135deg, #1e293b, #475569);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .efa-spam-card-clean .efa-spam-value {
                background: linear-gradient(135deg, #10b981, #059669);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .efa-spam-card-spam .efa-spam-value {
                background: linear-gradient(135deg, #ef4444, #dc2626);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .efa-spam-card-ratio .efa-spam-value {
                background: linear-gradient(135deg, #3b82f6, #2563eb);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .efa-spam-card-deleted .efa-spam-value {
                background: linear-gradient(135deg, #8b5cf6, #7c3aed);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }


            .efa-spam-card-total .efa-spam-value {
                background: linear-gradient(135deg, #5d5dfa, #8080ff);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .efa-spam-card-read .efa-spam-value {
                background: linear-gradient(135deg, #f59e0b, #fbbf24);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }


            .efa-spam-value-large {
                display: flex;
                align-items: baseline;
                gap: 4px;
                margin-bottom: 12px;
            }

            .efa-spam-desc {
                font-size: 14px;
                color: #94a3b8;
                margin-bottom: 16px;
            }

            .efa-spam-bar {
                width: 100%;
                height: 8px;
                background: #e2e8f0;
                border-radius: 4px;
                overflow: hidden;
                position: relative;
            }

            .efa-spam-bar-fill {
                height: 100%;
                border-radius: 4px;
                transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
                position: relative;
                overflow: hidden;
            }

            .efa-spam-bar-fill::after {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
                animation: shimmer 2s infinite;
            }

            @keyframes shimmer {
                0% {
                    transform: translateX(-100%);
                }

                100% {
                    transform: translateX(100%);
                }
            }

            .efa-spam-stats {
                display: flex;
                flex-direction: column;
                gap: 8px;
                margin-top: 12px;
            }

            .efa-spam-stat {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 13px;
                color: #475569;
            }

            .efa-spam-stat-dot {
                width: 8px;
                height: 8px;
                border-radius: 50%;
                display: inline-block;
            }

            .efa-spam-quality-badge {
                display: inline-block;
                padding: 8px 16px;
                border-radius: 20px;
                font-size: 13px;
                font-weight: 600;
                margin-top: 12px;
            }

            .efa-spam-quality-badge.excellent {
                background: linear-gradient(135deg, #10b981, #059669);
                color: white;
                box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
            }

            .efa-spam-quality-badge.good {
                background: linear-gradient(135deg, #3b82f6, #2563eb);
                color: white;
                box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
            }

            .efa-spam-quality-badge.fair {
                background: linear-gradient(135deg, #f59e0b, #d97706);
                color: white;
                box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
            }

            @media print {
                .efa-spam-card {
                    break-inside: avoid;
                    box-shadow: none;
                    border: 1px solid #e0e0e0;
                }

                .efa-spam-card:hover {
                    transform: none;
                }
            }


            .efa-chart-container {
                height: 350px;
                position: relative;
                margin: 0 auto;
                width: 100%;
                max-width: 100%;
                /* Full width for charts */
            }

            .efa-report-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
                font-size: 13px;
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                overflow: hidden;
            }

            .efa-report-table th,
            .efa-report-table td {
                padding: 12px 15px;
                border-bottom: 1px solid #e0e0e0;
                text-align: left;
            }

            .efa-report-table th {
                background: #f8f9fa;
                font-weight: 600;
                color: #2c3e50;
                text-transform: uppercase;
                font-size: 11px;
                letter-spacing: 0.5px;
            }

            .efa-report-table tr:last-child td {
                border-bottom: none;
            }

            .efa-report-table tr:nth-child(even) {
                background: #fcfcfc;
            }

            ``` .efa-report-table tr:hover {
        background: #f0f4f8;
    }

    @media print {
        @page {
            margin: 1cm;
            size: A4;
        }

        body * {
            visibility: hidden;
        }

        .efa-report-modal,
        .efa-report-modal * {
            visibility: visible;
        }

        .efa-report-modal {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            max-width: 100%;
            box-shadow: none;
            margin: 0;
            border: none;
            overflow: visible;
        }

        .efa-report-body {
            padding: 0;
            max-height: none;
            overflow: visible;
        }

        .efa-report-header {
            display: none;
        }

        .efa-report-overlay {
            position: absolute;
            background: white;
            padding: 0;
            display: block !important;
            z-index: auto;
        }

        .efa-report-section {
            page-break-inside: avoid;
            margin-bottom: 30px;
            border: none;
        }

        .efa-chart-container {
            page-break-inside: avoid;
        }
    }

            /* Botón de generar informe mejorado */
            .gw-generate-card {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border: none;
                border-radius: 16px;
                padding: 0;
                box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
                overflow: hidden;
                position: relative;
                z-index: 1;
            }

            .gw-generate-card::before {
                content: '';
                position: absolute;
                top: -50%;
                right: -50%;
                width: 200%;
                height: 200%;
                background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
                animation: pulse 3s ease-in-out infinite;
                pointer-events: none;
                z-index: 0;
            }

            @keyframes pulse {
                0%, 100% { opacity: 0.5; }
                50% { opacity: 0.8; }
            }

            .gw-generate-content {
                position: relative;
                z-index: 2;
                text-align: center;
                padding: 40px 30px;
                color: white;
                pointer-events: auto;
            }

            .gw-generate-icon {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 64px;
                height: 64px;
                background: rgba(255, 255, 255, 0.2);
                border-radius: 16px;
                margin-bottom: 20px;
                backdrop-filter: blur(10px);
            }

            .gw-generate-icon .dashicons {
                font-size: 32px;
                width: 32px;
                height: 32px;
                color: white;
            }

            .gw-generate-title {
                font-size: 24px;
                font-weight: 700;
                margin: 0 0 12px 0;
                color: white;
            }

            .gw-generate-description {
                font-size: 15px;
                margin: 0 0 28px 0;
                opacity: 0.95;
                line-height: 1.6;
            }

            .gw-generate-date-section {
                background: rgba(255, 255, 255, 0.15);
                backdrop-filter: blur(10px);
                border-radius: 12px;
                padding: 20px;
                margin: 0 0 28px 0;
                text-align: left;
            }

            .gw-generate-date-section .gw-input-group {
                margin-bottom: 15px;
            }

            .gw-generate-date-section .gw-label {
                color: rgba(255, 255, 255, 0.95);
                font-weight: 600;
                margin-bottom: 8px;
                display: block;
            }

            .gw-generate-date-section .gw-select,
            .gw-generate-date-section .gw-input {
                width: 100%;
                padding: 12px;
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 8px;
                background: rgba(255, 255, 255, 0.95);
                color: #1f2937;
                font-size: 14px;
                transition: all 0.2s ease;
            }

            .gw-generate-date-section .gw-select:focus,
            .gw-generate-date-section .gw-input:focus {
                outline: none;
                border-color: rgba(255, 255, 255, 0.6);
                background: white;
                box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
            }

            .gw-generate-date-section .gw-date-preview {
                background: rgba(255, 255, 255, 0.25) !important;
                border-left: 3px solid rgba(255, 255, 255, 0.8) !important;
                color: white !important;
            }

            .gw-generate-date-section .gw-date-preview strong {
                color: white;
            }

            .gw-generate-date-section .gw-date-preview span {
                color: rgba(255, 255, 255, 0.95);
            }

            .gw-generate-button {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 12px;
                padding: 18px 36px;
                font-size: 18px;
                font-weight: 600;
                color: #667eea;
                background: white;
                border: none;
                border-radius: 12px;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
                min-width: 240px;
            }

            .gw-generate-button:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
                background: #f8f9fa;
            }

            .gw-generate-button:active {
                transform: translateY(0);
            }

            .gw-generate-button:disabled {
                opacity: 0.7;
                cursor: not-allowed;
                transform: none;
            }

            .gw-button-icon {
                display: inline-flex;
                align-items: center;
            }

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

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

            .gw-generate-info {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                margin-top: 20px;
                font-size: 13px;
                opacity: 0.9;
            }

            .gw-generate-info .dashicons {
                font-size: 16px;
                width: 16px;
                height: 16px;
            }

            /* Mejoras en inputs y selects */
            .gw-input-group {
                margin-bottom: 16px;
            }

            .gw-label {
                display: block;
                font-size: 14px;
                font-weight: 600;
                color: #374151;
                margin-bottom: 8px;
            }

            .gw-select,
            .gw-input {
                width: 100%;
                padding: 12px 16px;
                font-size: 14px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                background: #ffffff;
                color: #1f2937;
                transition: all 0.2s ease;
                box-sizing: border-box;
                pointer-events: auto !important;
                cursor: pointer;
                position: relative;
                z-index: 1;
            }

            .gw-input[type="date"] {
                cursor: pointer;
                pointer-events: auto !important;
            }

            .gw-select:focus,
            .gw-input:focus {
                outline: none;
                border-color: #667eea;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            }

            .gw-date-preview {
                margin-top: 16px;
                padding: 14px;
                background: #eff6ff;
                border-left: 4px solid #3b82f6;
                border-radius: 8px;
                font-size: 14px;
                line-height: 1.6;
            }

            .gw-date-preview strong {
                color: #1e40af;
                display: block;
                margin-bottom: 4px;
            }

            .gw-date-preview span {
                color: #1f2937;
                font-weight: 500;
            }

            /* Botón guardar configuración - Mismo estilo que Ajustes */
            .gw-save-bar {
                background: #ffffff;
                padding: 24px;
                border-top: 2px solid #e5e7eb;
                margin-top: 40px;
                border-radius: 12px;
                box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);
                display: flex;
                justify-content: flex-end;
                position: sticky;
                bottom: 0;
                z-index: 100;
            }

            .gw-btn-primary {
                display: inline-flex;
                align-items: center;
                gap: 10px;
                background: #e01d75;
                color: white;
                border: none;
                padding: 14px 32px;
                border-radius: 8px;
                font-size: 15px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(224, 29, 117, 0.3);
                min-width: auto;
                width: auto;
            }

            .gw-btn-primary:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(224, 29, 117, 0.4);
                background: #c91a6a;
            }

            .gw-btn-primary:active {
                transform: translateY(0);
            }

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

            @media (max-width: 1200px) {
                .gw-reports-layout {
                    grid-template-columns: 1fr;
                }

                .gw-generate-card {
                    position: static;
                }
            }

            /* Toggle switch mejorado */
            .gw-toggle {
                position: relative;
                display: inline-block;
                width: 50px;
                height: 28px;
            }

            .gw-toggle input {
                opacity: 0;
                width: 0;
                height: 0;
            }

            .gw-slider {
                position: absolute;
                cursor: pointer;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #cbd5e1;
                transition: 0.3s ease;
                border-radius: 34px !important;
                overflow: hidden;
            }

            .gw-slider:before {
                position: absolute;
                content: "";
                height: 22px;
                width: 22px;
                left: 3px;
                bottom: 3px;
                background-color: white;
                transition: 0.3s ease;
                border-radius: 50% !important;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
            }

            input:checked + .gw-slider {
                background-color: #e01d75;
                border-radius: 34px !important;
            }

            input:checked + .gw-slider:before {
                transform: translateX(22px);
                border-radius: 50% !important;
            }

            .gw-slider:hover {
                background-color: #94a3b8;
            }

            input:checked + .gw-slider:hover {
                background-color: #c91a6a;
            }

            /* Dark mode para el nuevo diseño */
            body.efa-dark-mode .gw-reports-container {
                background: transparent;
            }

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

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

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

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

            body.efa-dark-mode .gw-card:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
                border-color: #4a4a6a !important;
            }

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

            body.efa-dark-mode .gw-card-title .dashicons {
                color: #e01d75 !important;
            }

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

            /* Checkbox list en dark mode */
            body.efa-dark-mode .gw-checkbox-list {
                background: #2a2a3e !important;
                border-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-checkbox-item {
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-checkbox-item:hover {
                background: #2a2a3e !important;
                border-color: #4a4a6a !important;
            }

            body.efa-dark-mode .gw-selection-summary {
                color: #9ca3af !important;
                border-top-color: #3a3a4e !important;
            }

            /* Report blocks en dark mode */
            body.efa-dark-mode .gw-report-block-item {
                background: #1f2940 !important;
                border-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-report-block-item:hover {
                border-color: #e01d75 !important;
                box-shadow: 0 4px 12px rgba(224, 29, 117, 0.2) !important;
            }

            body.efa-dark-mode .block-label {
                color: #ffffff !important;
            }

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

            body.efa-dark-mode .block-drag-handle {
                color: #6b7280 !important;
            }

            body.efa-dark-mode .gw-sortable-placeholder {
                background: #2a2a3e !important;
                border-color: #4a4a6a !important;
            }

            /* Inputs y selects en dark mode */
            body.efa-dark-mode .gw-input,
            body.efa-dark-mode .gw-select,
            body.efa-dark-mode .gw-textarea {
                background: #2a2a3e !important;
                border-color: #3a3a4e !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-input:focus,
            body.efa-dark-mode .gw-select:focus,
            body.efa-dark-mode .gw-textarea:focus {
                border-color: #e01d75 !important;
                box-shadow: 0 0 0 3px rgba(224, 29, 117, 0.2) !important;
            }

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

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

            /* Generate card en dark mode */
            body.efa-dark-mode .gw-generate-card {
                background: linear-gradient(135deg, #e01d75 0%, #c91a6a 100%) !important;
            }

            body.efa-dark-mode .gw-generate-button {
                background: #ffffff !important;
                color: #e01d75 !important;
            }

            body.efa-dark-mode .gw-generate-button:hover {
                background: #f3f4f6 !important;
            }

            /* Date picker en dark mode */
            body.efa-dark-mode .gw-date-preset {
                background: #1f2940 !important;
                border-color: #3a3a4e !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-date-preset:hover {
                background: #2a2a3e !important;
                border-color: #4a4a6a !important;
            }

            body.efa-dark-mode .gw-date-preset.active {
                background: #e01d75 !important;
                border-color: #e01d75 !important;
                color: #ffffff !important;
            }

            /* Botones en dark mode */
            body.efa-dark-mode .gw-save-bar {
                background: #1f2940 !important;
                border-top-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-save-bar .button {
                background: #e01d75 !important;
                border-color: #e01d75 !important;
                color: #ffffff !important;
            }

            body.efa-dark-mode .gw-save-bar .button:hover {
                background: #c91a6a !important;
                border-color: #c91a6a !important;
            }

            /* Toggles en dark mode - Solo para la página de informes */
            body.efa-dark-mode .gw-reports-container .gw-toggle {
                width: 50px !important;
                height: 28px !important;
            }

            body.efa-dark-mode .gw-reports-container .gw-slider {
                background-color: #3a3a4e !important;
                border-radius: 34px !important;
                overflow: hidden !important;
            }

            body.efa-dark-mode .gw-reports-container .gw-slider:hover {
                background-color: #4a4a6a !important;
                border-radius: 34px !important;
            }

            body.efa-dark-mode .gw-reports-container .gw-slider:before {
                border-radius: 50% !important;
                background-color: white !important;
                height: 22px !important;
                width: 22px !important;
            }

            body.efa-dark-mode .gw-reports-container input:checked + .gw-slider {
                background-color: #e01d75 !important;
                border-radius: 34px !important;
            }

            body.efa-dark-mode .gw-reports-container input:checked + .gw-slider:before {
                border-radius: 50% !important;
                transform: translateX(22px) !important;
            }

            body.efa-dark-mode .gw-reports-container input:checked + .gw-slider:hover {
                background-color: #c91a6a !important;
                border-radius: 34px !important;
            }

            /* Modal del informe siempre con fondo blanco, incluso en modo oscuro */
            body.efa-dark-mode .efa-report-modal {
                background: #ffffff !important;
                color: #000000 !important;
            }

            body.efa-dark-mode .efa-report-header {
                background: #f8f9fa !important;
                border-bottom-color: #e0e0e0 !important;
            }

            body.efa-dark-mode .efa-report-header h2 {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-report-body {
                background: #ffffff !important;
                color: #000000 !important;
            }

            body.efa-dark-mode .efa-report-page {
                color: #333 !important;
            }

            body.efa-dark-mode .efa-report-cover h1 {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-report-section {
                background: #fff !important;
            }

            body.efa-dark-mode .efa-report-section h2 {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-kpi-card {
                background: #fff !important;
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-kpi-value {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-kpi-label {
                color: #7f8c8d !important;
            }

            /* Cards del informe siempre con fondo blanco en modo oscuro */
            body.efa-dark-mode .efa-spam-card {
                background: #ffffff !important;
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-spam-card-title {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-spam-card-desc {
                color: #7f8c8d !important;
            }

            body.efa-dark-mode .efa-origin-card,
            body.efa-dark-mode .efa-form-card {
                background: #ffffff !important;
                border-color: #e0e0e0 !important;
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-origin-card .efa-origin-name,
            body.efa-dark-mode .efa-form-card .efa-form-name {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-origin-card .efa-origin-count,
            body.efa-dark-mode .efa-form-card .efa-form-count {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .efa-origin-card .efa-origin-percentage,
            body.efa-dark-mode .efa-form-card .efa-form-percentage {
                color: #7f8c8d !important;
            }

            body.efa-dark-mode .efa-report-cover h1 {
                color: #2c3e50 !important;
            }

            body.efa-dark-mode .report-period {
                color: #7f8c8d !important;
            }

            body.efa-dark-mode .report-total {
                color: #27ae60 !important;
                background: #eafaf1 !important;
            }

            /* Campo de fecha en dark mode */
            body.efa-dark-mode .gw-date-preview {
                background: #2a2a3e !important;
                border-left-color: #e01d75 !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-date-preview strong {
                color: #ffffff !important;
            }

            body.efa-dark-mode .gw-date-preview span,
            body.efa-dark-mode #efa-report-date-display {
                color: #e0e0e0 !important;
            }

            /* Scrollbars en dark mode */
            body.efa-dark-mode .gw-checkbox-list::-webkit-scrollbar-track {
                background: #2a2a3e !important;
            }

            body.efa-dark-mode .gw-checkbox-list::-webkit-scrollbar-thumb {
                background: #4a4a6a !important;
            }

            body.efa-dark-mode .gw-checkbox-list::-webkit-scrollbar-thumb:hover {
                background: #5a5a7a !important;
            }

            @media (max-width: 768px) {
                .gw-reports-container {
                    padding: 20px 15px;
                }

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

                .gw-header-content {
                    flex-direction: column;
                }

                .gw-generate-button {
                    min-width: 100%;
                    padding: 16px 24px;
                }
            }
</style>

<script>
    jQuery(document).ready(function ($) {
        // Configuration variables - using direct PHP output
        var ajaxUrl = <?php echo json_encode(admin_url('admin-ajax.php')); ?>;
        var ajaxNonce = <?php echo json_encode(wp_create_nonce('efa_nonce')); ?>;
        var siteLogo = <?php echo json_encode(get_site_icon_url(512) ?: get_site_icon_url()); ?>;
        var reportConfig = <?php echo json_encode([
            'show_kpis' => get_option('efa_report_show_kpis', '1') === '1',
            'show_timeline' => get_option('efa_report_show_timeline', '1') === '1',
            'show_forms' => get_option('efa_report_show_forms', '1') === '1',
            'show_origins' => get_option('efa_report_show_origins', '1') === '1',
            'show_crm' => get_option('efa_report_show_crm', '1') === '1',
            'show_read' => get_option('efa_report_show_read', '1') === '1',
            'show_spam' => get_option('efa_report_show_spam', '1') === '1',
            'blocks_order' => explode(',', get_option('efa_report_blocks_order', 'kpis,origins,timeline,spam,forms,crm,read')),
        ]); ?>;
        <?php
        // Obtener labels CRM con valores por defecto si no hay configuración
        $crm_labels_default = [
            ['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']
        ];
        $crm_labels = get_option('efa_crm_labels', $crm_labels_default);
        if (empty($crm_labels) || !is_array($crm_labels)) {
            $crm_labels = $crm_labels_default;
        }
        ?>
        var crmLabels = <?php echo json_encode($crm_labels); ?>;
        var defaultTheme = <?php echo json_encode(get_option('efa_default_theme', 'light')); ?>;

        console.log('Reports JS loaded. AJAX URL:', ajaxUrl, 'Nonce:', ajaxNonce);

        // --- INICIALIZACIÓN TEMA (Dark/Light) ---
        // Solo inicializar el tema, sin botón de toggle
        const body = $('body');

        // Función para inicializar el tema
        function initializeTheme() {
            // Si es 'auto', detectar preferencia del sistema
            let themeToUse = defaultTheme;
            if (themeToUse === 'auto') {
                if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                    themeToUse = 'dark';
                } else {
                    themeToUse = 'light';
                }
            }

            // Verificar localStorage primero (si el usuario ya cambió manualmente)
            const savedTheme = localStorage.getItem('efa_theme');
            const finalTheme = savedTheme || themeToUse;

            if (finalTheme === 'dark') {
                $('html').addClass('efa-dark-mode');
                body.addClass('efa-dark-mode');
            }
        }

        // Inicializar tema al cargar
        initializeTheme();

        // Generate report button - AJAX version with modal (Event Delegation)
        $(document).on('click', '#efa-btn-generate-report', function (e) {
            e.preventDefault();
            console.log('Generate Report button clicked (delegated)');
            // alert('Botón pulsado - Iniciando generación...'); // Debug alert

            const $btn = $(this);
            const originalText = $btn.html();

            // Get filters
            const start_date = $('#efa-report-start-date').val();
            const end_date = $('#efa-report-end-date').val();
            const origins = $('.efa-report-origin-check:checked').map(function () { return $(this).val(); }).get();
            const forms = $('.efa-report-form-check:checked').map(function () { return $(this).val(); }).get();

            console.log('Filters:', { start_date, end_date, origins, forms });

            // Validation
            if (origins.length === 0) {
                alert('Por favor, selecciona al menos un origen para el informe.');
                return;
            }
            if (forms.length === 0) {
                alert('Por favor, selecciona al menos un formulario para el informe.');
                return;
            }

            // Loading state
            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update" style="animation: rotation 1s infinite linear; margin-top:4px;"></span> Generando informe...');

            // AJAX call
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'gw_generate_report_data',
                    nonce: ajaxNonce,
                    start_date: start_date,
                    end_date: end_date,
                    origins: origins,
                    forms: forms,
                    all_origins: $('#efa-report-origins-all').is(':checked'),
                    all_forms: $('#efa-report-forms-all').is(':checked')
                },
                success: function (response) {
                    console.log('AJAX Success:', response);
                    $btn.prop('disabled', false).html(originalText);
                    if (response.success) {
                        if (response.data.debug) {
                            console.group('Report Debug Info');
                            console.log('SQL Query:', response.data.debug.sql);
                            console.log('SQL Params:', response.data.debug.params);
                            console.log('Result Count:', response.data.debug.count);
                            console.log('First Result:', response.data.debug.first_result);
                            console.log('Filters:', { origins: response.data.debug.origins_filter, forms: response.data.debug.forms_filter });
                            console.groupEnd();
                        }
                        generateReportModal(response.data);
                    } else {
                        alert('Error al generar el informe: ' + (response.data || 'Error desconocido'));
                    }
                },
                error: function (xhr, status, error) {
                    console.error('Error generating report:', error);
                    $btn.prop('disabled', false).html(originalText);
                    alert('❌ Error al generar el informe. Por favor, inténtalo de nuevo.');
                }
            });
        });

        // Helper to format date as YYYY-MM-DD in local time
        function toLocalISOString(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // Date preset handler
        $('#efa-report-date-preset').on('change', function () {
            const preset = $(this).val();
            const today = new Date();
            let startDate, endDate;

            if (preset === 'custom') {
                $('#efa-report-custom-dates').slideDown();
                return;
            } else {
                $('#efa-report-custom-dates').slideUp();
            }

            switch (preset) {
                case 'last_month':
                    const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                    startDate = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
                    endDate = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0);
                    break;
                case 'last_7':
                    endDate = new Date();
                    startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
                    break;
                case 'last_30':
                    endDate = new Date();
                    startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30);
                    break;
                case 'this_month':
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1);
                    endDate = new Date();
                    break;
            }

            updateDateDisplay(startDate, endDate);
        });

        // Custom dates handler
        $('#efa-report-start-date, #efa-report-end-date').on('change', function () {
            // Create dates from input string YYYY-MM-DD treating them as local
            const startParts = $('#efa-report-start-date').val().split('-');
            const endParts = $('#efa-report-end-date').val().split('-');

            const start = new Date(startParts[0], startParts[1] - 1, startParts[2]);
            const end = new Date(endParts[0], endParts[1] - 1, endParts[2]);

            updateDateDisplay(start, end);
        });

        function updateDateDisplay(start, end) {
            const format = (date) => {
                // Use toLocaleDateString for proper locale-aware formatting
                return date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: 'numeric' });
            };
            $('#efa-report-date-display').text(format(start) + ' - ' + format(end));

            // Set input values using local YYYY-MM-DD format
            $('#efa-report-start-date').val(toLocalISOString(start));
            $('#efa-report-end-date').val(toLocalISOString(end));
        }

        // Origins checkboxes
        $('#efa-report-origins-all').on('change', function () {
            const isChecked = $(this).is(':checked');
            $('.efa-report-origin-check').prop('checked', isChecked);
            updateOriginsCount();
        });

        $('.efa-report-origin-check').on('change', function () {
            updateOriginsCount();
            const allChecked = $('.efa-report-origin-check').length === $('.efa-report-origin-check:checked').length;
            $('#efa-report-origins-all').prop('checked', allChecked);
        });

        function updateOriginsCount() {
            const count = $('.efa-report-origin-check:checked').length;
            const total = $('.efa-report-origin-check').length;
            $('#efa-report-origins-count').text(count);
        }

        // Forms checkboxes
        $('#efa-report-forms-all').on('change', function () {
            const isChecked = $(this).is(':checked');
            $('.efa-report-form-check').prop('checked', isChecked);
            updateFormsCount();
        });

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

        function updateFormsCount() {
            const count = $('.efa-report-form-check:checked').length;
            const total = $('.efa-report-form-check').length;
            $('#efa-report-forms-count').text(count);
        }

        // Sortable blocks - Asegurar que jQuery UI Sortable esté disponible
        if (typeof $.fn.sortable !== 'undefined') {
            if ($("#gw-report-blocks-sortable").length > 0) {
                $("#gw-report-blocks-sortable").sortable({
                    placeholder: "gw-sortable-placeholder",
                    axis: "y",
                    opacity: 0.8,
                    handle: ".block-drag-handle",
                    cursor: "move",
                    tolerance: "pointer",
                    update: function (event, ui) {
                        const newOrder = [];
                        $(".gw-report-block-item").each(function () {
                            newOrder.push($(this).data("id"));
                        });
                        $("#efa_report_blocks_order").val(newOrder.join(","));
                        $("#efa_report_blocks_order_final").val(newOrder.join(","));
                        console.log('Blocks order updated:', newOrder.join(","));
                    }
                });
                console.log('Sortable initialized on #gw-report-blocks-sortable');
            } else {
                console.warn('Element #gw-report-blocks-sortable not found');
            }
        } else {
            console.error('jQuery UI Sortable is not available. Make sure jquery-ui-sortable is enqueued.');
            // Intentar cargar después de un delay
            setTimeout(function() {
                if (typeof $.fn.sortable !== 'undefined' && $("#gw-report-blocks-sortable").length > 0) {
                    $("#gw-report-blocks-sortable").sortable({
                        placeholder: "gw-sortable-placeholder",
                        axis: "y",
                        opacity: 0.8,
                        handle: ".block-drag-handle",
                        cursor: "move",
                        tolerance: "pointer",
                        update: function (event, ui) {
                            const newOrder = [];
                            $(".gw-report-block-item").each(function () {
                                newOrder.push($(this).data("id"));
                            });
                            $("#efa_report_blocks_order").val(newOrder.join(","));
                            $("#efa_report_blocks_order_final").val(newOrder.join(","));
                            console.log('Blocks order updated:', newOrder.join(","));
                        }
                    });
                    console.log('Sortable initialized (delayed)');
                }
            }, 500);
        }

        // Helper to format date
        function formatDate(dateString) {
            if (!dateString) return '';
            // Asumir formato YYYY-MM-DD y evitar problemas de zona horaria
            const parts = dateString.split('-');
            if (parts.length === 3) {
                return `${parts[2]}/${parts[1]}/${parts[0]}`;
            }
            return dateString;
        }

        // Function to generate report modal
        function generateReportModal(reportData) {
            console.log('Generating report modal with data:', reportData);
            const { data: rows, start_date, end_date, total, start_date_formatted, end_date_formatted, deleted_spam_count } = reportData;

            // Ensure rows is an array
            const rowsArray = Array.isArray(rows) ? rows : Object.values(rows);

            // Use server formatted dates if available, otherwise fallback
            const displayStart = start_date_formatted || formatDate(start_date);
            const displayEnd = end_date_formatted || formatDate(end_date);

            // Use predefined configuration
            const config = reportConfig;

            // Calculate aggregates
            let originsCount = {};
            let formsCount = {};
            let crmCount = {};
            let readCount = { read: 0, unread: 0 };
            let spamCount = { spam: 0, clean: 0 };

            // Función para normalizar nombres de orígenes (eliminar dominios y unificar mayúsculas)
            function normalizeOriginName(origin) {
                if (!origin) return 'Organico';
                const trimmed = (origin || '').toString().trim();
                if (trimmed === '') return 'Organico';
                
                // Convertir a minúsculas para procesamiento
                let normalized = trimmed.toLowerCase();
                
                // Eliminar terminaciones de dominio comunes (.com, .es, .net, .org, .io, .co, etc.)
                const domainPatterns = [
                    /\.com$/i, /\.es$/i, /\.net$/i, /\.org$/i, /\.io$/i, /\.co$/i,
                    /\.eu$/i, /\.uk$/i, /\.fr$/i, /\.de$/i, /\.it$/i, /\.pt$/i,
                    /\.mx$/i, /\.ar$/i, /\.cl$/i, /\.br$/i, /\.us$/i, /\.ca$/i
                ];
                
                for (const pattern of domainPatterns) {
                    normalized = normalized.replace(pattern, '');
                }
                
                // Capitalizar primera letra
                normalized = normalized.charAt(0).toUpperCase() + normalized.slice(1);
                
                return normalized;
            }
            
            rowsArray.forEach(row => {
                // Origins - Normalizar nombre (unificar mayúsculas/minúsculas y eliminar dominios)
                const origin = row.origin || 'Desconocido';
                const normalizedOrigin = normalizeOriginName(origin);
                originsCount[normalizedOrigin] = (originsCount[normalizedOrigin] || 0) + 1;

                // Forms
                const form = row.form || 'Desconocido';
                formsCount[form] = (formsCount[form] || 0) + 1;

                // CRM States
                const status = row.crm_status || 'new';
                crmCount[status] = (crmCount[status] || 0) + 1;

                // Read Status
                if (row.read_status == 1) {
                    readCount.read++;
                } else {
                    readCount.unread++;
                }

                // Spam
                if (row.is_spam) {
                    spamCount.spam++;
                } else {
                    spamCount.clean++;
                }
            });

            // Timeline data - group by date
            let timelineData = {};
            let originTimelineData = {};

            // Helper to normalize origin names (eliminar dominios y unificar mayúsculas/minúsculas)
            function normalizeOrigin(origin) {
                if (!origin) return 'Organico';
                const trimmed = origin.trim();
                if (!trimmed) return 'Organico';
                
                // Convertir a minúsculas para procesamiento
                let normalized = trimmed.toLowerCase();
                
                // Eliminar terminaciones de dominio comunes (.com, .es, .net, .org, .io, .co, etc.)
                const domainPatterns = [
                    /\.com$/i, /\.es$/i, /\.net$/i, /\.org$/i, /\.io$/i, /\.co$/i,
                    /\.eu$/i, /\.uk$/i, /\.fr$/i, /\.de$/i, /\.it$/i, /\.pt$/i,
                    /\.mx$/i, /\.ar$/i, /\.cl$/i, /\.br$/i, /\.us$/i, /\.ca$/i
                ];
                
                for (const pattern of domainPatterns) {
                    normalized = normalized.replace(pattern, '');
                }
                
                // Capitalizar primera letra
                normalized = normalized.charAt(0).toUpperCase() + normalized.slice(1);
                
                return normalized;
            }

            rowsArray.forEach(row => {
                const date = row.created_at.split(' ')[0]; // Extract date only (YYYY-MM-DD)

                // Total per day
                timelineData[date] = (timelineData[date] || 0) + 1;

                // Per origin per day - normalize origin name
                const rawOrigin = row.origin || 'Organico';
                const origin = normalizeOrigin(rawOrigin);
                if (!originTimelineData[origin]) {
                    originTimelineData[origin] = {};
                }
                originTimelineData[origin][date] = (originTimelineData[origin][date] || 0) + 1;
            });

            // Build HTML
            let html = `
                                                                                                                                                                                                                                                                                                        <div class="efa-report-page">
                                                                                                                                                                                                                                                                                                            <div class="efa-report-cover">
                                                                                                                                                                                                                                                                                                                <img src="${siteLogo}" alt="Logo" class="efa-report-logo">
                                                                                                                                                                                                                                                                                                                <h1>Informe de Leads</h1>
                                                                                                                                                                                                                                                                                                                <p class="report-period">Periodo: ${displayStart} - ${displayEnd}</p>
                                                                                                                                                                                                                                                                                                                <p class="report-total">Total de Leads: ${total}</p>
                                                                                                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                                                                                                    `;

            // Helper function to check if a block is enabled
            const isBlockEnabled = (blockId) => {
                switch(blockId) {
                    case 'kpis': return config.show_kpis;
                    case 'timeline': return config.show_timeline;
                    case 'forms': return config.show_forms;
                    case 'origins': return config.show_origins;
                    case 'crm': return config.show_crm;
                    case 'read': return config.show_read;
                    case 'spam': return config.show_spam;
                    default: return false;
                }
            };

            // Función para obtener color (debe estar antes de los blockRenderers para que esté disponible)
            function getColorForString(str) {
                if (!str) return '#646970';
                const 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' };
                const FALLBACK_PALETTE = ['#0d9488', '#be123c', '#d97706', '#4338ca', '#a21caf', '#15803d', '#0369a1', '#b91c1c'];
                const lower = str.toLowerCase().trim();
                if (SEMANTIC_COLORS[lower]) return SEMANTIC_COLORS[lower];
                for (const [key, color] of Object.entries(SEMANTIC_COLORS)) {
                    if (lower.includes(key)) return color;
                }
                let hash = 0;
                for (let i = 0; i < str.length; i++) {
                    hash = str.charCodeAt(i) + ((hash << 5) - hash);
                }
                return FALLBACK_PALETTE[Math.abs(hash % FALLBACK_PALETTE.length)];
            }

            // Función para aclarar colores (para gradientes)
            function lightenColor(hex, percent) {
                const num = parseInt(hex.replace('#', ''), 16);
                const amt = Math.round(2.55 * percent);
                const R = Math.min(255, (num >> 16) + amt);
                const G = Math.min(255, ((num >> 8) & 0x00FF) + amt);
                const B = Math.min(255, (num & 0x0000FF) + amt);
                return '#' + (0x1000000 + R * 0x10000 + G * 0x100 + B).toString(16).slice(1);
            }

            // Block Renderers Map
            const blockRenderers = {
                'kpis': () => {
                    if (!config.show_kpis) return '';
                    const spamRate = total > 0 ? ((spamCount.spam / total) * 100).toFixed(1) : 0;
                    const qualifiedCount = total - spamCount.spam;
                    const qualifiedRate = total > 0 ? ((qualifiedCount / total) * 100).toFixed(1) : 0;
                    const readRate = total > 0 ? ((readCount.read / total) * 100).toFixed(1) : 0;

                    return `
                                                                            <div class="efa-report-section">
                                                                                <h2 class="efa-report-section-title" style="margin-bottom: 25px;">📊 KPIs Generales</h2>
                                                                                <div class="efa-spam-grid" style="grid-template-columns: repeat(3, 1fr);">
                                                                                    <!-- Card 1: Total Leads -->
                                                                                    <div class="efa-spam-card efa-spam-card-total">
                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                        <div class="efa-spam-icon">
                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                                                                                                <circle cx="9" cy="7" r="4"></circle>
                                                                                                <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                                                                                                <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                                                                                            </svg>
                                                                                        </div>
                                                                                        <div class="efa-spam-content">
                                                                                            <div class="efa-spam-label">Total Leads</div>
                                                                                            <div class="efa-spam-value">${total}</div>
                                                                                            <div class="efa-spam-desc">En el periodo seleccionado</div>
                                                                                            <div class="efa-spam-bar">
                                                                                                <div class="efa-spam-bar-fill" style="width: 100%; background: linear-gradient(90deg, #5d5dfa, #8080ff);"></div>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>

                                                                                    <!-- Card 2: Tasa de Spam -->
                                                                                    <div class="efa-spam-card efa-spam-card-spam">
                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                        <div class="efa-spam-icon">
                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                <circle cx="12" cy="12" r="10"></circle>
                                                                                                <line x1="15" y1="9" x2="9" y2="15"></line>
                                                                                                <line x1="9" y1="9" x2="15" y2="15"></line>
                                                                                            </svg>
                                                                                        </div>
                                                                                        <div class="efa-spam-content">
                                                                                            <div class="efa-spam-label">Tasa de Spam</div>
                                                                                            <div class="efa-spam-value">${spamRate}%</div>
                                                                                            <div class="efa-spam-desc">${spamCount.spam} detectados como spam</div>
                                                                                            <div class="efa-spam-bar">
                                                                                                <div class="efa-spam-bar-fill" style="width: ${spamRate}%; background: linear-gradient(90deg, #ef4444, #f87171);"></div>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>

                                                                                    <!-- Card 3: Leads Cualificados -->
                                                                                    <div class="efa-spam-card efa-spam-card-clean">
                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                        <div class="efa-spam-icon">
                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                <polyline points="20 6 9 17 4 12"></polyline>
                                                                                            </svg>
                                                                                        </div>
                                                                                        <div class="efa-spam-content">
                                                                                            <div class="efa-spam-label">Cualificados</div>
                                                                                            <div class="efa-spam-value">${qualifiedRate}%</div>
                                                                                            <div class="efa-spam-desc">${qualifiedCount} leads cualificados</div>
                                                                                            <div class="efa-spam-bar">
                                                                                                <div class="efa-spam-bar-fill" style="width: ${qualifiedRate}%; background: linear-gradient(90deg, #10b981, #34d399);"></div>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        `;
                },
                'timeline': () => {
                    if (!config.show_timeline || Object.keys(timelineData).length === 0) return '';
                    return `
                                                                                                                                                                                                            <div class="efa-report-section">
                                                                                                                                                                                                                <h2>Evolución de Leads</h2>
                        
                                                                                                                                                                                                                <!-- Bar Chart: Total Leads per Day -->
                                                                                                                                                                                                                <div class="chart-wrapper" style="margin-bottom: 40px;">
                                                                                                                                                                                                                    <h3 style="font-size: 16px; margin-bottom: 15px; color: #666;">Total Leads por Día</h3>
                                                                                                                                                                                                                    <div class="efa-chart-container" style="max-width: 100%; height: 300px;">
                                                                                                                                                                                                                        <canvas id="report-timeline-bar"></canvas>
                                                                                                                                                                                                                    </div>
                                                                                                                                                                                                                </div>
                        
                                                                                                                                                                                                                <!-- Line Chart: Evolution by Origin -->
                                                                                                                                                                                                                <div class="chart-wrapper">
                                                                                                                                                                                                                    <h3 style="font-size: 16px; margin-bottom: 15px; color: #666;">Evolución por Origen</h3>
                                                                                                                                                                                                                    <div class="efa-chart-container" style="max-width: 100%; height: 300px;">
                                                                                                                                                                                                                        <canvas id="report-timeline-line"></canvas>
                                                                                                                                                                                                                    </div>
                                                                                                                                                                                                                </div>
                                                                                                                                                                                                            </div>
                                                                                                                                                                                                        `;
                },
                'forms': () => {
                    if (!config.show_forms || Object.keys(formsCount).length === 0) return '';
                    
                    // Ordenar formularios por cantidad (descendente)
                    const sortedForms = Object.entries(formsCount)
                        .map(([name, count]) => ({ name, count }))
                        .sort((a, b) => b.count - a.count);
                    
                    // Calcular total para porcentajes
                    const totalForms = sortedForms.reduce((sum, item) => sum + item.count, 0);
                    
                    // Generar cards de 3 en 3
                    let cardsHtml = '';
                    sortedForms.forEach((form) => {
                        const percentage = totalForms > 0 ? ((form.count / totalForms) * 100).toFixed(1) : 0;
                        
                        // Obtener color del formulario usando la misma función que la gráfica del dashboard
                        const formColor = getColorForString(form.name);
                        
                        // Círculo pequeño con el color del formulario
                        const circleHtml = `
                            <div style="width: 12px; height: 12px; border-radius: 50%; background-color: ${formColor}; margin-right: 8px; flex-shrink: 0;"></div>
                        `;
                        
                        // Usar clase genérica para todas las cards
                        const cardClass = 'efa-spam-card efa-spam-card-default';
                        const gradientColor = `linear-gradient(90deg, ${formColor}, ${formColor}dd)`;
                        
                        // Crear card
                        cardsHtml += `
                            <div class="${cardClass}">
                                <div class="efa-spam-card-bg"></div>
                                <div class="efa-spam-content">
                                    <div class="efa-spam-label" style="display: flex; align-items: center; margin-bottom: 8px;">
                                        ${circleHtml}
                                        <span>${form.name}</span>
                                    </div>
                                    <div class="efa-spam-value">${form.count}</div>
                                    <div class="efa-spam-desc">${percentage}% del total</div>
                                    <div class="efa-spam-bar">
                                        <div class="efa-spam-bar-fill" style="width: ${percentage}%; background: ${gradientColor};"></div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    return `
                        <div class="efa-report-section">
                            <h2 class="efa-report-section-title" style="margin-bottom: 25px;">📝 Distribución por Formularios</h2>
                            <div class="efa-spam-grid" style="grid-template-columns: repeat(3, 1fr);">
                                ${cardsHtml}
                            </div>
                        </div>
                    `;
                },
                'origins': () => {
                    if (!config.show_origins || Object.keys(originsCount).length === 0) return '';
                    
                    // Ordenar orígenes por cantidad (descendente)
                    const sortedOrigins = Object.entries(originsCount)
                        .map(([name, count]) => ({ name, count }))
                        .sort((a, b) => b.count - a.count);
                    
                    // Calcular total para porcentajes
                    const totalOrigins = sortedOrigins.reduce((sum, item) => sum + item.count, 0);
                    
                    // Generar cards de 3 en 3
                    let cardsHtml = '';
                    sortedOrigins.forEach((origin, index) => {
                        const position = index + 1;
                        const percentage = totalOrigins > 0 ? ((origin.count / totalOrigins) * 100).toFixed(1) : 0;
                        
                        // Obtener color del origen usando la misma función que la gráfica de tendencia
                        const originColor = getColorForString(origin.name);
                        
                        // Círculo pequeño con el color del origen
                        const circleHtml = `
                            <div style="width: 12px; height: 12px; border-radius: 50%; background-color: ${originColor}; margin-right: 8px; flex-shrink: 0;"></div>
                        `;
                        
                        // Usar clase genérica para todas las cards
                        const cardClass = 'efa-spam-card efa-spam-card-default';
                        const gradientColor = `linear-gradient(90deg, ${originColor}, ${originColor}dd)`;
                        
                        // Crear card
                        cardsHtml += `
                            <div class="${cardClass}">
                                <div class="efa-spam-card-bg"></div>
                                <div class="efa-spam-content">
                                    <div class="efa-spam-label" style="display: flex; align-items: center; margin-bottom: 8px;">
                                        ${circleHtml}
                                        <span>${origin.name}</span>
                                    </div>
                                    <div class="efa-spam-value">${origin.count}</div>
                                    <div class="efa-spam-desc">${percentage}% del total</div>
                                    <div class="efa-spam-bar">
                                        <div class="efa-spam-bar-fill" style="width: ${percentage}%; background: ${gradientColor};"></div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    return `
                        <div class="efa-report-section">
                            <h2 class="efa-report-section-title" style="margin-bottom: 25px;">🌍 Distribución por Orígenes</h2>
                            <div class="efa-spam-grid" style="grid-template-columns: repeat(3, 1fr);">
                                ${cardsHtml}
                            </div>
                        </div>
                    `;
                },
                'crm': () => {
                    if (!config.show_crm || Object.keys(crmCount).length === 0) return '';
                    
                    // Debug: verificar que crmLabels esté disponible
                    if (!crmLabels || !Array.isArray(crmLabels)) {
                        console.warn('crmLabels no está disponible o no es un array:', crmLabels);
                    }
                    
                    // Obtener total para calcular porcentajes
                    const totalCrm = Object.values(crmCount).reduce((sum, count) => sum + count, 0);
                    
                    // Crear array de estados con sus datos
                    const crmStates = [];
                    Object.entries(crmCount).forEach(([statusId, count]) => {
                        // Buscar el label y color del estado en crmLabels
                        // Asegurarse de que crmLabels esté definido y sea un array
                        let labelObj = null;
                        if (crmLabels && Array.isArray(crmLabels)) {
                            labelObj = crmLabels.find(l => l && l.id === statusId);
                        }
                        
                        if (labelObj && labelObj.label && labelObj.color) {
                            // Usar el label visible y el color configurado
                            crmStates.push({
                                id: statusId,
                                label: labelObj.label, // Nombre visible
                                color: labelObj.color, // Color configurado
                                count: count
                            });
                        } else {
                            // Si no se encuentra, intentar usar valores por defecto conocidos
                            const defaultLabels = {
                                'new': { label: 'Nuevo', color: '#2271b1' },
                                'contacted': { label: 'Contactado', color: '#f59e0b' },
                                'budget': { label: 'Presupuesto', color: '#9333ea' },
                                'won': { label: 'Ganado', color: '#16a34a' },
                                'lost': { label: 'Perdido', color: '#dc2626' }
                            };
                            
                            const defaultLabel = defaultLabels[statusId];
                            if (defaultLabel) {
                                crmStates.push({
                                    id: statusId,
                                    label: defaultLabel.label,
                                    color: defaultLabel.color,
                                    count: count
                                });
                            } else {
                                // Último recurso: usar el ID capitalizado
                                crmStates.push({
                                    id: statusId,
                                    label: statusId.charAt(0).toUpperCase() + statusId.slice(1),
                                    color: '#646970',
                                    count: count
                                });
                            }
                        }
                    });
                    
                    // Ordenar por cantidad (descendente)
                    crmStates.sort((a, b) => b.count - a.count);
                    
                    // Generar cards con diseño brutal
                    let cardsHtml = '';
                    crmStates.forEach((state) => {
                        const percentage = totalCrm > 0 ? ((state.count / totalCrm) * 100).toFixed(1) : 0;
                        
                        const lightColor = lightenColor(state.color, 20);
                        const gradientColor = `linear-gradient(90deg, ${state.color}, ${lightColor})`;
                        
                        // Card con diseño brutal usando el color del estado
                        cardsHtml += `
                            <div class="efa-spam-card efa-spam-card-default" style="border-left: 4px solid ${state.color}; position: relative; overflow: hidden;">
                                <div class="efa-spam-card-bg" style="background: radial-gradient(circle, ${state.color}15 0%, transparent 70%);"></div>
                                <div class="efa-spam-content">
                                    <div class="efa-spam-label" style="display: flex; align-items: center; margin-bottom: 12px;">
                                        <div style="width: 14px; height: 14px; border-radius: 50%; background-color: ${state.color}; margin-right: 10px; flex-shrink: 0; box-shadow: 0 2px 8px ${state.color}40;"></div>
                                        <span style="font-weight: 600; color: #2c3e50; font-size: 15px;">${state.label}</span>
                                    </div>
                                    <div class="efa-spam-value" style="background: linear-gradient(135deg, ${state.color}, ${lightColor}); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; font-size: 32px; font-weight: 700; margin: 8px 0; line-height: 1.2;">${state.count}</div>
                                    <div class="efa-spam-desc" style="color: #7f8c8d; margin-bottom: 12px; font-size: 13px;">${percentage}% del total</div>
                                    <div class="efa-spam-bar" style="height: 6px; background: #e5e7eb; border-radius: 10px; overflow: hidden; margin-top: 8px;">
                                        <div class="efa-spam-bar-fill" style="width: ${percentage}%; height: 100%; background: ${gradientColor}; border-radius: 10px; box-shadow: 0 2px 8px ${state.color}40; transition: width 0.3s ease;"></div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    
                    return `
                        <div class="efa-report-section">
                            <h2 class="efa-report-section-title" style="margin-bottom: 25px;">🏷️ Distribución por Estados CRM</h2>
                            <div class="efa-spam-grid" style="grid-template-columns: repeat(3, 1fr);">
                                ${cardsHtml}
                            </div>
                        </div>
                    `;
                },
                'read': () => {
                    if (!config.show_read) return '';
                    
                    const readRate = total > 0 ? ((readCount.read / total) * 100).toFixed(1) : 0;
                    const unreadRate = total > 0 ? ((readCount.unread / total) * 100).toFixed(1) : 0;
                    
                    return `
                        <div class="efa-report-section">
                            <h2 class="efa-report-section-title" style="margin-bottom: 25px;">👁️ Correos Leídos/No Leídos</h2>
                            <div class="efa-spam-grid" style="grid-template-columns: repeat(2, 1fr);">
                                <!-- Card 1: Leídos -->
                                <div class="efa-spam-card efa-spam-card-read">
                                    <div class="efa-spam-card-bg"></div>
                                    <div class="efa-spam-icon">
                                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                            <circle cx="12" cy="12" r="3"></circle>
                                        </svg>
                                    </div>
                                    <div class="efa-spam-content">
                                        <div class="efa-spam-label">Leídos</div>
                                        <div class="efa-spam-value">${readCount.read}</div>
                                        <div class="efa-spam-desc">${readRate}% del total</div>
                                        <div class="efa-spam-bar">
                                            <div class="efa-spam-bar-fill" style="width: ${readRate}%; background: linear-gradient(90deg, #f59e0b, #fbbf24);"></div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Card 2: No Leídos -->
                                <div class="efa-spam-card efa-spam-card-default">
                                    <div class="efa-spam-card-bg"></div>
                                    <div class="efa-spam-icon" style="background: linear-gradient(135deg, #6b7280, #9ca3af); box-shadow: 0 8px 16px rgba(107, 114, 128, 0.3);">
                                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                            <line x1="1" y1="1" x2="23" y2="23"></line>
                                        </svg>
                                    </div>
                                    <div class="efa-spam-content">
                                        <div class="efa-spam-label">No Leídos</div>
                                        <div class="efa-spam-value" style="background: linear-gradient(135deg, #6b7280, #9ca3af); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;">${readCount.unread}</div>
                                        <div class="efa-spam-desc">${unreadRate}% del total</div>
                                        <div class="efa-spam-bar">
                                            <div class="efa-spam-bar-fill" style="width: ${unreadRate}%; background: linear-gradient(90deg, #6b7280, #9ca3af);"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                },
                'spam': () => {
                    if (!config.show_spam) return '';
                    const cleanLeads = spamCount.clean;
                    const spamLeads = spamCount.spam;
                    const deletedSpam = deleted_spam_count || 0;
                    const cleanRate = total > 0 ? ((cleanLeads / total) * 100).toFixed(1) : 0;
                    const spamRate = total > 0 ? ((spamLeads / total) * 100).toFixed(1) : 0;
                    const deletedRate = (total + deletedSpam) > 0 ? ((deletedSpam / (total + deletedSpam)) * 100).toFixed(1) : 0;

                    return `
                                                                                                            <div class="efa-report-section">
                                                                                                                <h2 class="efa-report-section-title" style="margin-bottom: 25px;">🛡️ Detección de Spam</h2>
                                                                                                                <div class="efa-spam-grid" style="grid-template-columns: repeat(3, 1fr);">
                                                                                                                    <!-- Card 1: Tasa de Limpieza -->
                                                                                                                    <div class="efa-spam-card efa-spam-card-clean">
                                                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                                                        <div class="efa-spam-icon">
                                                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                                                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                                                                                                                                <polyline points="22 4 12 14.01 9 11.01"></polyline>
                                                                                                                            </svg>
                                                                                                                        </div>
                                                                                                                        <div class="efa-spam-content">
                                                                                                                            <div class="efa-spam-label">Tasa de Limpieza</div>
                                                                                                                            <div class="efa-spam-value">${cleanLeads}</div>
                                                                                                                            <div class="efa-spam-desc">${cleanRate}% de tasa de limpieza</div>
                                                                                                                            <div class="efa-spam-bar">
                                                                                                                                <div class="efa-spam-bar-fill" style="width: ${cleanRate}%; background: linear-gradient(90deg, #10b981, #34d399);"></div>
                                                                                                                            </div>
                                                                                                                        </div>
                                                                                                                    </div>

                                                                                                                    <!-- Card 2: Spam Detectado -->
                                                                                                                    <div class="efa-spam-card efa-spam-card-spam">
                                                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                                                        <div class="efa-spam-icon">
                                                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                                                <circle cx="12" cy="12" r="10"></circle>
                                                                                                                                <line x1="15" y1="9" x2="9" y2="15"></line>
                                                                                                                                <line x1="9" y1="9" x2="15" y2="15"></line>
                                                                                                                            </svg>
                                                                                                                        </div>
                                                                                                                        <div class="efa-spam-content">
                                                                                                                            <div class="efa-spam-label">Spam Detectado</div>
                                                                                                                            <div class="efa-spam-value">${spamLeads}</div>
                                                                                                                            <div class="efa-spam-desc">${spamRate}% del total</div>
                                                                                                                            <div class="efa-spam-bar">
                                                                                                                                <div class="efa-spam-bar-fill" style="width: ${spamRate}%; background: linear-gradient(90deg, #ef4444, #f87171);"></div>
                                                                                                                            </div>
                                                                                                                        </div>
                                                                                                                    </div>

                                                                                                                    <!-- Card 3: Spam Borrado -->
                                                                                                                    <div class="efa-spam-card efa-spam-card-deleted">
                                                                                                                        <div class="efa-spam-card-bg"></div>
                                                                                                                        <div class="efa-spam-icon">
                                                                                                                            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                                                                                                                <polyline points="3 6 5 6 21 6"></polyline>
                                                                                                                                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                                                                                                                <line x1="10" y1="11" x2="10" y2="17"></line>
                                                                                                                                <line x1="14" y1="11" x2="14" y2="17"></line>
                                                                                                                            </svg>
                                                                                                                        </div>
                                                                                                                        <div class="efa-spam-content">
                                                                                                                            <div class="efa-spam-label">Spam Borrado</div>
                                                                                                                            <div class="efa-spam-value">${deletedSpam}</div>
                                                                                                                            <div class="efa-spam-desc">${deletedRate}% del total procesado</div>
                                                                                                                            <div class="efa-spam-bar">
                                                                                                                                <div class="efa-spam-bar-fill" style="width: ${deletedRate}%; background: linear-gradient(90deg, #8b5cf6, #a78bfa);"></div>
                                                                                                                            </div>
                                                                                                                        </div>
                                                                                                                    </div>
                                                                                                                </div>
                                                                                                            </div>
                                                                                                        `;
                },
            };

            // Default order if not configured
            const defaultOrder = ['kpis', 'origins', 'timeline', 'spam', 'forms', 'crm', 'read'];
            const savedBlocksOrder = config.blocks_order && config.blocks_order.length > 0 ? config.blocks_order : defaultOrder;

            // Filter blocks order to only include enabled blocks, maintaining the saved order
            const blocksOrder = savedBlocksOrder.filter(blockId => isBlockEnabled(blockId));

            // Append blocks in order (only enabled ones, respecting saved order)
            blocksOrder.forEach(blockId => {
                if (blockRenderers[blockId]) {
                    const blockHtml = blockRenderers[blockId]();
                    // Only append if block returns content (not empty string)
                    if (blockHtml && blockHtml.trim() !== '') {
                        html += blockHtml;
                    }
                }
            });

            // Old block rendering code removed - now handled by blockRenderers above

            html += '</div>'; // Close efa-report-page

            // Create or update modal
            if ($('.efa-report-overlay').length === 0) {
                $('body').append(`
                                                                                                                                                                                                                                                                                                            <div class="efa-report-overlay">
                                                                                                                                                                                                                                                                                                                <div class="efa-report-modal">
                                                                                                                                                                                                                                                                                                                    <div class="efa-report-header">
                                                                                                                                                                                                                                                                                                                        <h2>Vista Previa del Informe</h2>
                                                                                                                                                                                                                                                                                                                        <div class="efa-report-actions">
                                                                                                                                                                                                                                                                                                                            <button class="efa-report-btn print" onclick="window.print()"><span class="dashicons dashicons-printer"></span> Imprimir / PDF</button>
                                                                                                                                                                                                                                                                                                                            <button class="efa-report-btn close"><span class="dashicons dashicons-no-alt"></span> Cerrar</button>
                                                                                                                                                                                                                                                                                                                        </div>
                                                                                                                                                                                                                                                                                                                    </div>
                                                                                                                                                                                                                                                                                                                    <div class="efa-report-content" id="efa-report-body"></div>
                                                                                                                                                                                                                                                                                                                </div>
                                                                                                                                                                                                                                                                                                            </div>
                                                                                                                                                                                                                                                                                                        `);

                $('.efa-report-btn.close').on('click', function () {
                    $('.efa-report-overlay').removeClass('open');
                });

                $('.efa-report-overlay').on('click', function (e) {
                    if ($(e.target).is('.efa-report-overlay')) {
                        $('.efa-report-overlay').removeClass('open');
                    }
                });
            }

            // Insert HTML
            $('#efa-report-body').html(html);
            $('.efa-report-overlay').addClass('open');

            // Render charts
            setTimeout(() => {
                // Check if Chart.js is loaded
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js not loaded yet, waiting...');
                    setTimeout(arguments.callee, 500); // Retry after 500ms
                    return;
                }

                // Forms and Origins charts removed - now using cards instead
                if (config.show_crm && document.getElementById('report-crm-chart')) {
                    const crmData = {};
                    Object.keys(crmCount).forEach(key => {
                        const label = crmLabels.find(l => l.id === key);
                        crmData[label ? label.label : key] = crmCount[key];
                    });
                    renderPieChart('report-crm-chart', crmData, 'Estados CRM');
                }
                // Read status now uses cards instead of charts
                // Spam detection now uses cards instead of charts
                // Timeline charts
                if (config.show_timeline) {
                    if (document.getElementById('report-timeline-bar')) {
                        renderBarChart('report-timeline-bar', timelineData, 'Total Leads por Día');
                    }
                    if (document.getElementById('report-timeline-line')) {
                        renderLineChart('report-timeline-line', originTimelineData, 'Evolución por Origen');
                    }
                }
            }, 500); // Increased delay to ensure Chart.js loads
        }

        // Helper function to render pie charts
        function renderPieChart(canvasId, data, title) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(data),
                    datasets: [{
                        data: Object.values(data),
                        backgroundColor: ['#5d5dfa', '#00e676', '#ffeb3b', '#ff5252', '#00bcd4', '#ff9800', '#9c27b0']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { position: 'bottom' },
                        title: { display: false }
                    }
                }
            });
        }

        // Helper function to render bar charts
        function renderBarChart(canvasId, data, title) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            // Sort dates chronologically
            const sortedDates = Object.keys(data).sort();
            const values = sortedDates.map(date => data[date]);

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: sortedDates.map(d => formatShortDate(d)),
                    datasets: [{
                        label: 'Leads',
                        data: values,
                        backgroundColor: '#a855f7', // Purple like user's example
                        borderRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        title: { display: false }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { stepSize: 1 }
                        }
                    }
                }
            });
        }

        // Helper function to render line charts
        function renderLineChart(canvasId, originData, title) {
            const ctx = document.getElementById(canvasId);
            if (!ctx) return;

            // Get all unique dates and sort
            const allDates = new Set();
            Object.values(originData).forEach(dates => {
                Object.keys(dates).forEach(date => allDates.add(date));
            });
            const sortedDates = Array.from(allDates).sort();

            // Use same color logic as dashboard
            const 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'
            };
            const FALLBACK_PALETTE = ['#0d9488', '#be123c', '#d97706', '#4338ca', '#a21caf', '#15803d', '#0369a1', '#b91c1c'];

            function getColorForString(str) {
                if (!str) return '#646970';
                const lower = str.toLowerCase().trim();
                if (SEMANTIC_COLORS[lower]) return SEMANTIC_COLORS[lower];
                for (const [key, color] of Object.entries(SEMANTIC_COLORS)) {
                    if (lower.includes(key)) return color;
                }
                let hash = 0;
                for (let i = 0; i < str.length; i++) {
                    hash = str.charCodeAt(i) + ((hash << 5) - hash);
                }
                return FALLBACK_PALETTE[Math.abs(hash % FALLBACK_PALETTE.length)];
            }

            const datasets = Object.keys(originData).map(origin => ({
                label: origin,
                data: sortedDates.map(date => originData[origin][date] || 0),
                borderColor: getColorForString(origin),
                backgroundColor: 'transparent',
                tension: 0.3,
                pointRadius: 4,
                pointHoverRadius: 6
            }));

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: sortedDates.map(d => formatShortDate(d)),
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'top' }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { stepSize: 1 }
                        }
                    }
                }
            });
        }

        // Helper to format dates
        function formatShortDate(dateStr) {
            const [year, month, day] = dateStr.split('-');
            return `${day}/${month}`;
        }

        // Helper function to format dates
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('es-ES');
        }


        // Save filter selections before form submit
        $('form').on('submit', function () {
            const selectedOrigins = $('.efa-report-origin-check:checked').map(function () { return $(this).val(); }).get();
            const selectedForms = $('.efa-report-form-check:checked').map(function () { return $(this).val(); }).get();
            $('#selected_origins').val(selectedOrigins.join(','));
            $('#selected_forms').val(selectedForms.join(','));
        });

        // Trigger default date calculation
        $('#efa-report-date-preset').trigger('change');

        // Interceptar el submit del formulario para guardar flag en sessionStorage
        $('form').on('submit', function(e) {
            const submitButton = $(this).find('button[name="gw_save_report_settings"]');
            if (submitButton.length > 0) {
                console.log('Formulario de guardar detectado, guardando flag en sessionStorage...');
                sessionStorage.setItem('gw_reports_settings_saved', 'true');
            }
        });

        // Mostrar modal de éxito al guardar configuración
        function showSaveSuccessModal() {
            console.log('=== INICIANDO showSaveSuccessModal (REPORTS) ===');
            
            // Verificar sessionStorage primero (más confiable que parámetros de URL)
            const savedFlag = sessionStorage.getItem('gw_reports_settings_saved');
            console.log('Flag en sessionStorage:', savedFlag);
            
            // También verificar parámetros de URL por si acaso
            const urlParams = new URLSearchParams(window.location.search);
            const urlString = window.location.href;
            const urlMatch = urlString.match(/[?&]updated=([^&]*)/);
            const updatedParam1 = urlParams.get('updated');
            const updatedParam2 = urlMatch ? urlMatch[1] : null;
            
            console.log('URL completa:', urlString);
            console.log('Parámetro updated (URLSearchParams):', updatedParam1);
            console.log('Parámetro updated (regex):', updatedParam2);
            console.log('Swal disponible:', typeof Swal !== 'undefined');
            console.log('Swal.fire disponible:', typeof Swal !== 'undefined' && typeof Swal.fire === 'function');
            
            // Verificar si el flag está presente en sessionStorage o en la URL
            const hasUpdated = savedFlag === 'true' || updatedParam1 === 'true' || updatedParam2 === 'true';
            
            if (hasUpdated) {
                // Limpiar el flag de sessionStorage inmediatamente
                if (savedFlag === 'true') {
                    sessionStorage.removeItem('gw_reports_settings_saved');
                    console.log('Flag de sessionStorage eliminado');
                }
                console.log('Parámetro updated=true encontrado, intentando mostrar modal...');
                // Esperar a que SweetAlert2 esté disponible con múltiples intentos
                let attempts = 0;
                const maxAttempts = 50; // 5 segundos máximo (50 * 100ms)
                
                function tryShowModal() {
                    attempts++;
                    console.log('Intento', attempts, 'de', maxAttempts, '- Swal disponible:', typeof Swal !== 'undefined', '- Swal.fire:', typeof Swal !== 'undefined' && typeof Swal.fire === 'function');
                    
                    if (typeof Swal !== 'undefined' && typeof Swal.fire === 'function') {
                        console.log('SweetAlert2 está disponible, mostrando modal...');
                        Swal.fire({
                            title: '<div style="display: flex; align-items: center; justify-content: center; gap: 10px;"><span class="dashicons dashicons-yes-alt" style="font-size: 32px; color: #10b981;"></span><span>¡Configuración Guardada!</span></div>',
                            html: `
                                <div style="text-align: center; padding: 10px 0;">
                                    <p style="margin-bottom: 15px; color: #6b7280; font-size: 14px;">Los ajustes del informe se han guardado correctamente.</p>
                                    <div style="background: #f0fdf4; border: 1px solid #86efac; border-radius: 6px; padding: 12px; font-size: 13px; color: #166534;">
                                        <span class="dashicons dashicons-info" style="font-size: 14px; vertical-align: middle; margin-right: 6px;"></span>
                                        Los cambios se aplicarán en los próximos informes que generes.
                                    </div>
                                </div>
                            `,
                            icon: false,
                            confirmButtonText: '<span class="dashicons dashicons-yes-alt" style="font-size: 14px; vertical-align: middle; margin-right: 4px;"></span> Aceptar',
                            confirmButtonColor: '#10b981',
                            timer: 3000,
                            timerProgressBar: true,
                            allowOutsideClick: false
                        }).then(() => {
                            console.log('Modal cerrado, limpiando URL...');
                            // Limpiar el parámetro de la URL sin recargar
                            const newUrl = window.location.pathname + window.location.search.replace(/[?&]updated=true/, '').replace(/^&/, '?');
                            window.history.replaceState({}, '', newUrl);
                        });
                    } else if (attempts < maxAttempts) {
                        // Si SweetAlert2 no está disponible, intentar de nuevo después de un breve delay
                        setTimeout(tryShowModal, 100);
                    } else {
                        // Si después de varios intentos no está disponible, mostrar un alert simple
                        console.error('SweetAlert2 no está disponible después de', maxAttempts, 'intentos');
                        alert('¡Configuración guardada correctamente!');
                        const newUrl = window.location.pathname + window.location.search.replace(/[?&]updated=true/, '').replace(/^&/, '?');
                        window.history.replaceState({}, '', newUrl);
                    }
                }
                
                // Iniciar intentos
                console.log('Iniciando intentos para mostrar modal...');
                tryShowModal();
            } else {
                console.log('Parámetro updated no es true, no se mostrará el modal');
            }
        }
        
        // Intentar mostrar el modal después de que todo esté cargado
        // IMPORTANTE: Después de un redirect, la página se recarga completamente
        // Necesitamos esperar a que todos los scripts estén cargados
        console.log('Estado del documento (REPORTS):', document.readyState);
        console.log('jQuery disponible (REPORTS):', typeof jQuery !== 'undefined');
        console.log('Swal disponible al inicio (REPORTS):', typeof Swal !== 'undefined');
        
        // Función para verificar y mostrar el modal cuando todo esté listo
        function initSaveModal() {
            console.log('initSaveModal ejecutado (REPORTS)');
            // Esperar a que jQuery y SweetAlert2 estén disponibles
            if (typeof jQuery !== 'undefined' && typeof Swal !== 'undefined') {
                console.log('jQuery y Swal disponibles (REPORTS), ejecutando showSaveSuccessModal...');
                showSaveSuccessModal();
            } else {
                console.log('Esperando a que jQuery o Swal estén disponibles (REPORTS)...');
                setTimeout(initSaveModal, 100);
            }
        }
        
        // Ejecutar cuando el DOM esté listo
        if (document.readyState === 'loading') {
            console.log('Documento aún cargando (REPORTS), esperando DOMContentLoaded...');
            document.addEventListener('DOMContentLoaded', function() {
                console.log('DOMContentLoaded disparado (REPORTS)');
                setTimeout(initSaveModal, 500);
            });
        } else {
            console.log('Documento ya cargado (REPORTS), ejecutando con delay...');
            setTimeout(initSaveModal, 500);
        }
        
        // También ejecutar cuando la ventana termine de cargar
        $(window).on('load', function() {
            console.log('Window load disparado (REPORTS)');
            setTimeout(initSaveModal, 800);
        });
    });
</script>
<?php
    }

    // ==================== MÉTODOS AUXILIARES PARA PDF ====================

    private function add_pdf_cover($pdf, $start_date, $end_date, $total_leads)
    {
        $pdf->SetFont('helvetica', 'B', 24);
        $pdf->SetTextColor(34, 113, 177); // Azul WordPress
        $pdf->Cell(0, 60, '', 0, 1);
        $pdf->Cell(0, 15, 'Informe de Leads', 0, 1, 'C');

        $pdf->SetFont('helvetica', '', 14);
        $pdf->SetTextColor(102, 102, 102);
        $pdf->Cell(0, 10, 'GW Elementor Analytics', 0, 1, 'C');

        $pdf->Ln(20);
        $pdf->SetFont('helvetica', '', 12);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(0, 8, 'Periodo: ' . date('d/m/Y', strtotime($start_date)) . ' - ' . date('d/m/Y', strtotime($end_date)), 0, 1, 'C');
        $pdf->Cell(0, 8, 'Total de Leads: ' . $total_leads, 0, 1, 'C');
        $pdf->Cell(0, 8, 'Generado: ' . date('d/m/Y H:i'), 0, 1, 'C');

        $pdf->AddPage();
    }

    private function add_pdf_kpis($pdf, $data)
    {
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(34, 113, 177);
        $pdf->Cell(0, 10, 'KPIs Generales', 0, 1);
        $pdf->Ln(5);

        $total = count($data);
        $spam = count(array_filter($data, fn($d) => $d['is_spam']));
        $limpio = $total - $spam;
        $leidos = count(array_filter($data, fn($d) => $d['read_status'] === '1'));
        $no_leidos = $total - $leidos;

        $html = '<table border="0" cellpadding="8" style="width:100%;">
            <tr>
                <td style="width:50%; background-color:#e3f2fd; text-align:center;">
                    <h2 style="color:#1976d2; margin:5px 0;">' . $total . '</h2>
                    <p style="margin:0; font-size:11px;">Total Leads</p>
                </td>
                <td style="width:50%; background-color:#e8f5e9; text-align:center;">
                    <h2 style="color:#388e3c; margin:5px 0;">' . $limpio . '</h2>
                    <p style="margin:0; font-size:11px;">Leads Limpios</p>
                </td>
            </tr>
            <tr>
                <td style="width:50%; background-color:#fff3e0; text-align:center;">
                    <h2 style="color:#f57c00; margin:5px 0;">' . $leidos . '</h2>
                    <p style="margin:0; font-size:11px;">Leídos</p>
                </td>
                <td style="width:50%; background-color:#ffebee; text-align:center;">
                    <h2 style="color:#d32f2f; margin:5px 0;">' . $spam . '</h2>
                    <p style="margin:0; font-size:11px;">Spam Detectado</p>
                </td>
            </tr>
        </table>';

        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_forms_distribution($pdf, $data)
    {
        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(34, 113, 177);
        $pdf->Cell(0, 10, 'Distribución por Formularios', 0, 1);
        $pdf->Ln(5);

        $forms_count = [];
        foreach ($data as $row) {
            $form = $row['form'];
            $forms_count[$form] = ($forms_count[$form] ?? 0) + 1;
        }
        arsort($forms_count);

        $html = '<table border="1" cellpadding="6" style="border-collapse:collapse; width:100%;">
            <tr style="background-color:#2271b1; color:#ffffff;">
                <th style="width:70%; text-align:left;"><strong>Formulario</strong></th>
                <th style="width:30%; text-align:center;"><strong>Cantidad</strong></th>
            </tr>';

        foreach ($forms_count as $form => $count) {
            $percentage = round(($count / count($data)) * 100, 1);
            $html .= '<tr>
                <td>' . htmlspecialchars($form) . '</td>
                <td style="text-align:center;"><strong>' . $count . '</strong> (' . $percentage . '%)</td>
            </tr>';
        }

        $html .= '</table>';
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_origins_distribution($pdf, $data)
    {
        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(34, 113, 177);
        $pdf->Cell(0, 10, 'Distribución por Orígenes', 0, 1);
        $pdf->Ln(5);

        $origins_count = [];
        foreach ($data as $row) {
            $origin = $row['origin'];
            $origins_count[$origin] = ($origins_count[$origin] ?? 0) + 1;
        }
        arsort($origins_count);

        $html = '<table border="1" cellpadding="6" style="border-collapse:collapse; width:100%;">
            <tr style="background-color:#2271b1; color:#ffffff;">
                <th style="width:70%; text-align:left;"><strong>Origen</strong></th>
                <th style="width:30%; text-align:center;"><strong>Cantidad</strong></th>
            </tr>';

        foreach ($origins_count as $origin => $count) {
            $percentage = round(($count / count($data)) * 100, 1);
            $html .= '<tr>
                <td>' . htmlspecialchars($origin) . '</tml>
                <td style="text-align:center;"><strong>' . $count . '</strong> (' . $percentage . '%)</td>
            </tr>';
        }

        $html .= '</table>';
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_timeline($pdf, $data, $start_date, $end_date)
    {
        // Placeholder: aquí podrías generar un gráfico visual
        // Por ahora mostraremos datos agregados por día
        $pdf->SetFont('helvetica', 'B', 14);
        $pdf->Cell(0, 8, 'Evolución de Leads (Resumen)', 0, 1);
        $pdf->SetFont('helvetica', '', 10);
        $pdf->Cell(0, 6, 'Total en el periodo: ' . count($data) . ' leads', 0, 1);
        $pdf->Ln(5);
    }

    private function add_pdf_crm_distribution($pdf, $data)
    {
        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(34, 113, 177);
        $pdf->Cell(0, 10, 'Estados CRM', 0, 1);
        $pdf->Ln(5);

        $crm_labels = get_option('efa_crm_labels', []);
        $crm_count = [];

        foreach ($data as $row) {
            $status = $row['crm_status'];
            $crm_count[$status] = ($crm_count[$status] ?? 0) + 1;
        }

        $html = '<table border="1" cellpadding="6" style="border-collapse:collapse; width:100%;">
            <tr style="background-color:#2271b1; color:#ffffff;">
                <th style="width:70%; text-align:left;"><strong>Estado CRM</strong></th>
                <th style="width:30%; text-align:center;"><strong>Cantidad</strong></th>
            </tr>';

        foreach ($crm_count as $status => $count) {
            $label = $status;
            foreach ($crm_labels as $crm_label) {
                if ($crm_label['id'] === $status) {
                    $label = $crm_label['label'];
                    break;
                }
            }
            $percentage = round(($count / count($data)) * 100, 1);
            $html .= '<tr>
                <td>' . htmlspecialchars($label) . '</td>
                <td style="text-align:center;"><strong>' . $count . '</strong> (' . $percentage . '%)</td>
            </tr>';
        }

        $html .= '</table>';
        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_read_distribution($pdf, $data)
    {
        $pdf->SetFont('helvetica', 'B', 14);
        $pdf->Cell(0, 8, 'Estado de Lectura', 0, 1);
        $pdf->Ln(5);

        $leidos = count(array_filter($data, fn($d) => $d['read_status'] === '1'));
        $no_leidos = count($data) - $leidos;

        $html = '<table border="1" cellpadding="6" style="border-collapse:collapse; width:100%;">
            <tr style="background-color:#e8f5e9;">
                <td style="width:70%;"><strong>Leídos</strong></td>
                <td style="width:30%; text-align:center;">' . $leidos . ' (' . round(($leidos / count($data)) * 100, 1) . '%)</td>
            </tr>
            <tr style="background-color:#ffebee;">
                <td><strong>No Leídos</strong></td>
                <td style="text-align:center;">' . $no_leidos . ' (' . round(($no_leidos / count($data)) * 100, 1) . '%)</td>
            </tr>
        </table>';

        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_spam_distribution($pdf, $data)
    {
        $pdf->SetFont('helvetica', 'B', 14);
        $pdf->Cell(0, 8, 'Detección de Spam', 0, 1);
        $pdf->Ln(5);

        $spam = count(array_filter($data, fn($d) => $d['is_spam']));
        $limpio = count($data) - $spam;

        $html = '<table border="1" cellpadding="6" style="border-collapse:collapse; width:100%;">
            <tr style="background-color:#e8f5e9;">
                <td style="width:70%;"><strong>Emails Limpios</strong></td>
                <td style="width:30%; text-align:center;">' . $limpio . ' (' . round(($limpio / count($data)) * 100, 1) . '%)</td>
            </tr>
            <tr style="background-color:#ffebee;">
                <td><strong>Spam Detectado</strong></td>
                <td style="text-align:center;">' . $spam . ' (' . round(($spam / count($data)) * 100, 1) . '%)</td>
            </tr>
        </table>';

        $pdf->writeHTML($html, true, false, true, false, '');
        $pdf->Ln(10);
    }

    private function add_pdf_data_table($pdf, $data)
    {
        $pdf->AddPage();
        $pdf->SetFont('helvetica', 'B', 16);
        $pdf->SetTextColor(34, 113, 177);
        $pdf->Cell(0, 10, 'Tabla Detallada de Leads', 0, 1);
        $pdf->Ln(5);

        $pdf->SetFont('helvetica', '', 8);

        $html = '<table border="1" cellpadding="4" style="border-collapse:collapse; width:100%; font-size:7px;">
            <tr style="background-color:#2271b1; color:#ffffff;">
                <th style="width:15%;"><strong>Fecha</strong></th>
                <th style="width:20%;"><strong>Nombre</strong></th>
                <th style="width:25%;"><strong>Email</strong></th>
                <th style="width:20%;"><strong>Formulario</strong></th>
                <th style="width:20%;"><strong>Origen</strong></th>
            </tr>';

        // Limitar a primeros 50 registros para no sobrecargar el PDF
        $limited_data = array_slice($data, 0, 50);

        foreach ($limited_data as $row) {
            $date = date('d/m/Y', strtotime($row['created_at']));
            $html .= '<tr>
                <td>' . $date . '</td>
                <td>' . htmlspecialchars(substr($row['nombre'], 0, 20)) . '</td>
                <td style="font-size:6px;">' . htmlspecialchars($row['email']) . '</td>
                <td>' . htmlspecialchars(substr($row['form'], 0, 15)) . '</td>
                <td>' . htmlspecialchars(substr($row['origin'], 0, 15)) . '</td>
            </tr>';
        }

        if (count($data) > 50) {
            $html .= '<tr>
                <td colspan="5" style="text-align:center; font-style:italic;">... y ' . (count($data) - 50) . ' registros más</td>
            </tr>';
        }

        $html .= '</table>';
        $pdf->writeHTML($html, true, false, true, false, '');
    }
}
