<?php
include 'files/guardiankey.php';

ob_start();
session_start();

error_reporting(0);
ini_set('display_errors', 0);

include_once 'db/db_connection.php';

// --- Lógica PHP para obtener datos de la base de datos ---
$prospects_data_from_db = [];
try {
    $stmt = $pdo->query("SELECT id, first_name, last_name, company, email, phone, mobile, source, status, 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'] ?? '';

        $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'],
            'direccion_calle' => $row['street_address'],
            'ciudad' => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code' => $row['zip_code'],
            'created_at' => $row['created_at']
        ];
    }
} catch (PDOException $e) {
    error_log("Error al cargar prospectos desde la DB en leads.php: " . $e->getMessage());
}

$prospects_json = json_encode($prospects_data_from_db);

ob_end_clean();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Dashboard | Prospectos | OrozDesign Multiemdia</title>
    <meta name="description" content="Administra tus prospectos en LocalCRM: añade, clasifica, realiza seguimiento y convierte oportunidades de forma organizada y eficiente">
    <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>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
</head>
<body data-page-title="Panel De Seguimiento De Prospectos"
      data-page-subtitle="Registra, Califica Y Convierte Contactos En Clientes"
      data-page-icon="users">

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

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>

    <?php include 'menu.php'; ?>

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

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            <section id="prospectos" class="dashboard-section">

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 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-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-primary)]"></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="Descartado">DESCARTADO</option>
                                <option value="Cotizacion enviada">COTIZACIÓN ENVIADA</option>
                                <option value="Seguimiento">SEGUIMIENTO</option>
                                <option value="Recordatorio de seguimiento">RECORDATORIO DE SEGUIMIENTO</option>
                                <option value="Ultimo recordatorio">ÚLTIMO RECORDATORIO</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 DESCARTADOS
                    </h3>
                    <p class="text-gray-500 text-sm mb-4 uppercase">LEADS QUE NO CONTINUARON EN EL PROCESO, 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/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">AGREGAR NUEVO PROSPECTO</h3>
            <button onclick="closePanel('addProspectoPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <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-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 id="editProspectoPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">EDITAR PROSPECTO</h3>
            <button onclick="closePanel('editProspectoPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <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" required>
                </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-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">
                        <option value="Nuevo">NUEVO</option>
                        <option value="Contactado">CONTACTADO</option>
                        <option value="Descartado">DESCARTADO</option>
                        <option value="Cotizacion enviada">COTIZACIÓN ENVIADA</option>
                        <option value="Seguimiento">SEGUIMIENTO</option>
                        <option value="Recordatorio de seguimiento">RECORDATORIO DE SEGUIMIENTO</option>
                        <option value="Ultimo recordatorio">ÚLTIMO RECORDATORIO</option>
                    </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 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="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">GESTIONAR FUENTES</h3>
            <button onclick="closePanel('manageSourcesPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <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 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-red-500"></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>

<script>
    let prospectsData = <?php echo $prospects_json; ?>;
    let leadSourcesData = [];

    // Función auxiliar para forzar la recreación de iconos Lucide
    function recreateLucideIcons(element) {
        if (typeof lucide !== 'undefined' && lucide.createIcons) {
            lucide.createIcons({ container: element });
        }
    }

    Object.values(prospectsData).forEach(p => {
        if (!p.mobile) p.mobile = '';
        if (!p.company) p.company = '';
    });

    let filteredProspects = [];
    let currentMonthFilter = '';

    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 mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    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');

    let currentView = 'kanban';

    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) { showToast(`Error: Panel con ID "${panelId}" no encontrado.`, 'error'); return; }
        panel.classList.remove('translate-x-full');
        panel.classList.add('translate-x-0');
        panelOverlay.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

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

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

    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; // Elimina cualquier listener anterior

        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(); // Recarga la página
                    } 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(); // Recargar fuentes
                    } else {
                        showToast(result.message || 'Error desconocido al eliminar fuente.', 'error');
                        closeModal('confirmDeleteModal');
                    }
                } catch (error) {
                    showToast('Error de conexión al eliminar fuente.', 'error');
                    console.error('Error al comunicarse con la API para eliminar fuente:', error);
                    closeModal('confirmDeleteModal');
                }
            }
        };
        openModal('confirmDeleteModal');
    };

    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() {
        applyInputPhoneFormat(document.getElementById('prospecto-telefono'));
        applyInputPhoneFormat(document.getElementById('prospecto-celular'));
        applyInputPhoneFormat(document.getElementById('edit-prospecto-telefono'));
        applyInputPhoneFormat(document.getElementById('edit-prospecto-celular'));
    }

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

    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();
                if (leadYear < currentYear || (leadYear === currentYear && leadMonth <= currentMonth)) {
                    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) => a - b);

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

        const defaultMonthValue = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}`;
        if (monthFilterSelect.querySelector(`option[value="${defaultMonthValue}"]`)) {
            monthFilterSelect.value = defaultMonthValue;
            currentMonthFilter = defaultMonthValue;
        } else {
            monthFilterSelect.value = 'all';
            currentMonthFilter = 'all';
        }
    }

    const mainStatuses = {
        "Entrante": { title: "ENTRANTE", icon: "inbox", color: "blue-500" },
        "Nuevo": { title: "NUEVO", icon: "sparkles", color: "var(--color-primary)" },
        "Contactado": { title: "CONTACTADO", icon: "phone-call", color: "var(--color-highlight)" }
    };
    const trackingStatuses = {
        "Cotizacion enviada": { title: "COTIZACIÓN ENVIADA", icon: "file-text", color: "#34D399" },
        "Seguimiento": { title: "SEGUIMIENTO", icon: "bell", color: "#FBBF24" },
        "Recordatorio de seguimiento": { title: "RECORDATORIO", icon: "alarm-check", color: "#60A5FA" },
        "Ultimo recordatorio": { title: "ÚLTIMO RECORDATORIO", icon: "alert-triangle", color: "#EF4444" }
    };
    const discardedStatus = {
        "Descartado": { title: "DESCARTADO", icon: "x-circle", color: "var(--color-secondary)" }
    };
    const allStatuses = { ...mainStatuses, ...trackingStatuses, ...discardedStatus };

    function renderMainKanbanBoard(prospects) {
        prospectosKanbanView.innerHTML = '';
        const prospectsForMainBoard = prospects.filter(p => mainStatuses[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); // Recrear iconos después de agregar elementos al DOM

        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 = '';
        const prospectsForTrackingBoard = prospects.filter(p => trackingStatuses[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 = '';
            switch (prospect.estado) {
                case 'Cotizacion enviada': statusClass = 'bg-green-100 text-green-800'; break;
                case 'Seguimiento': statusClass = 'bg-yellow-100 text-yellow-800'; break;
                case 'Recordatorio de seguimiento': statusClass = 'bg-blue-100 text-blue-800'; break;
                case 'Ultimo recordatorio': statusClass = 'bg-red-100 text-red-800'; break;
                default: statusClass = 'bg-gray-100 text-gray-800'; break;
            }

            row.innerHTML = `
                <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE">${prospect.nombre_completo} <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}">
                        ${allStatuses[prospect.estado]?.title || prospect.estado.toUpperCase()}
                    </span>
                </td>
                <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                    <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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-red-500 delete-prospecto-btn" data-id="${prospect.id}" title="Eliminar">
                            <i data-lucide="trash-2" 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'));
        });
    }

    function renderDescartedProspectsTable(prospects) {
        descartadosTableBody.innerHTML = '';
        const prospectsDescartados = prospects.filter(p => p.estado === 'Descartado');

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

        prospectsDescartados.forEach(prospecto => {
            const row = document.createElement('tr');
            row.className = 'border-b border-gray-100 hover:bg-gray-50';
            const statusClass = 'bg-gray-100 text-gray-800';

            row.innerHTML = `
                <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE">${prospecto.nombre_completo} <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}">
                        ${discardedStatus[prospecto.estado]?.title || prospecto.estado.toUpperCase()}
                    </span>
                </td>
                <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                    <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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); // Recrear iconos
            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 || 'N/A';
        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-red-500 hover:bg-red-600 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-red-500 ${iconBtnClasses} rounded-md delete-prospecto-btn" data-id="${prospect.id}" title="Eliminar">
                    <i data-lucide="trash-2" class="w-5 h-5"></i>
                </button>
            `;
        }

        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}">${prospect.nombre_completo}</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}
                </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 sm:flex-row sm:space-y-0'}"> ${actionButtonsHtml}
            </div>
        `;
        
        recreateLucideIcons(card); // Asegurarse de que los iconos de la tarjeta se creen

        const approveButton = card.querySelector('.approve-prospecto-btn'); // CAMBIO DE NOMBRE DE CLASE
        const discardButton = card.querySelector('.discard-prospecto-btn'); // CAMBIO DE NOMBRE DE CLASE
        const editButton = card.querySelector('.edit-prospecto-btn');
        const deleteButton = card.querySelector('.delete-prospecto-btn');
        const toggleDetailsButton = card.querySelector('.toggle-details-btn');
        const cardDetails = card.querySelector('.card-details');

        if (approveButton) {
            approveButton.addEventListener('click', async (e) => { // Async para await
                e.stopPropagation();
                await updateProspectStatus(prospect.id, 'Nuevo'); // Usar await
            });
        }
        if (discardButton) {
            discardButton.addEventListener('click', async (e) => { // Async para await
                e.stopPropagation();
                showToast('Prospecto descartado.', 'info');
                await updateProspectStatus(prospect.id, 'Descartado'); // Actualizar estado a 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 (toggleDetailsButton && cardDetails) {
            toggleDetailsButton.addEventListener('click', (e) => {
                e.stopPropagation();
                cardDetails.classList.toggle('hidden');
                const icon = toggleDetailsButton.querySelector('i');
                icon.setAttribute('data-lucide', cardDetails.classList.contains('hidden') ? 'chevron-down' : 'chevron-up');
                recreateLucideIcons(toggleDetailsButton); // Recrear icono para cambiarlo
            });
            card.querySelector('.card-header').addEventListener('click', (e) => {
                if (!e.target.closest('button')) {
                    toggleDetailsButton.click();
                }
            });
        }
        return card;
    }

    async function updateProspectStatus(prospectId, newStatus) {
        try {
            const response = await fetch('db/leads-update.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(); // Recarga la página
            } else {
                showToast(result.message || 'Error desconocido al actualizar estado del prospecto.', 'error');
                console.error('Error al actualizar estado del prospecto:', result.message);
            }
        } catch (error) {
            showToast('Error de conexión al actualizar estado del prospecto.', 'error');
            console.error('Error de conexión al actualizar estado del prospecto:', error);
        }
    }

    function setupDragAndDrop(containerElement) {
        containerElement.querySelectorAll('.kanban-column').forEach(column => {
            const prospectList = column.querySelector('.space-y-4, .space-y-3');

            if (prospectList) {
                prospectList.addEventListener('dragover', e => {
                    e.preventDefault();
                    prospectList.classList.add('border-2', 'border-dashed', 'border-blue-400');
                    const draggingCard = document.querySelector('.dragging');
                    if (draggingCard) {
                        const afterElement = getDragAfterElement(prospectList, e.clientY);
                        if (afterElement == null) {
                            prospectList.appendChild(draggingCard);
                        } else {
                            prospectList.insertBefore(draggingCard, afterElement);
                        }
                    }
                });
                prospectList.addEventListener('dragleave', () => {
                    prospectList.classList.remove('border-2', 'border-dashed', 'border-blue-400');
                });
                prospectList.addEventListener('drop', async e => { // Convertir a async
                    e.preventDefault();
                    prospectList.classList.remove('border-2', 'border-dashed', 'border-blue-400');
                    const draggingCard = document.querySelector('.dragging');
                    if (draggingCard) {
                        const prospectId = draggingCard.dataset.prospectId;
                        const newStatus = column.dataset.status;

                        if (mainStatuses[newStatus]) {
                            if (prospectsData[prospectId] && prospectsData[prospectId].estado !== newStatus) {
                                await updateProspectStatus(prospectId, newStatus); // Usar await
                            }
                        } else {
                            // En caso de un drop inválido o no manejado por updateProspectStatus, simplemente recargar para consistencia
                            location.reload(); 
                        }
                        draggingCard.classList.remove('dragging');
                    }
                });
            }
        });
        containerElement.addEventListener('dragstart', e => {
            if (e.target.classList.contains('kanban-card')) {
                e.target.classList.add('dragging');
            }
        });
        containerElement.addEventListener('dragend', e => {
            if (e.target.classList.contains('kanban-card')) {
                e.target.classList.remove('dragging');
            }
        });
    }

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

    function renderTable(prospects) {
        prospectsTableBody.innerHTML = '';
        const prospectsForMainTable = prospects.filter(p => !discardedStatus[p.estado] && !trackingStatuses[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 = '';
            if (allStatuses[prospecto.estado]) {
                switch (prospecto.estado) {
                    case 'Nuevo': statusClass = 'bg-blue-100 text-blue-800'; break;
                    case 'Contactado': statusClass = 'bg-yellow-100 text-yellow-800'; break;
                    case 'Descartado': statusClass = 'bg-red-100 text-red-800'; break;
                    case 'Cotizacion enviada': statusClass = 'bg-green-100 text-green-800'; break;
                    case 'Seguimiento': statusClass = 'bg-orange-100 text-orange-800'; break;
                    case 'Recordatorio de seguimiento': statusClass = 'bg-indigo-100 text-indigo-800'; break;
                    case 'Ultimo recordatorio': statusClass = 'bg-pink-100 text-pink-100'; break;
                    case 'Entrante': statusClass = 'bg-blue-100 text-blue-800'; break;
                    default: statusClass = 'bg-gray-100 text-gray-800'; break;
                }
            } else {
                statusClass = 'bg-gray-100 text-gray-800';
            }

            row.innerHTML = `
                <td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE">${prospecto.nombre_completo} <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}">
                        ${prospecto.estado.toUpperCase()}
                    </span>
                </td>
                <td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES">
                    <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm: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>
            `;
            prospectsTableBody.appendChild(row);
            recreateLucideIcons(row); // Recrear iconos
            row.querySelector('.edit-prospecto-btn').addEventListener('click', () => openEditPanel(prospecto.id));
            row.querySelector('.delete-prospecto-btn').addEventListener('click', () => window.openConfirmDeleteModal(prospecto.id, 'prospecto'));
        });
    }

    function updateProspectCounts() {
        totalProspectosCount.textContent = Object.keys(prospectsData).length;
        let currentMonthlyCount = 0;
        const monthFilter = monthFilterSelect.value;
        if (monthFilter === 'all') {
            currentMonthlyCount = filteredProspects.length;    
        } else {
            currentMonthlyCount = filteredProspects.filter(p => {
                if (p.created_at) {
                    const createdAtDate = new Date(p.created_at);
                    const prospectMonthYear = `${createdAtDate.getFullYear()}-${String(createdAtDate.getMonth() + 1).padStart(2, '0')}`;
                    return prospectMonthYear === monthFilter;
                }
                return false;
            }).length;
        }
        monthlyProspectosCount.textContent = currentMonthlyCount;
    }

    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));
            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();

        if (currentView === 'kanban') {
            prospectosKanbanView.classList.remove('hidden');
            document.getElementById('seguimiento-table-view').classList.remove('hidden');    
            prospectosTableView.classList.add('hidden');
            document.getElementById('descartados-table-view').classList.remove('hidden');
            renderMainKanbanBoard(filteredProspects);
            renderSeguimientoTable(filteredProspects);    
            renderDescartedProspectsTable(filteredProspects);
        } else {
            prospectosKanbanView.classList.add('hidden');
            document.getElementById('seguimiento-table-view').classList.remove('hidden');    
            prospectosTableView.classList.remove('hidden');
            document.getElementById('descartados-table-view').classList.remove('hidden');
            renderTable(filteredProspects);
            renderSeguimientoTable(filteredProspects);    
            renderDescartedProspectsTable(filteredProspects);
        }
    }

    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,
            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(); // Recarga la página
            } else {
                showToast(result.message || 'Error desconocido al agregar prospecto.', 'error');
            }
        } catch (error) {
            showToast('Error de conexión al agregar prospecto.', 'error');
            console.error('Error:', error);
        }
    });

    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 || '';
            document.getElementById('edit-prospecto-fuente').value = 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 || '';
            
            const statusSelect = document.getElementById('edit-prospecto-status');
            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; // Establecer el valor después de llenar las opciones
            
            openPanel('editProspectoPanel');
            applyPhoneFormatToInputs();    
        } else {
            showToast('Prospecto no encontrado para editar.', '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,
            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(); // Recarga la página
            } else {
                showToast(result.message || 'Error desconocido al actualizar prospecto.', 'error');
                console.error(result.message);
            }
        } catch (error) {
            showToast('Error de conexión al actualizar prospecto.', 'error');
            console.error('Error:', 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);

    if (mobileMenuButton) mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });
    if (sidebarOverlay) sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });
    panelOverlay.addEventListener('click', () => {
        closePanel('addProspectoPanel');
        closePanel('editProspectoPanel');
        closePanel('manageSourcesPanel');
        closeModal('confirmDeleteModal');
    });

    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');
                console.error('Error al cargar fuentes de leads:', result.message);
            }
        } catch (error) {
            showToast('Error de conexión al cargar fuentes de leads.', 'error');
            console.error('Error de conexión al cargar fuentes de leads:', error);
        }
    }

    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);
        }
        leadSourcesData.forEach(source => {
            const option = document.createElement('option');
            option.value = source.name;
            option.textContent = source.name.toUpperCase();
            selectElement.appendChild(option);
        });
        selectElement.value = selectedValue;
        if (selectElement.value !== selectedValue && selectElement.options.length > 0) {
            selectElement.value = selectElement.options[0].value;
        }
    }

    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-red-500 hover:text-red-700 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); // Recrear iconos
        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');
            });
        });
    }

    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');
                    console.error('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();      
        filterAndRenderProspects();      
        applyPhoneFormatToInputs();
        kanbanViewBtn.classList.add('active');
    });
</script>

</body>
</html>