<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

$discarded_leads = [];
$total_discarded = 0;
$reason_counts = [];
$source_counts = [];
$most_frequent_reason = ['name' => 'N/A', 'count' => 0];
$most_frequent_source = ['name' => 'N/A', 'count' => 0];
$sources = [];
$reasons = [];
$final_statuses = [];

    function fetchDiscardedLeads($pdo) {
        try {
            // Sentencias Preparadas: Cumple con SQLi Mitigation
            $stmt = $pdo->prepare("
                SELECT id, first_name, last_name, company, email, phone, mobile, source, status, 
                    lost_reason, updated_at
                FROM leads
                WHERE status IN ('Lead Archivado', 'Cotización Perdida')
                ORDER BY updated_at DESC
            ");
            $stmt->execute();
            $leads_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $formatted_leads = [];
            foreach ($leads_raw as $lead) {
                $name = trim(($lead['first_name'] ?? '') . ' ' . ($lead['last_name'] ?? ''));
                
                $formatted_leads[] = [
                    'id' => $lead['id'],
                    'name' => $name ?: 'Sin Nombre',
                    'first_name' => $lead['first_name'],
                    'last_name' => $lead['last_name'],
                    'email' => $lead['email'],
                    'phone_mobile' => $lead['mobile'] ?? $lead['phone'],
                    'company' => $lead['company'] ?? '',
                    'source' => $lead['source'] ?? 'N/A',
                    'discard_reason' => $lead['lost_reason'] ?? 'No especificada',
                    'discard_date' => date('Y-m-d', strtotime($lead['updated_at'])),
                    'status_final' => $lead['status']
                ];
            }
            return $formatted_leads;

        } catch (PDOException $e) {
            error_log("Error SQL en fetchDiscardedLeads: " . $e->getMessage());
            return [];
        }
    }

    $discarded_leads = fetchDiscardedLeads($pdo);
    $total_discarded = count($discarded_leads);

    foreach ($discarded_leads as $lead) {
        $reason = $lead['discard_reason'];
        $reason_counts[$reason] = ($reason_counts[$reason] ?? 0) + 1;

        $source = $lead['source'];
        $source_counts[$source] = ($source_counts[$source] ?? 0) + 1;
    }

    if (!empty($reason_counts)) {
        arsort($reason_counts);
        $most_frequent_reason['name'] = array_key_first($reason_counts);
        $most_frequent_reason['count'] = $reason_counts[$most_frequent_reason['name']];
    }

    if (!empty($source_counts)) {
        arsort($source_counts);
        $most_frequent_source['name'] = array_key_first($source_counts);
        $most_frequent_source['count'] = $source_counts[$most_frequent_source['name']];
    }

    $sources = array_unique(array_column($discarded_leads, 'source'));
    $sources = array_filter($sources);
    sort($sources);

    $reasons = array_unique(array_column($discarded_leads, 'discard_reason'));
    $reasons = array_filter($reasons);
    sort($reasons);

    $final_statuses = array_unique(array_column($discarded_leads, 'status_final'));
    sort($final_statuses);

} catch (Exception $e) {
    error_log("Error crítico en inicialización de discarded-leads.php: " . $e->getMessage());
}

$discarded_leads_json = json_encode($discarded_leads, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

if (ob_get_level() > 0) {
    ob_end_clean();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centro De Prospectos Descartados <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
</head>

<body class="font-barlow"
    data-page-title="Centro De Prospectos Descartados"
    data-page-subtitle="Archivo De Clientes Potenciales Para Análisis Y Reactivación"
    data-page-icon="archive">

    <div id="toast-container" class="toast-container"></div>
    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

    <div id="content-area" class="p-4 md:p-8 bg-[var(--color-background)] space-y-8">

             <div>
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-6">

                    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="archive" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                        <div>
                            <h3 class="text-lg font-black text-gray-500 mb-1">TOTAL ARCHIVADOS</h3>
                            <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_discarded; ?></p>
                        </div>
                    </div>

                    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="alert-triangle" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                        <div>
                            <h3 class="text-lg font-black text-gray-500 mb-1">RAZÓN DE PÉRDIDA</h3>
                            <p class="text-3xl font-black text-[var(--color-primary)] uppercase mb-1 truncate" title="<?php echo htmlspecialchars($most_frequent_reason['name']); ?>">
                                <?php echo htmlspecialchars($most_frequent_reason['name']); ?>
                            </p>
                        </div>
                    </div>

                    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="compass" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                        <div>
                            <h3 class="text-lg font-black text-gray-500 mb-1">FUENTE DE PÉRDIDA</h3>
                            <p class="text-3xl font-black text-[var(--color-primary)] uppercase mb-1 truncate" title="<?php echo htmlspecialchars($most_frequent_source['name']); ?>">
                                <?php echo htmlspecialchars($most_frequent_source['name']); ?>
                            </p>
                        </div>
                    </div>

                </div>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-[var(--color-primary)]">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                    <div>
                        <label for="filter-source" class="block text-sm font-black uppercase text-gray-700 mb-1">Filtrar por Fuente</label>
                        <select id="filter-source" name="filter-source" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todas las Fuentes --</option>
                            <?php foreach ($sources as $source): ?>
                                <option value="<?php echo htmlspecialchars($source); ?>"><?php echo htmlspecialchars($source); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="filter-reason" class="block text-sm font-semibold uppercase text-gray-700 mb-1">Filtrar por Razón</label>
                        <select id="filter-reason" name="filter-reason" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todas las Razones --</option>
                             <?php foreach ($reasons as $reason): ?>
                                 <option value="<?php echo htmlspecialchars($reason); ?>"><?php echo htmlspecialchars($reason); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="filter-status" class="block text-sm font-semibold uppercase text-gray-700 mb-1">Filtrar por Resultado</label>
                        <select id="filter-status" name="filter-status" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white" onchange="filterTable()">
                            <option value="">-- Todos los Resultados --</option>
                            <?php foreach ($final_statuses as $status): ?>
                                <option value="<?php echo htmlspecialchars($status); ?>"><?php echo htmlspecialchars($status); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <button onclick="resetFilters()" class="w-full md:w-auto bg-[var(--color-secondary)] text-white font-black uppercase py-2 px-4 rounded-lg text-sm flex items-center justify-center shadow-md hover:shadow-lg transition-all">
                            <i data-lucide="rotate-ccw" class="w-4 h-4 mr-2"></i> Limpiar Filtros
                        </button>
                    </div>
                </div>
            </div>

            <div>
                <h3 class="text-3xl font-black text-[var(--color-primary)] mb-4 uppercase flex items-center"><i data-lucide="list-x" class="w-6 h-6 mr-2"></i>Listado de Leads Descartados</h3>

                <div class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-[var(--color-secondary)]">
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left text-gray-700 responsive-stack" id="discarded-leads-table">
                            <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                                <tr>
                                    <th scope="col" class="py-3 px-4">Nombre</th>
                                    <th scope="col" class="py-3 px-4">Fuente</th>
                                    <th scope="col" class="py-3 px-4">Razón De Pérdida</th>
                                    <th scope="col" class="py-3 px-4">Fecha Archivo</th>
                                    <th scope="col" class="py-3 px-4 text-center">Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($discarded_leads)): ?>
                                    <tr class="bg-white border-b">
                                        <td colspan="5" class="py-8 px-4 text-center text-gray-500 italic">
                                            <i data-lucide="inbox" class="w-12 h-12 mx-auto text-gray-300 mb-2"></i>
                                            No hay leads descartados en el archivo
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($discarded_leads as $lead): 
                                        // Determinar clases de estilo para el chip (LEAD ARCHIVADO)
                                        $chip_class = ($lead['status_final'] === 'Cotización Perdida') ? 'bg-red-500' : 'bg-[var(--color-secondary)]';
                                        
                                        // Determinar si la razón es "Archivado" o el motivo real
                                        $is_default_reason = ($lead['discard_reason'] === 'Lead Archivado' || $lead['discard_reason'] === 'Razón no especificada');
                                        $reason_text = $is_default_reason ? 'No especificada' : $lead['discard_reason'];
                                        
                                        // Determinar clase de estilo para la razón
                                        $reason_class = $is_default_reason ? 'text-gray-400' : 'text-[var(--color-secondary)] font-black text-md';
                                ?>
                                    <tr class="bg-white border-b hover:bg-gray-50 transition-colors duration-150" 
                                        data-source="<?php echo htmlspecialchars($lead['source']); ?>" 
                                        data-reason="<?php echo htmlspecialchars($lead['discard_reason']); ?>"
                                        data-status="<?php echo htmlspecialchars($lead['status_final']); ?>">
                                            
                                        <td class="py-3 px-4 font-black text-gray-900 text-lg" data-label="Nombre"><?php echo htmlspecialchars($lead['name']); ?></td>
                                        <td class="py-3 px-4" data-label="Fuente"><?php echo htmlspecialchars($lead['source']); ?></td>
                                        <td class="py-3 px-4" data-label="Razón De Pérdida">

                                                
                                                <span class="block text-md uppercase font-black <?php echo $reason_class; ?>" title="Razón de pérdida">
                                                    <i data-lucide="octagon-x" class="w-3 h-3 inline mr-1"></i>
                                                    <?php echo htmlspecialchars($reason_text); ?>
                                                </span>
                                            </td>
                                            <td class="py-3 px-4" data-label="Fecha Archivo"><?php echo date('d M Y', strtotime($lead['discard_date'])); ?></td>
                                            <td class="py-3 px-4 text-center space-x-2 actions-cell" data-label="Acciones">
                                                <button
                                                    onclick="openDiscardedPanel(<?php echo $lead['id']; ?>)"
                                                    class="inline-flex items-center text-[var(--color-primary)] hover:text-[var(--color-secondary)] transition-colors duration-150 p-1.5 rounded-md hover:bg-gray-100"
                                                    title="Ver Detalles">
                                                    <i data-lucide="eye" class="w-4 h-4"></i>
                                                    <span class="sr-only">Ver Detalles</span>
                                                </button>
                                                <button
                                                    onclick="openDeleteModal(<?php echo $lead['id']; ?>, '<?php echo htmlspecialchars(addslashes($lead['name'])); ?>')"
                                                    class="inline-flex items-center text-[var(--color-secondary)] hover:text-red-700 transition-colors duration-150 p-1.5 rounded-md hover:bg-red-50"
                                                    title="Eliminar Permanentemente">
                                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                                    <span class="sr-only">Eliminar</span>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                    </div>
                </div>
            </div>

        </div>
    </main>
</div>

<div id="confirmDeleteModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
     onclick="if(event.target === this) window.closeModal('confirmDeleteModal')">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        
        <div class="modal-header-container rounded-t-xl pt-6">
            <h3 class="modal-primary-title text-4xl font-black text-[var(--color-highlight)] uppercase leading-none">
                ADVERTENCIA
            </h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>

            <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿DESEAS ELIMINAR DEFINITIVAMENTE A <span id="delete-lead-name-display" class="font-black text-[var(--color-secondary)] inline"></span>?
            </p>

            <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
                <button type="button" 
                        class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" 
                        onclick="window.closeModal('confirmDeleteModal')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" 
                        id="confirm-delete-button"
                        class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR
                </button>
            </div>

            <p class="mt-6 uppercase text-xs font-black text-gray-500 tracking-wider"> 
                ESTA ACCIÓN ES IRREVERSIBLE
            </p>
        </div>
    </div>
</div>

<div id="confirmReactivateModal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
     onclick="if(event.target === this) window.closeModal('confirmReactivateModal')">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        
        <div class="modal-header-container rounded-t-xl pt-6">
            <h3 class="modal-primary-title text-4xl font-black text-[var(--color-highlight)] uppercase leading-none">
                ADVERTENCIA
            </h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i data-lucide="shuffle" class="w-16 h-16 text-green-600"></i>
            </div>

            <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿ESTAS SEGURO(A) QUE DESEAS REACTIVAR A <span id="reactivate-lead-name-display" class="font-black text-[var(--color-secondary)] inline"></span>?
            </p>

            <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
                <button type="button" 
                        class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" 
                        onclick="window.closeModal('confirmReactivateModal')">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" 
                        id="confirm-reactivate-button"
                        class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="check-circle" class="w-5 h-5"></i> REACTIVAR
                </button>
            </div>

            <p class="mt-6 uppercase text-xs font-black text-gray-500 tracking-wider"> 
                VOLVERÁ AL LISTADO ACTIVO
            </p>
        </div>
    </div>
</div>

<div id="discarded-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300 opacity-0 pointer-events-none" onclick="closeDiscardedPanel()"></div>

<aside id="discarded-panel" class="fixed top-0 right-0 h-full w-full lg:w-[450px] bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl">
    
    <div class="flex flex-col h-full">
        
        <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
            <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
                <i data-lucide="user-x" class="w-8 h-8 mr-2 text-white"></i>
                DETALLES DEL LEAD
            </h3>
            <button class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200" onclick="closeDiscardedPanel()">
                <i data-lucide="x" class="w-8 h-8"></i>
            </button>
        </div>

        <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
            <div id="panel-content-area" class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                
                <div class="border-b pb-3 mb-4">
                    <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="user" class="w-5 h-5 mr-2"></i>
                        <span id="panel-discarded-name"></span>
                    </h4>
                    <div class="flex justify-between items-center mt-1">
                        <p class="text-xs font-bold bg-gray-200 text-gray-700 px-2 py-0.5 rounded-full uppercase">
                            <i data-lucide="compass" class="w-3 h-3 inline mr-1"></i>
                            <span id="panel-discarded-source"></span>
                        </p>
                        <p class="text-xs font-bold text-gray-400">ID: <span id="panel-discarded-id"></span></p>
                    </div>
                </div>

                <div class="space-y-4 mb-4">
                    <div class="bg-red-50 p-3 rounded-lg border border-red-100">
                        <label class="block text-lg font-black text-red-800 uppercase mb-1 flex items-center">
                            <i data-lucide="info" class="w-3 h-3 mr-1"></i> Resultado y Razón
                        </label>
                        <p class="text-sm font-semibold text-gray-800" id="panel-discarded-reason"></p>
                    </div>
                    
                    <div>
                        <label class="block text-xs font-bold text-gray-500 uppercase mb-1">
                            <i data-lucide="calendar-x" class="w-3 h-3 inline mr-1"></i> Fecha de Archivo
                        </label>
                        <p class="text-sm font-semibold text-gray-800" id="panel-discarded-date"></p>
                    </div>
                </div>

                <div class="border-t pt-4 mb-4">
                    <h5 class="text-lg font-black text-[var(--color-primary)] mb-3 uppercase flex items-center">
                        <i data-lucide="contact" class="w-4 h-4 mr-2"></i> Información de Contacto
                    </h5>
                    <div class="space-y-2 pl-2">
                        <p class="text-sm text-gray-700 flex items-center">
                            <i data-lucide="mail" class="w-4 h-4 mr-2 text-[var(--color-secondary)]"></i>
                            <span id="panel-discarded-email" class="break-all font-medium"></span>
                        </p>
                        <p class="text-sm text-gray-700 flex items-center">
                            <i data-lucide="phone" class="w-4 h-4 mr-2 text-[var(--color-secondary)]"></i>
                            <span id="panel-discarded-phone-mobile" class="font-medium"></span>
                        </p>
                        <p class="text-sm text-gray-700 flex items-center">
                            <i data-lucide="building" class="w-4 h-4 mr-2 text-[var(--color-secondary)]"></i>
                            <span id="panel-discarded-company" class="font-medium"></span>
                        </p>
                    </div>
                </div>

                <div class="border-t pt-4">
                    <h5 class="text-lg font-black text-[var(--color-primary)] mb-3 uppercase flex items-center">
                        <i data-lucide="history" class="w-4 h-4 mr-2"></i> Historial de Notas
                    </h5>
                    <div id="panel-discarded-notes" class="space-y-2 text-xs text-gray-600 max-h-40 overflow-y-auto pr-2 custom-scrollbar border border-gray-100 rounded p-2 bg-gray-50">
                        <p class="italic text-gray-500 text-center py-2">No hay notas disponibles.</p>
                    </div>
                </div>

            </div>
        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10">
            <div class="grid grid-cols-2 gap-3">
                <button type="button" onclick="closeDiscardedPanel()" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR
                </button>
                
                <button id="reactivate-lead-btn" onclick="reactivateLead()" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="shuffle" class="w-5 h-5"></i> REACTIVAR
                </button>
            </div>
        </div>

    </div>
</aside>

<script>
// *** DATOS GLOBALES (Seguros) ***
const discardedLeadsData = <?php echo $discarded_leads_json; ?>;
let currentLeadIdToReactivate = null; 
let currentLeadIdToDelete = null;

// =================================================================
// FUNCIONES DE UTILIDAD
// =================================================================

function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container');
    if (!toastContainer) return;
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    let icon = 'info';
    if (type === 'success') icon = 'check-circle';
    if (type === 'error') icon = 'alert-circle';
    if (type === 'warning') icon = 'alert-triangle';
    toast.innerHTML = `<i data-lucide="${icon}" class="w-5 h-5"></i><span>${message}</span>`;
    toastContainer.appendChild(toast);
    lucide.createIcons({ container: toast });
    setTimeout(() => toast.classList.add('show'), 100);
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => { if (toastContainer.contains(toast)) toastContainer.removeChild(toast); }, 500);
    }, 4000);
}

function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const modalBox = modal.querySelector('div:first-of-type');
    modal.classList.remove('hidden');
    setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
    lucide.createIcons();
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const modalBox = modal.querySelector('div:first-of-type');
    modalBox.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 300);
}

// =================================================================
// PANEL LATERAL
// =================================================================

function openDiscardedPanel(leadId) {
    const lead = discardedLeadsData.find(l => l.id == leadId);
    if (!lead) {
        showToast("No se pudo cargar la información del lead.", 'error');
        return;
    }

    currentLeadIdToReactivate = leadId; 
    
    document.getElementById('panel-discarded-name').textContent = lead.name || 'N/A';
    document.getElementById('panel-discarded-source').textContent = lead.source || 'N/A';
    document.getElementById('panel-discarded-id').textContent = lead.id;
    
    const reasonTextElement = document.getElementById('panel-discarded-reason');
    
    // XSS PROTECTION: Usar textContent en partes dinámicas o escapar
    reasonTextElement.innerHTML = `
        <span class="font-black text-white px-2 py-0.5 rounded-md bg-[var(--color-secondary)]">
            ${lead.status_final.toUpperCase()}
        </span> 
        <span class="font-medium text-gray-700 ml-2">
            ${lead.discard_reason.replace(/</g, "&lt;").replace(/>/g, "&gt;")}
        </span>`;
        
    const discardDate = new Date(lead.discard_date + 'T00:00:00'); 
    document.getElementById('panel-discarded-date').textContent = discardDate.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', day: 'numeric' }) || 'N/A';
    
    document.getElementById('panel-discarded-email').textContent = lead.email || '--';
    document.getElementById('panel-discarded-phone-mobile').textContent = lead.phone_mobile || '--';
    document.getElementById('panel-discarded-company').textContent = lead.company || '--';

    // Notas con carga asíncrona segura
    const notesContainer = document.getElementById('panel-discarded-notes');
    notesContainer.innerHTML = '<p class="text-gray-500 italic text-xs">Cargando notas...</p>';
    
    fetch(`db/leads-get-notes.php?lead_id=${leadId}`) 
        .then(response => response.json())
        .then(data => {
            notesContainer.innerHTML = ''; 
            if (data.success && data.notes.length > 0) {
                data.notes.forEach(note => {
                    const noteDiv = document.createElement('div');
                    noteDiv.className = 'bg-gray-50 p-2 rounded-md border-l-2 border-[var(--color-primary)]';
                    // XSS PROTECTION: Escapar contenido de nota
                    const safeContent = note.content.replace(/</g, "&lt;").replace(/>/g, "&gt;");
                    noteDiv.innerHTML = `<div class="flex justify-between text-xs text-gray-500 mb-0.5"><span>${new Date(note.created_at).toLocaleDateString('es-ES')}</span></div><p>${safeContent}</p>`;
                    notesContainer.appendChild(noteDiv);
                });
            } else {
                notesContainer.innerHTML = '<p class="italic text-gray-500">No hay notas registradas para este lead.</p>';
            }
            lucide.createIcons();
        })
        .catch(error => {
            console.error('Error al cargar notas:', error);
            notesContainer.innerHTML = '<p class="italic text-[var(--color-secondary)]">Error al cargar historial de notas.</p>';
        });

    const discardedPanel = document.getElementById('discarded-panel');
    const discardedPanelOverlay = document.getElementById('discarded-panel-overlay');
    discardedPanel.classList.remove('translate-x-full');
    discardedPanelOverlay.classList.remove('opacity-0', 'pointer-events-none');
    discardedPanelOverlay.classList.add('opacity-100');
    lucide.createIcons(); 
}

function closeDiscardedPanel() {
    const discardedPanel = document.getElementById('discarded-panel');
    const discardedPanelOverlay = document.getElementById('discarded-panel-overlay');
    discardedPanel.classList.add('translate-x-full');
    discardedPanelOverlay.classList.remove('opacity-100');
    discardedPanelOverlay.classList.add('opacity-0', 'pointer-events-none');
}

// =================================================================
// REACTIVACIÓN
// =================================================================
function reactivateLead() {
    const lead = discardedLeadsData.find(l => l.id == currentLeadIdToReactivate);
    if (!currentLeadIdToReactivate || !lead) {
        showToast("Error: No hay lead seleccionado para reactivar.", 'error');
        return;
    }
    closeDiscardedPanel(); 
    const nameDisplay = document.getElementById('reactivate-lead-name-display');
    if(nameDisplay) nameDisplay.textContent = lead.name;
    openModal('confirmReactivateModal');
}

async function confirmReactivateLogic() {
    const leadId = currentLeadIdToReactivate;
    if (!leadId) { closeModal('confirmReactivateModal'); return; }
    
    showToast("Reactivando lead...", 'info');
    closeModal('confirmReactivateModal');

    try {
        const response = await fetch('db/leads-update-status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                id: leadId, 
                status: 'En Seguimiento', 
                lost_reason: null 
            })
        });
        const data = await response.json();

        if (data.success) {
            showToast("Lead reactivado con éxito.", 'success');
            setTimeout(() => { location.reload(); }, 500);
        } else {
            showToast(`Error al reactivar: ${data.message || 'Error desconocido'}`, 'error');
        }
    } catch (error) {
        console.error('Error de conexión al reactivar:', error);
        showToast("Error de conexión al servidor.", 'error');
    }
}

// =================================================================
// ELIMINACIÓN
// =================================================================
function openDeleteModal(leadId, leadName) {
    currentLeadIdToDelete = leadId;
    const nameDisplay = document.getElementById('delete-lead-name-display');
    if(nameDisplay) nameDisplay.textContent = leadName;
    openModal('confirmDeleteModal');
}

async function confirmDeleteLogic() {
    const leadId = currentLeadIdToDelete;
    if (!leadId) { closeModal('confirmDeleteModal'); return; }
    
    showToast("Eliminando lead permanentemente...", 'info');
    closeModal('confirmDeleteModal');

    try {
        const response = await fetch('db/leads-delete.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: leadId })
        });
        const data = await response.json();

        if (data.success) {
            showToast("Lead eliminado permanentemente.", 'success');
            setTimeout(() => { location.reload(); }, 500);
        } else {
            showToast(`Error al eliminar: ${data.message || 'Error desconocido'}`, 'error');
        }
    } catch (error) {
        console.error('Error de conexión al eliminar:', error);
        showToast("Error de conexión al servidor.", 'error');
    }
}

// =================================================================
// FILTROS
// =================================================================

function filterTable() {
    const sourceFilter = document.getElementById('filter-source').value;
    const reasonFilter = document.getElementById('filter-reason').value;
    const statusFilter = document.getElementById('filter-status') ? document.getElementById('filter-status').value : ''; 
    
    const tableBody = document.getElementById('discarded-leads-table').querySelector('tbody');
    const rows = tableBody.querySelectorAll('tr');
    let visibleCount = 0;

    rows.forEach(row => {
        if (row.querySelector('td[colspan="5"]')) { row.style.display = 'none'; return; }

        const source = row.dataset.source;
        const reason = row.dataset.reason;
        const status = row.dataset.status ? row.dataset.status.toUpperCase() : '';
        
        let show = true;
        if (sourceFilter && source !== sourceFilter) { show = false; }
        if (reasonFilter && reason !== reasonFilter) { show = false; }
        if (statusFilter && statusFilter.toUpperCase() !== status) { show = false; }

        row.style.display = show ? '' : 'none';
        if (show) visibleCount++;
    });

    const noResultsRow = tableBody.querySelector('td[colspan="5"]');
    if (noResultsRow) {
        const noResultsTr = noResultsRow.closest('tr');
        if (visibleCount === 0 && rows.length > 1) {
            noResultsTr.style.display = '';
            noResultsRow.textContent = "No hay leads que coincidan con los filtros seleccionados.";
        } else {
            noResultsTr.style.display = 'none';
        }
    }
}

function resetFilters() {
    document.getElementById('filter-source').value = '';
    document.getElementById('filter-reason').value = '';
    const statusSelect = document.getElementById('filter-status');
    if(statusSelect) statusSelect.value = '';
    filterTable();
}

document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();

    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    if (confirmDeleteButton) confirmDeleteButton.addEventListener('click', confirmDeleteLogic);
    
    const confirmReactivateButton = document.getElementById('confirm-reactivate-button');
    if (confirmReactivateButton) confirmReactivateButton.addEventListener('click', confirmReactivateLogic);

    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    if (mobileMenuButton && sidebar && sidebarOverlay) {
        mobileMenuButton.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
    }

    filterTable();
});
</script>
<script src="files/toast.js"></script>
</body>
</html>