<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

$prospects_data_from_db = [];
$source_counts = []; // Para contar las fuentes
try {
$stmt = $pdo->query("SELECT id, first_name, last_name, company, email, phone, mobile, source, status, priority, street_address, city, state_province, zip_code, created_at FROM leads ORDER BY created_at DESC, first_name ASC");
$db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_prospects_rows as $row) {
        $row['mobile'] = $row['mobile'] ?? '';
        $row['company'] = $row['company'] ?? '';
        $row['first_name'] = $row['first_name'] ?? '';
        $row['last_name'] = $row['last_name'] ?? '';

        $prospects_data_from_db[$row['id']] = [
            'id' => $row['id'],
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'nombre_completo' => $row['first_name'] . ' ' . $row['last_name'],
            'empresa' => $row['company'],
            'email' => $row['email'],
            'phone' => $row['phone'],
            'mobile' => $row['mobile'],
            'fuente' => $row['source'],
            'estado' => $row['status'],
            'prioridad' => $row['priority'] ?? 'Media',
            'direccion_calle' => $row['street_address'],
            'ciudad' => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code' => $row['zip_code'],
            'created_at' => $row['created_at']
        ];
        
        // Contar leads por fuente
        if (!empty($row['source'])) {
            $source_counts[$row['source']] = ($source_counts[$row['source']] ?? 0) + 1;
        }
    }
} catch (PDOException $e) {
    error_log("Error al cargar prospectos desde la DB en leads.php: " . $e->getMessage());
}

// Lógica para encontrar la fuente más frecuente
$most_frequent_source = ['name' => 'N/A', 'count' => 0];
if (!empty($source_counts)) {
    arsort($source_counts); // Ordenar por conteo de forma descendente
    $most_frequent_source_name = array_key_first($source_counts);
    $most_frequent_source['name'] = $most_frequent_source_name;
    $most_frequent_source['count'] = $source_counts[$most_frequent_source_name];
}

$prospects_json = json_encode($prospects_data_from_db);
?>
<!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 FlowCRM™  De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
 <style>   
    /* =====================
   MOBILE IMPROVEMENTS
   ===================== */
@media (max-width: 768px) {
  .page-header-container, #page-title, #page-subtitle { display: none !important; }
  .dashboard-section:first-of-type,
  #inicio:first-of-type,
  main .dashboard-section:first-child,
  main section:first-of-type { margin-top: calc(var(--header-height) + 12px) !important; }
}
.stat-card { display:flex; align-items:center; gap:1rem; box-shadow:0 10px 25px rgba(0,0,0,.06); border-left-width:4px; }
.stat-card p.text-5xl { line-height:1; }
@media (max-width: 480px) {
  .dashboard-section .grid { gap: 12px !important; }
  .stat-card, .lead-card, .card, .panel, .box {
    padding: 14px !important;
    border-radius: 14px !important;
    box-shadow: 0 10px 22px rgba(0,0,0,.06) !important;
  }
  .stat-card [data-lucide], .lead-card [data-lucide], .card [data-lucide] { width: 32px !important; height: 32px !important; }
  .stat-card h3, .lead-card h3, .card h3 { font-size: .95rem !important; line-height: 1.15 !important; margin-bottom: .25rem !important; }
  .stat-card .text-5xl { font-size: 2.25rem !important; line-height: 1 !important; }
  .stat-card .text-sm, .lead-card .text-sm, .card .text-sm { font-size: .75rem !important; }
}
@media (max-width: 640px) {
  table.responsive-stack { width: 100% !important; border-collapse: collapse; display: block; }
  table.responsive-stack thead { display: none !important; }
  table.responsive-stack tbody { display: block; width: 100%; }
  table.responsive-stack tbody tr {
    display: block;
    background: #ffffff;
    border-radius: 12px;
    margin: 10px 0;
    box-shadow: 0 8px 18px rgba(0,0,0,.06);
    overflow: hidden;
  }
  table.responsive-stack tbody td {
    display: block; /* AHORA LAS CELDAS SE APILAN */
    padding: 10px 12px;
    border-bottom: 1px solid rgba(0,0,0,.06);
    text-align: left; /* Alineamos el texto a la izquierda */
    white-space: normal;
  }
  table.responsive-stack tbody td:last-child { border-bottom: none; }
  table.responsive-stack tbody td::before {
    content: attr(data-label);
    display: block; /* La etiqueta se pone arriba del valor */
    font-weight: 800;
    font-size: .72rem;
    letter-spacing: .02em;
    text-transform: uppercase;
    color: #6B7280;
    margin-bottom: 4px; /* Espacio entre etiqueta y valor */
  }
  
  table.responsive-stack tbody td.actions-cell {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 1rem;
      padding: 12px;
      border-bottom: none; /* La última celda de acciones no necesita borde */
  }
  table.responsive-stack tbody td.actions-cell::before {
      content: none; /* Oculta la etiqueta "ACCIONES" */
  }
}
@media (max-width: 480px) {
  .swal2-actions,
  .modal-actions,
  .modal-footer,
  .dialog-actions,
  [role="dialog"] .actions {
    display: flex !important;
    flex-direction: column !important;
    gap: 10px !important;
    width: 100%;
  }
  .swal2-actions .swal2-styled,
  .modal-actions button,
  .modal-footer button,
  .dialog-actions button,
  [role="dialog"] .actions button {
    width: 100% !important;
  }
}
@media (max-width: 480px) {
  #confirmDeleteModal .flex.justify-center.space-x-4,
  #confirmConvertModal .flex.justify-center.space-x-4 {
    flex-direction: column !important;
    align-items: stretch !important;
    justify-content: center !important;
    gap: 12px !important;
  }
  #confirmDeleteModal .flex.justify-center.space-x-4 > :not([hidden]) ~ :not([hidden]),
  #confirmConvertModal .flex.justify-center.space-x-4 > :not([hidden]) ~ :not([hidden]) {
    margin-left: 0 !important;
  }
  #confirmDeleteModal .flex.justify-center.space-x-4 > button,
  #confirmConvertModal .flex.justify-center.space-x-4 > button {
    width: 100% !important;
    display: block !important;
  }
}
</style>
    
</head>
<body data-page-title="Centro De Prospectos Y Oportunidades"
      data-page-subtitle="Panel De Administración De Clientes Potenciales"
      data-page-icon="user-plus">

    <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>
    <div id="task-panel-overlay" class="off-canvas-overlay"></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 space-y-8">
            <section id="prospectos" class="dashboard-section">


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

    <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
        <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1">TOTAL PROSPECTOS</h3>
            <p id="total-prospectos-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">Acumulados</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-secondary)]">
        <i data-lucide="zap" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1">FUENTE MÁS COMÚN</h3>
            <p class="text-3xl font-black text-[var(--color-primary)] uppercase mb-1"><?php echo htmlspecialchars($most_frequent_source['name']); ?></p>
            <p class="text-sm text-gray-400 mt-1 uppercase">Leads: <?php echo $most_frequent_source['count']; ?></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="user-plus" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1">PROSPECTOS MENSUALES</h3>
            <p id="monthly-prospectos-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
            <div class="mt-2 flex items-center">
                <select id="month-filter-select" class="p-2 border border-gray-300 rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                </select>
            </div>
        </div>
    </div>


</div>
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col mb-6 gap-4">
                        <div class="flex flex-col items-center text-center">
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center justify-center gap-2">
                                <i data-lucide="trending-up" class="w-7 h-7 text-[var(--color-secondary)]"></i> FLUJO DE CONVERSIÓN DE PROSPECTOS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">ORGANIZA CADA ETAPA HASTA CERRAR LA VENTA.</p>
                        </div>

                        <div class="flex flex-col md:flex-row items-center justify-center gap-4 w-full mt-4">
                            <div class="view-toggle inline-flex bg-gray-200 rounded-lg p-1">
                                <button id="kanban-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 active uppercase" title="Vista de Tablero">
                                    <i data-lucide="layout-grid" class="w-5 h-5"></i>
                                </button>
                                <button id="table-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 uppercase" title="Vista de Tabla">
                                    <i data-lucide="list" class="w-5 h-5"></i>
                                </button>
                            </div>
                            <button class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase" onclick="openPanel('addProspectoPanel')">
                                <i data-lucide="plus" class="w-5 h-5 mr-2"></i> AGREGAR PROSPECTO
                            </button>
                            <button id="manage-sources-btn" class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase">
                                <i data-lucide="settings" class="w-4 h-4 mr-2"></i> GESTIONAR FUENTES
                            </button>
                            <button id="download-prospectos-btn" class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase text-sm">
                                <i data-lucide="download" class="w-4 h-4 mr-2"></i> DESCARGAR
                            </button>
                        </div>

                        <div class="flex flex-col md:flex-row justify-between items-center gap-4 w-full mt-4">
                            <div class="relative flex-grow">
                                <input type="text" id="prospect-search" placeholder="Buscar Prospceto Por Nombre..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                            </div>
                            <select id="prospect-filter-status" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                                <option value="all">TODOS</option>
                                <option value="Nuevo">NUEVO</option>
                                <option value="Contactado">CONTACTADO</option>
                                <option value="En Seguimiento">EN SEGUIMIENTO</option>
                                <option value="Cotizacion Enviada">COTIZACIÓN ENVIADA</option>
                                <option value="Descartado">DESCARTADO</option>
                            </select>
                            <select id="prospect-filter-source" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                                <option value="all">TODAS LAS FUENTES</option>
                                </select>
                        </div>
                    </div>

                    <div id="prospectos-kanban-view" class="kanban-board grid grid-cols-1 md:grid-cols-3 gap-6">
                    </div>

                    <div id="prospectos-table-view" class="overflow-x-auto hidden">
                        <table class="min-w-full bg-white responsive-invoices-table">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-semibold">NOMBRE</th>
                                    <th class="py-3 px-6 font-semibold hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-semibold hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-semibold">ESTADO</th>
                                    <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="prospectsTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-2xl font-extrabold text-[var(--color-primary)] mb-2 flex items-center gap-2">
                        <i data-lucide="bell" class="w-7 h-7 text-[var(--color-secondary)]"></i> PROSPECTOS EN SEGUIMIENTO
                    </h3>
                    <p class="text-gray-500 text-sm mb-4 uppercase">PROSPECTOS QUE REQUIEREN ATENCIÓN Y SEGUIMIENTO ACTIVO.</p>

                    <div id="seguimiento-table-view" class="overflow-x-auto">
                        <table class="min-w-full bg-white responsive-invoices-table">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-semibold">NOMBRE</th>
                                    <th class="py-3 px-6 font-semibold hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-semibold hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-semibold">ESTADO</th>
                                    <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="seguimientoTableBody">
                                </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white p-6 rounded-xl shadow-md mt-8">
                    <h3 class="text-2xl font-extrabold text-[var(--color-primary)] mb-2 flex items-center gap-2">
                        <i data-lucide="archive" class="w-7 h-7 text-[var(--color-secondary)]"></i> PROSPECTOS RECHAZADOS
                    </h3>
                    <p class="text-gray-500 text-sm mb-4 uppercase">LEADS QUE NO CUALIFICAN (PORQUE SON SPAM), ALMACENADOS PARA REFERENCIA</p>

                    <div id="descartados-table-view" class="overflow-x-auto">
                        <table class="min-w-full bg-white responsive-invoices-table">
                            <thead class="bg-gray-50">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-semibold">NOMBRE</th>
                                    <th class="py-3 px-6 font-semibold hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-semibold hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-semibold">ESTADO</th>
                                    <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="descartadosTableBody">
                                </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addProspectoPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="clipboard-list" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">AGREGAR NUEVO PROSPECTO</h3>
            </div>
            <button onclick="closePanel('addProspectoPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <form id="add-prospecto-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                    <div>
                        <label for="prospecto-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Primer Nombre</label>
                        <input type="text" id="prospecto-first-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Primer Nombre" required>
                    </div>
                    <div>
                        <label for="prospecto-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label>
                        <input type="text" id="prospecto-last-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido" required>
                    </div>
                    <div>
                        <label for="prospecto-empresa-add" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMPRESA (Opcional)</label>
                        <input type="text" id="prospecto-empresa-add" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Nombre Del Negocio">
                    </div>
                    <div>
                        <label for="prospecto-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMAIL</label>
                        <input type="email" id="prospecto-email" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@paginaweb.com" required>
                    </div>
                    <div>
                        <label for="prospecto-telefono" class="block text-gray-700 text-sm font-bold mb-2 uppercase">TELÉFONO FIJO</label>
                        <input type="tel" id="prospecto-telefono" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                    </div>
                    <div>
                        <label for="prospecto-celular" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CELULAR</label>
                        <input type="tel" id="prospecto-celular" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                    </div>
                    <div class="md:col-span-2">
                        <label for="prospecto-fuente" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FUENTE</label>
                        <select id="prospecto-fuente" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                        </select>
                    </div>
                    
                    <div class="md:col-span-2">
                        <label for="prospecto-prioridad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PRIORIDAD</label>
                        <select id="prospecto-prioridad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="Alta">ALTA</option>
                            <option value="Media" selected>MEDIA</option>
                            <option value="Baja">BAJA</option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label for="prospecto-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                        <input type="text" id="prospecto-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                    </div>
                    <div class="col-span-1">
                        <label for="prospecto-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CIUDAD</label>
                        <input type="text" id="prospecto-ciudad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                    </div>
                    <div class="col-span-1">
                        <label for="prospecto-estado-provincia" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label> <input type="text" id="prospecto-estado-provincia" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                    </div>
                    <div class="md:col-span-2">
                        <label for="prospecto-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CÓDIGO POSTAL</label>
                        <input type="text" id="prospecto-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62704">
                    </div>
                </div>
                <div class="mt-8 flex justify-end">
                    <button type="submit" class="btn-primary font-bold py-3 px-6 rounded-lg flex items-center justify-center uppercase">
                        <i data-lucide="save" class="w-5 h-5 mr-2"></i> GUARDAR PROSPECTO
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="editProspectoPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="clipboard-pen" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">EDITAR PROSPECTO</h3>
            </div>
            <button onclick="closePanel('editProspectoPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <form id="edit-prospecto-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
                <input type="hidden" id="edit-prospecto-id">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                    <div>
                        <label for="edit-prospecto-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Primer Nombre</label>
                        <input type="text" id="edit-prospecto-first-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="PrimerNombre" required>
                    </div>
                    <div>
                        <label for="edit-prospecto-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label>
                        <input type="text" id="edit-prospecto-last-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido" required>
                    </div>
                    <div>
                        <label for="edit-prospecto-empresa" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMPRESA (Opcional)</label>
                        <input type="text" id="edit-prospecto-empresa" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Nombre Del Negocio">
                    </div>
                    <div>
                        <label for="edit-prospecto-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMAIL</label>
                        <input type="email" id="edit-prospecto-email" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@paginaweb.com">
                    </div>
                    <div>
                        <label for="edit-prospecto-telefono" class="block text-gray-700 text-sm font-bold mb-2 uppercase">TELÉFONO FIJO</label>
                        <input type="tel" id="edit-prospecto-telefono" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                    </div>
                    <div>
                        <label for="edit-prospecto-celular" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CELULAR</label>
                        <input type="tel" id="edit-prospecto-celular" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                    </div>
                    <div class="md:col-span-2">
                        <label for="edit-prospecto-fuente" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FUENTE</label>
                        <select id="edit-prospecto-fuente" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label for="edit-prospecto-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                        <input type="text" id="edit-prospecto-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                    </div>
                    <div class="col-span-1">
                        <label for="edit-prospecto-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CIUDAD</label>
                        <input type="text" id="edit-prospecto-ciudad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                    </div>
                    <div class="col-span-1">
                        <label for="edit-prospecto-estado-provincia" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label> <input type="text" id="edit-prospecto-estado-provincia" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                    </div>
                    <div class="md:col-span-2">
                        <label for="edit-prospecto-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CÓDIGO POSTAL</label>
                        <input type="text" id="edit-prospecto-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62704">
                    </div>
                    
                    <div class="md:col-span-2">
                        <label for="edit-prospecto-prioridad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">PRIORIDAD</label>
                        <select id="edit-prospecto-prioridad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="Alta">ALTA</option>
                            <option value="Media">MEDIA</option>
                            <option value="Baja">BAJA</option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label for="edit-prospecto-status" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label>
                        <select id="edit-prospecto-status" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                        </select>
                    </div>
                </div>
                <div class="mt-8 flex justify-end">
                    <button type="submit" class="btn-primary font-bold py-3 px-6 rounded-lg flex items-center justify-center uppercase">
                        <i data-lucide="save" class="w-5 h-5 mr-2"></i> GUARDAR CAMBIOS
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div id="manageSourcesPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="folder-search" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 class="text-xl font-bold uppercase">GESTIONAR FUENTES</h3>
            </div>
            <button onclick="closePanel('manageSourcesPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <div class="p-8 flex-grow flex flex-col">
            <div class="flex-grow overflow-y-auto pr-2 -mr-2">
                <div class="mb-6">
                    <h4 class="text-lg font-bold text-gray-800 mb-3 uppercase">Añadir Nueva Fuente</h4>
                    <div class="flex gap-2">
                        <input type="text" id="new-source-name" placeholder="Nombre De La Fuente" class="flex-grow p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                        <button id="add-source-btn" class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase">
                            <i data-lucide="plus" class="w-5 h-5"></i>
                        </button>
                    </div>
                </div>
                <div>
                    <h4 class="text-lg font-bold text-gray-800 mb-3 uppercase">Fuentes Existentes</h4>
                    <ul id="sources-list" class="space-y-2">
                    </ul>
                </div>
            </div>
            <div class="mt-8 flex justify-end flex-shrink-0">
                <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('manageSourcesPanel')">CANCELAR</button>
            </div>
        </div>
    </div>
</div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ELIMINACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR ESTE <span id="confirm-item-type" class="font-semibold">ELEMENTO</span>? ESTA ACCIÓN NO SE PUEDE DESHACER.</p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmDeleteModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>

<div id="confirmConvertModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i data-lucide="user-check" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR CONVERSIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿Estás seguro de que deseas convertir a <span id="convert-prospect-name" class="font-semibold">este prospecto</span> en un cliente? </p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmConvertModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-convert-button">CONFIRMAR</button>
        </div>
    </div>
</div>

<script>
// =================================================================
// CONFIGURACIÓN INICIAL Y VARIABLES GLOBALES
// =================================================================
let prospectsData = <?php echo $prospects_json; ?>;
let leadSourcesData = [];
let filteredProspects = [];
let currentMonthFilter = '';
let prospectIdToConvert = null;
let currentView = 'kanban';


// =================================================================
// SELECCIÓN DE ELEMENTOS DEL DOM
// (Este bloque se deja intacto ya que las variables coinciden con el original)
// =================================================================
const prospectSearchInput = document.getElementById('prospect-search');
const prospectFilterStatusSelect = document.getElementById('prospect-filter-status');
const prospectFilterSourceSelect = document.getElementById('prospect-filter-source');
const monthFilterSelect = document.getElementById('month-filter-select');
const prospectosKanbanView = document.getElementById('prospectos-kanban-view');
const prospectosTableView = document.getElementById('prospectos-table-view');
const prospectsTableBody = document.getElementById('prospectsTableBody');
const seguimientoTableBody = document.getElementById('seguimientoTableBody');
const descartadosTableBody = document.getElementById('descartadosTableBody');
const kanbanViewBtn = document.getElementById('kanban-view-btn');
const tableViewBtn = document.getElementById('table-view-btn');
const totalProspectosCount = document.getElementById('total-prospectos-count');
const monthlyProspectosCount = document.getElementById('monthly-prospectos-count');
const addProspectoForm = document.getElementById('add-prospecto-form');
const editProspectoForm = document.getElementById('edit-prospecto-form');
const downloadProspectosBtn = document.getElementById('download-prospectos-btn');
const manageSourcesBtn = document.getElementById('manage-sources-btn');
const manageSourcesPanel = document.getElementById('manageSourcesPanel');
const newSourceNameInput = document.getElementById('new-source-name');
const addSourceBtn = document.getElementById('add-source-btn');
const sourcesList = document.getElementById('sources-list');
const addProspectoFuenteSelect = document.getElementById('prospecto-fuente');
const editProspectoFuenteSelect = document.getElementById('edit-prospecto-fuente');
const confirmConvertButton = document.getElementById('confirm-convert-button');
const convertProspectNameSpan = document.getElementById('convert-prospect-name');
const mobileMenuButton = document.getElementById('mobile-menu-button');
const sidebar = document.getElementById('sidebar');
const sidebarOverlay = document.getElementById('sidebar-overlay');
const phoneInput = document.getElementById('contact_phone');


// =================================================================
// DEFINICIONES DE ESTADOS Y CONFIGURACIONES (AQUÍ ESTÁ LA CORRECCIÓN)
// =================================================================

// 1. Estados del Kanban Principal (Fases Iniciales)
const mainStatuses = {
    "Entrante": { title: "LEAD ENTRANTE", icon: "bell-ring", color: "var(--color-secondary)" },
    "Nuevo": { title: "LEAD APROVADO", icon: "square-check-big", color: "var(--color-secondary)" },
    "Contactado": { title: "CONTACTADO", icon: "user-check", color: "var(--color-secondary)" }
};

// 2. Estados de Seguimiento (Activos en Funnel 1 o Funnel 2) - Se usan en la Tabla de Seguimiento
const trackingStatuses = {
    "En Seguimiento": { title: "EN SEGUIMIENTO", icon: "search-check", color: "#FBBF24" }, // F1 - Comprender Problema
    "Presentar Solución": { title: "PRESENTANDO LA SOLUCIÓN", icon: "presentation", color: "#3B82F6" },
    "Introducir Servicio": { title: "INTRODUCIENDO EL SERVICIO", icon: "package-check", color: "#3B82F6" },
    "Cotización Solicitada": { title: "COTIZACIÓN SOLICITADA", icon: "file-check-2", color: "#34D399" },
    
    "Cotización Enviada": { title: "COTIZACIÓN ENVIADA", icon: "file-check-2", color: "#34D399" },
    "Seguimiento Post Envío": { title: "SEGUIMIENTO POST-ENVÍO", icon: "badge-check", color: "#34D399" },
    "Seguimiento Recordatorio": { title: "SEGUIMIENTO RECORDATORIO", icon: "badge-info", color: "#34D399" },
    "Negociación Final": { title: "NEGOCIACIÓN FINAL", icon: "badge-plus", color: "#34D399" },
};

const closedStatuses = {
    "Descartado": { title: "DESCARTADO", icon: "x-circle", color: "var(--color-secondary)" },
};

// 4. Combinar todos para búsquedas y ediciones de estado
const allStatuses = { ...mainStatuses, ...trackingStatuses, ...closedStatuses };


// =================================================================
// FUNCIONES AUXILIARES Y DE UTILIDAD
// =================================================================
function recreateLucideIcons(element) {
    if (!element) {
        console.warn("recreateLucideIcons fue llamado con un elemento nulo o indefinido.");
        return;
    }
    if (typeof lucide !== 'undefined' && lucide.createIcons) {
        lucide.createIcons({ container: element });
    }
}

function formatPhoneNumber(number) {
    if (!number) return '';
    const cleaned = ('' + number).replace(/\D/g, '');
    const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
    if (match) {
        return `(${match[1]}) ${match[2]}-${match[3]}`;
    }
    return cleaned;
}

function applyInputPhoneFormat(inputElement) {
    if (!inputElement) return;
    inputElement.value = formatPhoneNumber(inputElement.value);
    inputElement.addEventListener('input', (e) => {
        let value = e.target.value.replace(/\D/g, '');
        e.target.value = formatPhoneNumber(value);
    });
    inputElement.addEventListener('blur', (e) => {
        e.target.value = formatPhoneNumber(e.target.value);
    });
}

function applyPhoneFormatToInputs() {
    const phoneOptions = {
        mask: '(000) 000-0000',
        lazy: false // Importante: Fuerza a que la máscara se muestre de inmediato
    };

    // Inputs del panel "Agregar"
    const addTelefono = document.getElementById('prospecto-telefono');
    const addCelular = document.getElementById('prospecto-celular');
    // Inputs del panel "Editar"
    const editTelefono = document.getElementById('edit-prospecto-telefono');
    const editCelular = document.getElementById('edit-prospecto-celular');

    // Aplica iMask a cada input si existe
    if (addTelefono && !addTelefono.imask) { // Evita reinicializar
        addTelefono.imask = IMask(addTelefono, phoneOptions);
    }
    if (addCelular && !addCelular.imask) { // Evita reinicializar
        addCelular.imask = IMask(addCelular, phoneOptions);
    }
    if (editTelefono && !editTelefono.imask) { // Evita reinicializar
        editTelefono.imask = IMask(editTelefono, phoneOptions);
    }
    if (editCelular && !editCelular.imask) { // Evita reinicializar
        editCelular.imask = IMask(editCelular, phoneOptions);
    }
    console.log("[applyPhoneFormatToInputs] IMask inicializado en los campos necesarios.");
}

function getMonthName(monthIndex) {
    const months = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
    return months[monthIndex];
}

function getPriorityBadgeHtml(prioridad) {
    let badgeClass = 'bg-gray-100 text-gray-800';
    let iconName = 'snowflake'; 
    let priorityText = 'BAJA';

    switch (prioridad) {
        case 'Alta': 
            badgeClass = 'bg-[var(--color-secondary)] text-white';
            iconName = 'flame';
            priorityText = 'ALTA'; 
            break;
        case 'Media': 
            badgeClass = 'bg-blue-100 text-blue-800';
            iconName = 'thermometer-snowflake';
            priorityText = 'MEDIA'; 
            break;
        case 'Baja': 
            break;
    }

    return `<span class="inline-flex items-center gap-1 px-2 py-1 text-xs font-bold rounded-full ${badgeClass}">
                <i data-lucide="${iconName}" class="w-3 h-3"></i>
                ${priorityText}
            </span>`;
}


// =================================================================
// MANEJO DE PANELES Y MODALES
// =================================================================
const panelOverlay = document.createElement('div');
panelOverlay.id = 'panel-overlay';
panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
document.body.appendChild(panelOverlay);

function openPanel(panelId) {
    const panel = document.getElementById(panelId);
    if (!panel) { 
        // Si no encuentra el panel, muestra error y detiene
        showToast(`Error: Panel con ID "${panelId}" no encontrado.`, 'error'); 
        return; 
    }
    
    // Muestra el panel y el overlay
    panel.classList.remove('translate-x-full');
    panel.classList.add('translate-x-0');
    panelOverlay.classList.remove('hidden'); 
    document.body.style.overflow = 'hidden'; 
    recreateLucideIcons(panel); 
}

function closePanel(panelId) {
    const panel = document.getElementById(panelId);
    if (!panel) { showToast(`Error: Panel con ID "${panelId}" no encontrado para cerrar.`, 'error'); return; }
    panel.classList.remove('translate-x-0');
    panel.classList.add('translate-x-full');
    panelOverlay.classList.add('hidden');
    document.body.style.overflow = '';
}

function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) { showToast(`Error: Modal con ID "${modalId}" no encontrado.`, 'error'); return; }
    const modalBox = modal.querySelector('div:first-of-type');
    modal.classList.remove('hidden');
    setTimeout(() => { modalBox.classList.remove('scale-95', 'opacity-0'); }, 50);
    panelOverlay.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
    recreateLucideIcons(modal);
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) { showToast(`Error: Modal con ID "${modalId}" no encontrado para cerrar.`, 'error'); return; }
    const modalBox = modal.querySelector('div:first-of-type');
    modalBox.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
        panelOverlay.classList.add('hidden');
        document.body.style.overflow = '';
    }, 300);
}


// =================================================================
// ACCIONES PRINCIPALES (MODALES DE CONFIRMACIÓN, ETC.)
// =================================================================
window.openConfirmDeleteModal = function(itemId, itemType) {
    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    const confirmItemTypeSpan = document.getElementById('confirm-item-type');
    if (!confirmDeleteButton || !confirmItemTypeSpan) { showToast("Error: Elementos del modal de confirmación de eliminación no encontrados.", 'error'); return; }

    confirmDeleteButton.dataset.itemId = itemId;
    confirmDeleteButton.dataset.itemType = itemType;
    confirmItemTypeSpan.textContent = itemType.toUpperCase();

    confirmDeleteButton.onclick = null;

    confirmDeleteButton.onclick = async function() {
        const idToDelete = this.dataset.itemId;
        const typeToDelete = this.dataset.itemType;

        if (typeToDelete === 'prospecto') {
            try {
                const response = await fetch('db/leads-delete.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: idToDelete })
                });
                const result = await response.json();
                if (result.success) {
                    closeModal('confirmDeleteModal');
                    showToast('Prospecto eliminado con éxito.', 'success');
                    location.reload();
                } else {
                    showToast(result.message || 'Error desconocido al eliminar prospecto.', 'error');
                    closeModal('confirmDeleteModal');
                }
            } catch (error) {
                showToast('Error de conexión al eliminar prospecto.', 'error');
                closeModal('confirmDeleteModal');
            }
        } else if (typeToDelete === 'fuente') {
            try {
                const response = await fetch('db/lead-sources-delete.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: idToDelete })
                });
                const result = await response.json();
                if (result.success) {
                    closeModal('confirmDeleteModal');
                    showToast('Fuente eliminada con éxito.', 'success');
                    fetchAndPopulateSources();
                } else {
                    showToast(result.message || 'Error desconocido al eliminar fuente.', 'error');
                    closeModal('confirmDeleteModal');
                }
            } catch (error) {
                showToast('Error de conexión al eliminar fuente.', 'error');
                closeModal('confirmDeleteModal');
            }
        }
    };
    openModal('confirmDeleteModal');
};

window.openConfirmConvertModal = function(prospectId) {
    const prospect = prospectsData[prospectId];
    if (!prospect) {
        showToast('Prospecto no encontrado para confirmar conversión.', 'error');
        return;
    }

    prospectIdToConvert = prospectId;
    if (convertProspectNameSpan) {
        convertProspectNameSpan.textContent = prospect.nombre_completo;
    }

    openModal('confirmConvertModal');
};

window.openEditPanel = function(id) {
    const prospect = prospectsData[id];
    if (prospect) {
        document.getElementById('edit-prospecto-id').value = prospect.id;
        document.getElementById('edit-prospecto-first-name').value = prospect.first_name || '';
        document.getElementById('edit-prospecto-last-name').value = prospect.last_name || '';
        document.getElementById('edit-prospecto-empresa').value = prospect.empresa || '';
        document.getElementById('edit-prospecto-email').value = prospect.email || '';
        document.getElementById('edit-prospecto-telefono').value = prospect.phone || '';
        document.getElementById('edit-prospecto-celular').value = prospect.mobile || '';
        
        const editProspectoFuenteSelect = document.getElementById('edit-prospecto-fuente');
        if (editProspectoFuenteSelect) {
            populateSourceSelect(editProspectoFuenteSelect, prospect.fuente);
        }

        document.getElementById('edit-prospecto-direccion-calle').value = prospect.direccion_calle || '';
        document.getElementById('edit-prospecto-ciudad').value = prospect.ciudad || '';
        document.getElementById('edit-prospecto-estado-provincia').value = prospect.state_province || '';
        document.getElementById('edit-prospecto-codigo-postal').value = prospect.zip_code || '';
        document.getElementById('edit-prospecto-prioridad').value = prospect.prioridad || 'Media';

        const statusSelect = document.getElementById('edit-prospecto-status');
        if (statusSelect) {
            statusSelect.innerHTML = '';
            for (const key in allStatuses) {
                const option = document.createElement('option');
                option.value = key;
                option.textContent = allStatuses[key].title;
                statusSelect.appendChild(option);
            }
            statusSelect.value = prospect.estado;
        }

        openPanel('editProspectoPanel');
        applyPhoneFormatToInputs();
    } else {
        showToast('Prospecto no encontrado para editar.', 'error');
    }
}

// =================================================================
// LÓGICA DE DATOS (FETCH, UPDATE, DELETE)
// =================================================================
async function convertToClientLogic() {
    if (!prospectIdToConvert) {
        showToast('No se ha seleccionado ningún prospecto para convertir.', 'error');
        return;
    }

    const prospect = prospectsData[prospectIdToConvert];
    if (!prospect) {
        showToast('Error: Datos del prospecto no disponibles para la conversión.', 'error');
        closeModal('confirmConvertModal');
        return;
    }

    try {
        showToast('Convirtiendo prospecto a cliente...', 'info');
        closeModal('confirmConvertModal');

        const response = await fetch('db/leads-convert-to-client.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prospect_id: prospectIdToConvert })
        });
        const result = await response.json();

        if (result.success) {
            showToast(result.message || 'Prospecto convertido a cliente con éxito.', 'success');
            location.reload();
        } else {
            showToast(result.message || 'Error desconocido al convertir prospecto a cliente.', 'error');
        }
    } catch (error) {
        showToast('Error de conexión al convertir prospecto a cliente.', 'error');
    } finally {
        prospectIdToConvert = null;
    }
}

async function updateProspectStatus(prospectId, newStatus) {
    try {
        const response = await fetch('db/leads-update-status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: prospectId, status: newStatus })
        });
        const result = await response.json();
        if (result.success) {
            showToast('Estado del prospecto actualizado con éxito.', 'success');
            location.reload();
        } else {
            showToast(result.message || 'Error desconocido al actualizar estado del prospecto.', 'error');
        }
    } catch (error) {
        showToast('Error de conexión al actualizar estado del prospecto.', 'error');
    }
}

async function fetchAndPopulateSources() {
    try {
        const response = await fetch('db/lead-sources-read.php?' + new Date().getTime());
        const result = await response.json();
        if (result.success) {
            leadSourcesData = result.data;
            populateSourceSelects();
            renderManageSourcesList();
        } else {
            showToast('Error al cargar fuentes de leads: ' + (result.message || 'Error desconocido.'), 'error');
        }
    } catch (error) {
        showToast('Error de conexión al cargar fuentes de leads.', 'error');
    }
}

// =================================================================
// RENDERIZADO Y VISUALIZACIÓN (AQUÍ ESTÁ LA CORRECCIÓN CLAVE)
// =================================================================
function populateMonthFilter() {
    const now = new Date();
    const currentMonth = now.getMonth();
    const currentYear = now.getFullYear();
    const monthsToDisplay = new Set();
    
    monthsToDisplay.add(`${currentYear}-${String(currentMonth + 1).padStart(2, '0')}`);

    Object.values(prospectsData).forEach(prospect => {
        if (prospect.created_at) {
            const createdAtDate = new Date(prospect.created_at);
            const leadMonth = createdAtDate.getMonth();
            const leadYear = createdAtDate.getFullYear();
            monthsToDisplay.add(`${leadYear}-${String(leadMonth + 1).padStart(2, '0')}`);
        }
    });

    const sortedDates = Array.from(monthsToDisplay).map(monthKey => {
        const [year, month] = monthKey.split('-').map(Number);
        return new Date(year, month - 1, 1);
    }).sort((a, b) => b - a); // Ordenar descendente

    monthFilterSelect.innerHTML = '';
    
    const allOption = document.createElement('option');
    allOption.value = 'all';
    allOption.textContent = 'TODOS LOS MESES';
    monthFilterSelect.appendChild(allOption);

    sortedDates.forEach(date => {
        let monthIndex = date.getMonth();
        let year = date.getFullYear();
        const option = document.createElement('option');
        option.value = `${year}-${String(monthIndex + 1).padStart(2, '0')}`;
        option.textContent = `${getMonthName(monthIndex).toUpperCase()} ${year}`;
        monthFilterSelect.appendChild(option);
    });

    monthFilterSelect.value = 'all';
    currentMonthFilter = 'all';
    
    console.log("[populateMonthFilter] Filtro mensual poblado, mostrando todos los meses por defecto.");
}

function renderMainKanbanBoard(prospects) {
    prospectosKanbanView.innerHTML = '';
    
    // Obtener las claves de estado que deben ir en el Kanban Principal
    const mainKanbanStatusesKeys = Object.keys(mainStatuses);
    const prospectsForMainBoard = prospects.filter(p => mainKanbanStatusesKeys.includes(p.estado));

    for (const statusKey in mainStatuses) {
        const statusDef = mainStatuses[statusKey];
        const column = document.createElement('div');
        column.className = `kanban-column bg-gray-50 p-4 rounded-xl shadow-inner border-t-4 border-[${statusDef.color}]`;
        column.setAttribute('data-status', statusKey);
        const columnHeader = document.createElement('h4');
        const headerColorClass = statusDef.color.startsWith('var(') ? `text-[${statusDef.color}]` : `text-${statusDef.color}`;
        columnHeader.className = `text-lg font-extrabold text-gray-700 mb-4 flex items-center gap-2 uppercase`;
        columnHeader.innerHTML = `<i data-lucide="${statusDef.icon}" class="w-6 h-6 ${headerColorClass}"></i> ${statusDef.title}`;
        column.appendChild(columnHeader);
        const prospectList = document.createElement('div');
        prospectList.className = 'space-y-4 min-h-[100px]';
        prospectList.setAttribute('data-status-list', statusKey);
        column.appendChild(prospectList);
        prospectosKanbanView.appendChild(column);
    }
    recreateLucideIcons(prospectosKanbanView);

    prospectsForMainBoard.forEach(prospect => {
        const card = createProspectCard(prospect);
        const targetList = prospectosKanbanView.querySelector(`[data-status-list="${prospect.estado}"]`);
        if (targetList) {
            targetList.appendChild(card);
        }
    });
    setupDragAndDrop(prospectosKanbanView);
}

function renderSeguimientoTable(prospects) {
    seguimientoTableBody.innerHTML = '';
    
    // Obtener las claves de estado que deben ir en la Tabla de Seguimiento
    const trackingStatusesKeys = Object.keys(trackingStatuses); 
    const prospectsForTrackingBoard = prospects.filter(p => trackingStatusesKeys.includes(p.estado));

    if (prospectsForTrackingBoard.length === 0) {
        seguimientoTableBody.innerHTML = `<tr><td colspan="5" class="py-4 text-center text-gray-500">NO SE ENCONTRARON PROSPECTOS EN SEGUIMIENTO</td></tr>`;
        return;
    }

    prospectsForTrackingBoard.forEach(prospect => {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-100 hover:bg-gray-50';
        let statusClass = '';
        const statusDef = trackingStatuses[prospect.estado];
        if (statusDef) {
            // Asignar clases de color basadas en el grupo de funnel
            if (prospect.estado.includes('(F1)')) {
                statusClass = 'bg-yellow-100 text-yellow-800'; 
            } else if (prospect.estado.includes('(F2)')) {
                statusClass = 'bg-green-100 text-green-800'; 
            } else {
                statusClass = 'bg-gray-100 text-gray-800'; 
            }
        } else {
            statusClass = 'bg-gray-100 text-gray-800';
        }

        const priorityBadgeHtml = getPriorityBadgeHtml(prospect.prioridad);

        row.innerHTML = `
            <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE"><div class="flex items-center gap-2"><span>${prospect.nombre_completo}</span>${priorityBadgeHtml}</div> <p class="text-xs text-gray-500">${prospect.empresa || ''}</p></td>
            <td class="py-3 px-6 hidden md:table-cell" data-label="TELÉFONO">${formatPhoneNumber(prospect.phone || prospect.mobile || '')}</td>
            <td class="py-3 px-6 hidden lg:table-cell" data-label="EMAIL">${prospect.email}</td>
            <td class="py-3 px-6" data-label="ESTADO">
                <span class="px-3 py-1 rounded-full text-xs font-semibold ${statusClass}">
                    ${statusDef?.title || prospect.estado.toUpperCase()}
                </span>
            </td>
            <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                <div class="flex flex-row justify-center space-x-2">
                    <button class="text-gray-500 hover:text-[var(--color-primary)] edit-prospecto-btn" data-id="${prospect.id}" title="Editar">
                        <i data-lucide="edit" class="w-5 h-5"></i>
                    </button>
                    <button class="text-gray-500 hover:text-[var(--color-secondary)] delete-prospecto-btn" data-id="${prospect.id}" title="Eliminar">
                        <i data-lucide="trash-2" class="w-5 h-5"></i>
                    </button>
                    ${['Nuevo', 'Contactado', 'En Seguimiento', 'Cotizacion Solicitada', 'Seguimiento Post Envío', 'Seguimiento Recordatorio', 'Negociación Final'].includes(prospect.estado) ?
                        `<button class="text-green-600 hover:text-green-800 convert-to-client-btn" data-id="${prospect.id}" title="Convertir A Cliente">
                            <i data-lucide="user-check" class="w-5 h-5"></i>
                        </button>` : ''}
                </div>
            </td>
        `;
        seguimientoTableBody.appendChild(row);
        recreateLucideIcons(row);
        row.querySelector('.edit-prospecto-btn').addEventListener('click', () => openEditPanel(prospect.id));
        row.querySelector('.delete-prospecto-btn').addEventListener('click', () => window.openConfirmDeleteModal(prospect.id, 'prospecto'));
        const convertBtnSeguimiento = row.querySelector('.convert-to-client-btn');
        if (convertBtnSeguimiento) {
            convertBtnSeguimiento.addEventListener('click', () => openConfirmConvertModal(prospect.id));
        }
    });
}

function renderDescartedProspectsTable(prospects) {
    descartadosTableBody.innerHTML = '';
    
    // Obtener las claves de estado que deben ir en la Tabla de Rechazados
    const closedStatusesKeys = Object.keys(closedStatuses);
    const prospectsDescartados = prospects.filter(p => closedStatusesKeys.includes(p.estado));

    if (prospectsDescartados.length === 0) {
        descartadosTableBody.innerHTML = `<tr><td colspan="5" class="py-4 text-center text-gray-500">NO SE ENCONTRARON PROSPECTOS RECHAZADOS</td></tr>`;
        return;
    }

    prospectsDescartados.forEach(prospecto => {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-100 hover:bg-gray-50';
        
        let statusClass = 'bg-gray-100 text-gray-800';
        if (prospecto.estado === 'Ganada') {
            statusClass = 'bg-green-100 text-green-800';
        } else if (prospecto.estado === 'Perdida' || prospecto.estado === 'Descartado') {
            statusClass = 'bg-[var(--color-secondary)]-100 text-[var(--color-secondary)]';
        }

        const priorityBadgeHtml = getPriorityBadgeHtml(prospecto.prioridad);
        const statusTitle = closedStatuses[prospecto.estado]?.title || prospecto.estado.toUpperCase();

        row.innerHTML = `
            <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE"><div class="flex items-center gap-2"><span>${prospecto.nombre_completo}</span>${priorityBadgeHtml}</div> <p class="text-xs text-gray-500">${prospecto.empresa || ''}</p></td>
            <td class="py-3 px-6 hidden md:table-cell" data-label="TELÉFONO">${formatPhoneNumber(prospecto.phone || prospecto.mobile || '')}</td>
            <td class="py-3 px-6 hidden lg:table-cell" data-label="EMAIL">${prospecto.email}</td>
            <td class="py-3 px-6" data-label="ESTADO">
                <span class="px-3 py-1 rounded-full text-xs font-semibold ${statusClass}">
                    ${statusTitle}
                </span>
            </td>
            <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                <div class="flex flex-row justify-center space-x-2">
                    <button class="text-gray-500 hover:text-[var(--color-primary)] edit-prospecto-btn" data-id="${prospecto.id}" title="Editar">
                        <i data-lucide="edit" class="w-5 h-5"></i>
                    </button>
                    <button class="text-gray-500 hover:text-red-500 delete-prospecto-btn" data-id="${prospecto.id}" title="Eliminar">
                        <i data-lucide="trash-2" class="w-5 h-5"></i>
                    </button>
                </div>
            </td>
        `;
        descartadosTableBody.appendChild(row);
        recreateLucideIcons(row);
        row.querySelector('.edit-prospecto-btn').addEventListener('click', () => openEditPanel(prospecto.id));
        row.querySelector('.delete-prospecto-btn').addEventListener('click', () => window.openConfirmDeleteModal(prospecto.id, 'prospecto'));
    });
}

function createProspectCard(prospect) {
    const card = document.createElement('div');
    let iconSize = 'w-6 h-6';
    let textSize = 'text-lg';
    let detailTextSize = 'text-sm';
    let iconBtnClasses = 'p-2';

    card.className = 'kanban-card bg-white p-4 rounded-lg shadow-sm border border-gray-200 cursor-grab active:cursor-grabbing';
    card.setAttribute('draggable', true);
    card.setAttribute('data-prospect-id', prospect.id);

    const displayEmpresa = prospect.empresa || 'Sin Negocio';
    const displayPhone = formatPhoneNumber(prospect.phone || prospect.mobile || '');

    let actionButtonsHtml = '';
    if (prospect.estado === 'Entrante') {
        actionButtonsHtml = `
            <button class="btn-primary flex items-center justify-center py-2 px-4 rounded-md text-sm uppercase approve-prospecto-btn" data-id="${prospect.id}" title="Aprobar Prospecto">
                <i data-lucide="check-circle" class="w-6 h-6 mr-1"></i> Aprobar
            </button>
            <button class="bg-[var(--color-secondary)] hover:bg-[var(--color-secondary)] text-white flex items-center justify-center py-2 px-4 rounded-md text-sm uppercase discard-prospecto-btn" data-id="${prospect.id}" title="Desechar Prospecto">
                <i data-lucide="x-circle" class="w-6 h-6 mr-1"></i> Desechar
            </button>
        `;
    } else {
        actionButtonsHtml = `
            <button class="text-gray-500 hover:text-[var(--color-primary)] ${iconBtnClasses} rounded-md edit-prospecto-btn" data-id="${prospect.id}" title="Editar">
                <i data-lucide="edit" class="w-5 h-5"></i>
            </button>
            <button class="text-gray-500 hover:text-[var(--color-secondary)] ${iconBtnClasses} rounded-md delete-prospecto-btn" data-id="${prospect.id}" title="Eliminar">
                <i data-lucide="trash-2" class="w-5 h-5"></i>
            </button>
            ${Object.keys(trackingStatuses).includes(prospect.estado) || Object.keys(mainStatuses).includes(prospect.estado) ?
                `<button class="text-green-600 hover:text-green-800 ${iconBtnClasses} rounded-md convert-to-client-btn" data-id="${prospect.id}" title="Convertir A Cliente">
                    <i data-lucide="user-check" class="w-5 h-5"></i>
                </button>` : ''}
        `;
    }

    const priorityBadgeHtml = getPriorityBadgeHtml(prospect.prioridad);

    card.innerHTML = `
        <div class="card-header cursor-pointer flex justify-between items-center pb-2 mb-2">
            <div>
                <h5 class="font-semibold text-gray-800 ${textSize} flex items-center gap-2">
                    ${prospect.nombre_completo}
                    ${priorityBadgeHtml}
                </h5>
                <p class="text-gray-500 ${detailTextSize} mt-1">${displayEmpresa}</p>
            </div>
            <button class="toggle-details-btn text-gray-400 hover:text-gray-600">
                <i data-lucide="chevron-down" class="${iconSize}"></i>
            </button>
        </div>
        <div class="card-details hidden space-y-1">
            <div class="flex items-center text-gray-600 ${detailTextSize}">
                <i data-lucide="mail" class="${iconSize} mr-2 text-gray-400"></i> ${(prospect.email || 'Sin Email - Solicitarlo')}
            </div>
            <div class="flex items-center text-gray-600 ${detailTextSize}">
                <i data-lucide="phone" class="${iconSize} mr-2 text-gray-400"></i> ${displayPhone}
            </div>
            <div class="flex items-center text-gray-600 ${detailTextSize}">
                <i data-lucide="tag" class="${iconSize} mr-2 text-gray-400"></i> ${prospect.fuente}
            </div>
        </div>
        <div class="mt-4 flex ${prospect.estado === 'Entrante' ? 'flex-col space-y-2' : 'justify-end space-x-2 flex-row'}"> ${actionButtonsHtml}
        </div>
    `;

    recreateLucideIcons(card);

    const approveButton = card.querySelector('.approve-prospecto-btn');
    const discardButton = card.querySelector('.discard-prospecto-btn');
    const editButton = card.querySelector('.edit-prospecto-btn');
    const deleteButton = card.querySelector('.delete-prospecto-btn');
    const convertToClientButton = card.querySelector('.convert-to-client-btn');
    const toggleDetailsButton = card.querySelector('.toggle-details-btn');
    const cardDetails = card.querySelector('.card-details');

    if (approveButton) {
        approveButton.addEventListener('click', async (e) => {
            e.stopPropagation();
            await updateProspectStatus(prospect.id, 'Nuevo');
        });
    }
    if (discardButton) {
        discardButton.addEventListener('click', async (e) => {
            e.stopPropagation();
            showToast('Prospecto descartado.', 'info');
            await updateProspectStatus(prospect.id, 'Descartado');
        });
    }
    if (editButton) {
        editButton.addEventListener('click', (e) => {
            e.stopPropagation();
            openEditPanel(prospect.id);
        });
    }
    if (deleteButton) {
        deleteButton.addEventListener('click', (e) => {
            e.stopPropagation();
            window.openConfirmDeleteModal(prospect.id, 'prospecto');
        });
    }
    if (convertToClientButton) {
        convertToClientButton.addEventListener('click', (e) => {
            e.stopPropagation();
            openConfirmConvertModal(prospect.id);
        });
    }
    if (toggleDetailsButton && cardDetails) {
        toggleDetailsButton.addEventListener('click', (e) => {
            e.stopPropagation();
            cardDetails.classList.toggle('hidden');
            const icon = toggleDetailsButton.querySelector('i');
            if (icon) {
                icon.setAttribute('data-lucide', cardDetails.classList.contains('hidden') ? 'chevron-down' : 'chevron-up');
                recreateLucideIcons(toggleDetailsButton);
            }
        });
        card.querySelector('.card-header').addEventListener('click', (e) => {
            if (!e.target.closest('button')) {
                toggleDetailsButton.click();
            }
        });
    }
    return card;
}

function setupDragAndDrop(containerElement) {
    let draggingCard = null;
    
    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.kanban-card:not(.dragging)')];
        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    containerElement.addEventListener('dragstart', e => {
        if (e.target.classList.contains('kanban-card')) {
            draggingCard = e.target;
            e.target.classList.add('dragging');
        }
    });

    containerElement.addEventListener('dragend', e => {
        if (draggingCard) {
            draggingCard.classList.remove('dragging');
            draggingCard = null;
        }
    });

    containerElement.querySelectorAll('.kanban-column').forEach(column => {
        const prospectList = column.querySelector('[data-status-list]');
        if (prospectList) {
            prospectList.addEventListener('dragover', e => {
                e.preventDefault();
                if (!draggingCard) return;
                const afterElement = getDragAfterElement(prospectList, e.clientY);
                if (afterElement == null) {
                    prospectList.appendChild(draggingCard);
                } else {
                    prospectList.insertBefore(draggingCard, afterElement);
                }
            });

            prospectList.addEventListener('drop', async e => {
                e.preventDefault();
                if (!draggingCard) return;
                const prospectId = draggingCard.dataset.prospectId;
                const newStatus = column.dataset.status;
                if (prospectsData[prospectId] && prospectsData[prospectId].estado !== newStatus) {
                    await updateProspectStatus(prospectId, newStatus);
                }
            });
        }
    });
}

function renderTable(prospects) {
    prospectsTableBody.innerHTML = '';
    
    // La tabla principal debe mostrar leads de Main Kanban y leads de Seguimiento (Activos)
    const activeStatusesKeys = Object.keys(mainStatuses).concat(Object.keys(trackingStatuses));
    const prospectsForMainTable = prospects.filter(p => activeStatusesKeys.includes(p.estado));

    if (prospectsForMainTable.length === 0) {
        prospectsTableBody.innerHTML = `<tr><td colspan="5" class="py-4 text-center text-gray-500">No se encontraron prospectos.</td></tr>`;
        return;
    }

    prospectsForMainTable.forEach(prospecto => {
        const row = document.createElement('tr');
        row.className = 'border-b border-gray-100 hover:bg-gray-50';
        
        let statusClass = 'bg-gray-100 text-gray-800';
        let statusTitle = prospecto.estado.toUpperCase();
        
        const statusDef = allStatuses[prospecto.estado];
        if (statusDef) {
            statusTitle = statusDef.title;
            if (Object.keys(mainStatuses).includes(prospecto.estado)) {
                statusClass = 'bg-blue-100 text-blue-800'; 
            } else if (Object.keys(trackingStatuses).includes(prospecto.estado)) {
                statusClass = 'bg-yellow-100 text-yellow-800';
            }
        }

        const priorityBadgeHtml = getPriorityBadgeHtml(prospecto.prioridad);

        row.innerHTML = `
            <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE"><div class="flex items-center gap-2"><span>${prospecto.nombre_completo}</span>${priorityBadgeHtml}</div> <p class="text-xs text-gray-500">${prospecto.empresa || ''}</p></td>
            <td class="py-3 px-6 hidden md:table-cell" data-label="TELÉFONO">${formatPhoneNumber(prospecto.phone || prospecto.mobile || '')}</td>
            <td class="py-3 px-6 hidden lg:table-cell" data-label="EMAIL">${prospecto.email}</td>
            <td class="py-3 px-6" data-label="ESTADO">
                <span class="px-3 py-1 rounded-full text-xs font-semibold ${statusClass}">
                    ${statusTitle}
                </span>
            </td>
            <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                <div class="flex flex-row justify-center space-x-2">
                    <button class="text-gray-500 hover:text-[var(--color-primary)] edit-prospecto-btn" data-id="${prospecto.id}" title="Editar">
                        <i data-lucide="edit" class="w-5 h-5"></i>
                    </button>
                    <button class="text-gray-500 hover:text-[var(--color-secondary)] delete-prospecto-btn" data-id="${prospecto.id}" title="Eliminar">
                        <i data-lucide="trash-2" class="w-5 h-5"></i>
                    </button>
                    ${activeStatusesKeys.includes(prospecto.estado) ?
                        `<button class="text-green-600 hover:text-green-800 convert-to-client-btn" data-id="${prospecto.id}" title="Convertir A Cliente">
                            <i data-lucide="user-check" class="w-5 h-5"></i>
                        </button>` : ''}
                </div>
            </td>
        `;
        prospectsTableBody.appendChild(row);
        recreateLucideIcons(row);
        row.querySelector('.edit-prospecto-btn').addEventListener('click', () => openEditPanel(prospecto.id));
        row.querySelector('.delete-prospecto-btn').addEventListener('click', () => window.openConfirmDeleteModal(prospecto.id, 'prospecto'));
        const convertBtnTabla = row.querySelector('.convert-to-client-btn');
        if (convertBtnTabla) {
            convertBtnTabla.addEventListener('click', () => openConfirmConvertModal(prospecto.id));
        }
    });
}

function updateProspectCounts() {
    totalProspectosCount.textContent = Object.keys(prospectsData).length;
    
    // Obtener los leads que coinciden con el filtro de mes para el KPI mensual
    const monthFilter = monthFilterSelect.value;
    const monthlyProspectsCountValue = Object.values(prospectsData).filter(prospect => {
        if (monthFilter === 'all') return true;
        if (prospect.created_at) {
            const createdAtDate = new Date(prospect.created_at);
            const prospectMonthYear = `${createdAtDate.getFullYear()}-${String(createdAtDate.getMonth() + 1).padStart(2, '0')}`;
            return prospectMonthYear === monthFilter;
        }
        return false;
    }).length;

    monthlyProspectosCount.textContent = monthlyProspectsCountValue;
}

function filterAndRenderProspects() {
    const searchTerm = prospectSearchInput.value.toLowerCase();
    const statusFilter = prospectFilterStatusSelect.value;
    const sourceFilter = prospectFilterSourceSelect.value;
    const monthFilter = monthFilterSelect.value;

    filteredProspects = Object.values(prospectsData).filter(prospect => {
        const matchesSearch = searchTerm === '' || prospect.nombre_completo.toLowerCase().includes(searchTerm) || (prospect.empresa && prospect.empresa.toLowerCase().includes(searchTerm));
        
        // El filtro de estado ahora debe filtrar por todos los estados si se selecciona 'all'
        const matchesStatus = statusFilter === 'all' || prospect.estado === statusFilter;
        
        const matchesSource = sourceFilter === 'all' || prospect.fuente === sourceFilter;
        let matchesMonth = true;
        if (prospect.created_at) {
            const createdAtDate = new Date(prospect.created_at);
            const prospectMonthYear = `${createdAtDate.getFullYear()}-${String(createdAtDate.getMonth() + 1).padStart(2, '0')}`;
            if (monthFilter !== 'all') {
                matchesMonth = prospectMonthYear === monthFilter;
            }
        } else {
            if (monthFilter !== 'all') {
                matchesMonth = false;
            }
        }
        return matchesSearch && matchesStatus && matchesSource && matchesMonth;
    });

    updateProspectCounts();

    // Re-filtrar para las secciones
    const mainKanbanStatusesKeys = Object.keys(mainStatuses);
    const trackingStatusesKeys = Object.keys(trackingStatuses);
    const closedStatusesKeys = Object.keys(closedStatuses);
    
    const leadsForMainKanban = filteredProspects.filter(p => mainKanbanStatusesKeys.includes(p.estado));
    const leadsForTrackingTable = filteredProspects.filter(p => trackingStatusesKeys.includes(p.estado));
    const leadsForClosedTable = filteredProspects.filter(p => closedStatusesKeys.includes(p.estado));

    if (currentView === 'kanban') {
        prospectosKanbanView.classList.remove('hidden');
        prospectosTableView.classList.add('hidden');
        renderMainKanbanBoard(leadsForMainKanban);
        renderSeguimientoTable(leadsForTrackingTable);
        renderDescartedProspectsTable(leadsForClosedTable);
    } else {
        prospectosKanbanView.classList.add('hidden');
        prospectosTableView.classList.remove('hidden');
        // La tabla principal muestra Main Kanban + Seguimiento
        const leadsForMainTable = leadsForMainKanban.concat(leadsForTrackingTable);
        renderTable(leadsForMainTable);
        renderSeguimientoTable(leadsForTrackingTable); // Mantener para mostrar la lista de seguimiento
        renderDescartedProspectsTable(leadsForClosedTable); // Mantener para mostrar la lista de descartados
    }
}

function populateSourceSelect(selectElement, selectedValue = 'all') {
    selectElement.innerHTML = ''; 

    if (selectElement.id === 'prospect-filter-source') {
        const allOption = document.createElement('option');
        allOption.value = 'all';
        allOption.textContent = 'TODAS LAS FUENTES';
        selectElement.appendChild(allOption);
    }

    let matchedOptionValue = null;

    leadSourcesData.forEach(source => {
        const option = document.createElement('option');
        option.value = source.name; 
        option.textContent = source.name.toUpperCase(); 
        selectElement.appendChild(option);


        if (selectedValue && source.name.toLowerCase() === selectedValue.toLowerCase()) {
             matchedOptionValue = source.name; 
        }
    });

    if (matchedOptionValue) {
         selectElement.value = matchedOptionValue;
    } else if (selectedValue !== 'all' && selectElement.querySelector(`option[value="${selectedValue}"]`)) {
         selectElement.value = selectedValue; // Intenta seleccionar el valor original si existe
    } else if (selectElement.options.length > 0) {
         // Si no hay coincidencia ni valor original, selecciona la primera opción disponible
         // (excepto si es el filtro y queremos 'all')
         if (selectElement.id !== 'prospect-filter-source' || selectedValue !== 'all') {
             selectElement.value = selectElement.options[0].value;
         } else {
             selectElement.value = 'all'; // Para el filtro, mantenemos 'all' si no hay coincidencia
         }
    }
}

function populateSourceSelects() {
    populateSourceSelect(addProspectoFuenteSelect, addProspectoFuenteSelect.value || '');
    populateSourceSelect(editProspectoFuenteSelect, editProspectoFuenteSelect.value || '');
    populateSourceSelect(prospectFilterSourceSelect, prospectFilterSourceSelect.value || 'all');
}

function renderManageSourcesList() {
    sourcesList.innerHTML = '';
    if (leadSourcesData.length === 0) {
        sourcesList.innerHTML = '<li class="text-gray-500 text-sm">No hay fuentes de leads definidas.</li>';
        return;
    }
    leadSourcesData.forEach(source => {
        const listItem = document.createElement('li');
        listItem.className = 'flex items-center justify-between bg-gray-100 p-3 rounded-lg';
        listItem.innerHTML = `
            <span class="text-gray-800 font-semibold uppercase">${source.name}</span>
            <button type="button" class="text-[var(--color-secondary)] hover:text-[var(--color-secondary)] delete-source-btn" data-id="${source.id}" title="Eliminar Fuente">
                <i data-lucide="trash-2" class="w-5 h-5"></i>
            </button>
        `;
        sourcesList.appendChild(listItem);
    });
    recreateLucideIcons(sourcesList);
    setupDeleteSourceListeners();
}

function setupDeleteSourceListeners() {
    sourcesList.querySelectorAll('.delete-source-btn').forEach(button => {
        button.onclick = null;
        button.addEventListener('click', function() {
            const sourceId = this.dataset.id;
            window.openConfirmDeleteModal(sourceId, 'fuente');
        });
    });
}


// =================================================================
// EVENT LISTENERS E INICIALIZACIÓN
// =================================================================
Object.values(prospectsData).forEach(p => {
    if (!p.mobile) p.mobile = '';
    if (!p.company) p.company = '';
    if (!p.first_name) p.first_name = '';
    if (!p.last_name) p.last_name = '';
});

mobileMenuButton.addEventListener('click', () => {
    sidebar.classList.toggle('-translate-x-full');
    sidebarOverlay.classList.toggle('hidden');
});
sidebarOverlay.addEventListener('click', () => {
    sidebar.classList.add('-translate-x-full');
    sidebarOverlay.classList.add('hidden');
});

const urlParams = new URLSearchParams(window.location.search);
const notificationType = urlParams.get('notification_type');
const notificationMessage = urlParams.get('notification_message');
if (notificationType && notificationMessage) {
    if (typeof showToast === 'function') {
        showToast(notificationMessage, notificationType);
    }
}

if (phoneInput && typeof IMask !== 'undefined') {
    IMask(phoneInput, { mask: '(000) 000-0000' });
}

addProspectoForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const newProspecto = {
        first_name: document.getElementById('prospecto-first-name').value,
        last_name: document.getElementById('prospecto-last-name').value,
        company: document.getElementById('prospecto-empresa-add').value || '',
        email: document.getElementById('prospecto-email').value,
        phone: document.getElementById('prospecto-telefono').value.replace(/\D/g, ''),
        mobile: document.getElementById('prospecto-celular').value.replace(/\D/g, '') || '',
        source: document.getElementById('prospecto-fuente').value,
        priority: document.getElementById('prospecto-prioridad').value,
        status: 'Nuevo',
        street_address: document.getElementById('prospecto-direccion-calle').value || '',
        city: document.getElementById('prospecto-ciudad').value || '',
        state_province: document.getElementById('prospecto-estado-provincia').value || '',
        zip_code: document.getElementById('prospecto-codigo-postal').value || '',
    };

    try {
        const response = await fetch('db/leads-create.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(newProspecto),
        });
        const result = await response.json();
        if (result.success && result.prospect) {
            closePanel('addProspectoPanel');
            addProspectoForm.reset();
            showToast('Prospecto agregado con éxito.', 'success');
            location.reload();
        } else {
            showToast(result.message || 'Error desconocido al agregar prospecto.', 'error');
        }
    } catch (error) {
        showToast('Error de conexión al agregar prospecto.', 'error');
    }
});

editProspectoForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const updatedProspecto = {
        id: document.getElementById('edit-prospecto-id').value,
        first_name: document.getElementById('edit-prospecto-first-name').value || '',
        last_name: document.getElementById('edit-prospecto-last-name').value || '',
        company: document.getElementById('edit-prospecto-empresa').value || '',
        email: document.getElementById('edit-prospecto-email').value || '',
        phone: document.getElementById('edit-prospecto-telefono').value.replace(/\D/g, '') || '',
        mobile: document.getElementById('edit-prospecto-celular').value.replace(/\D/g, '') || '',
        source: document.getElementById('edit-prospecto-fuente').value || '',
        priority: document.getElementById('edit-prospecto-prioridad').value || 'Media', // CAMBIO: Valor por defecto
        status: document.getElementById('edit-prospecto-status').value || '',
        street_address: document.getElementById('edit-prospecto-direccion-calle').value || '',
        city: document.getElementById('edit-prospecto-ciudad').value || '',
        state_province: document.getElementById('edit-prospecto-estado-provincia').value || '',
        zip_code: document.getElementById('edit-prospecto-codigo-postal').value || ''
    };
    try {
        const response = await fetch('db/leads-update.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(updatedProspecto),
        });
        const result = await response.json();
        if (result.success) {
            closePanel('editProspectoPanel');
            showToast('Prospecto actualizado con éxito.', 'success');
            location.reload();
        } else {
            showToast(result.message || 'Error desconocido al actualizar prospecto.', 'error');
        }
    } catch (error) {
        showToast('Error de conexión al actualizar prospecto.', 'error');
    }
});

downloadProspectosBtn.addEventListener('click', () => {
    if (filteredProspects.length === 0) {
        showToast('No hay prospectos para descargar.', 'info');
        return;
    }
    showToast('Preparando descarga de prospectos...', 'info');
    const dataToExport = filteredProspects.map(p => ({
        "Primer Nombre": p.first_name, "Apellido": p.last_name, "Empresa": p.empresa,
        "Email": p.email, "Teléfono Fijo": p.phone, "Celular": p.mobile, "Fuente": p.fuente,
        "Estado": p.estado, "Dirección": p.direccion_calle, "Ciudad": p.ciudad,
        "Estado/Provincia": p.state_province, "Código Postal": p.zip_code, "Fecha de Creación": p.created_at
    }));
    const headers = Object.keys(dataToExport[0]);
    let csv = headers.map(header => `"${header}"`).join(',') + '\n';
    dataToExport.forEach(row => {
        const values = headers.map(header => {
            const value = row[header] !== undefined && row[header] !== null ? String(row[header]) : '';
            return `"${value.replace(/"/g, '""')}"`;
        });
        csv += values.join(',') + '\n';
    });
    const blob = new Blob(["\uFEFF" + csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'prospectos.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        showToast('Descarga de prospectos completada.', 'success');
    }
});

kanbanViewBtn.addEventListener('click', () => {
    currentView = 'kanban';
    kanbanViewBtn.classList.add('active');
    tableViewBtn.classList.remove('active');
    filterAndRenderProspects();
});
tableViewBtn.addEventListener('click', () => {
    currentView = 'table';
    tableViewBtn.classList.add('active');
    kanbanViewBtn.classList.remove('active');
    filterAndRenderProspects();
});

prospectSearchInput.addEventListener('input', filterAndRenderProspects);
prospectFilterStatusSelect.addEventListener('change', filterAndRenderProspects);
prospectFilterSourceSelect.addEventListener('change', filterAndRenderProspects);
monthFilterSelect.addEventListener('change', filterAndRenderProspects);

panelOverlay.addEventListener('click', () => {
    closePanel('addProspectoPanel');
    closePanel('editProspectoPanel');
    closePanel('manageSourcesPanel');
    closeModal('confirmDeleteModal');
    closeModal('confirmConvertModal');
});

if (manageSourcesBtn) {
    manageSourcesBtn.addEventListener('click', () => {
        openPanel('manageSourcesPanel');
        renderManageSourcesList();
    });
}

if (addSourceBtn) {
    addSourceBtn.addEventListener('click', async () => {
        const newSourceName = newSourceNameInput.value.trim();
        if (newSourceName) {
            try {
                const response = await fetch('db/lead-sources-create.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name: newSourceName })
                });
                const result = await response.json();
                if (result.success) {
                    showToast('Fuente de lead agregada con éxito.', 'success');
                    newSourceNameInput.value = '';
                    fetchAndPopulateSources();
                } else {
                    showToast(result.message || 'Error desconocido al agregar fuente.', 'error');
                }
            } catch (error) {
                showToast('Error de conexión al añadir fuente.', 'error');
            }
        } else {
            showToast('El nombre de la fuente no puede estar vacío.', 'warning');
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    fetchAndPopulateSources();
    populateMonthFilter();
    
    
    // --- Llenar el filtro de estado con TODOS los estados ---
    const allStatusSelect = document.getElementById('prospect-filter-status');
    allStatusSelect.innerHTML = '<option value="all">TODOS</option>';
    for(const key in allStatuses) {
        const option = document.createElement('option');
        option.value = key;
        option.textContent = allStatuses[key].title;
        allStatusSelect.appendChild(option);
    }
    // --------------------------------------------------------
    
    filterAndRenderProspects();
    applyPhoneFormatToInputs();
    kanbanViewBtn.classList.add('active');

    if (confirmConvertButton) {
        confirmConvertButton.addEventListener('click', convertToClientLogic);
    }
});
</script>

</body>
</html>