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

$prospects_data_from_db = [];
$services_data_from_db = []; 
$source_counts = [];
$most_frequent_source = ['name' => 'N/A', 'count' => 0];

// Variable para el estado por defecto (Geo)
$default_geo_state = $client_info['state_region'] ?? ''; 

try {
    // 1. OBTENER SERVICIOS
    $stmtServices = $pdo->prepare("SELECT id, name FROM services ORDER BY name ASC");
    $stmtServices->execute();
    $services_data_from_db = $stmtServices->fetchAll(PDO::FETCH_ASSOC);

    // 2. Lógica para obtener prospectos
    // CRMSA: Se permite cargar leads con cualquier estado para gestionar la papelera
    
    $columnCheck = $pdo->query("SHOW COLUMNS FROM leads LIKE 'service_id'");
    $hasServiceCol = $columnCheck->fetch() !== false;

    $select_fields = "id, first_name, last_name, company, email, phone, mobile, source, status, priority, street_address, city, state_province, zip_code, created_at";
    if ($hasServiceCol) {
        $select_fields .= ", service_id";
    }

    $sql = "
        SELECT $select_fields
        FROM leads  
        WHERE status IS NOT NULL  
        ORDER BY created_at DESC  
        LIMIT 2500
    "; 

    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Mapeo y limpieza de datos
    $status_mapping_fix = [
        'Cotización Ganada' => 'Lead Ganado',
        'Cotización Perdida' => 'Lead Perdido',
        'Cotización Solicitada' => 'En Seguimiento',
        'Cotización Enviada' => 'En Seguimiento',
        'Seguimiento Post Envío' => 'En Seguimiento',
        'Seguimiento Recordatorio' => 'En Seguimiento',
        'Negociación Final' => 'En Seguimiento',
        'Descartado' => 'Rechazados',
        'Lead Archivado' => 'Rechazados', // CRMSA: Mapeo clave
    ];
    
    foreach ($db_prospects_rows as $row) {
        $raw_status = $row['status'] ?? 'Nuevo';
        $clean_status = $status_mapping_fix[$raw_status] ?? trim(html_entity_decode($raw_status, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
        $email = $row['email'] === 'null' || $row['email'] === null ? '' : $row['email'];
        $company_name = $row['company'] ?? '';

        if ($company_name === 'null' || empty(trim($company_name)) || strtoupper(trim($company_name)) === 'RESIDENCIAL') {
            $company_name = '';
        } else {
            $company_name = trim($company_name);
        }

        $prospects_data_from_db[$row['id']] = [
            'id' => $row['id'],
            'first_name' => $row['first_name'],
            'last_name' => $row['last_name'],
            'nombre_completo' => trim($row['first_name'] . ' ' . $row['last_name']),
            'empresa' => $company_name,
            'email' => $email,
            'phone' => $row['phone'] ?? '',
            'mobile' => $row['mobile'] ?? '',
            'fuente' => $row['source'] ?? 'Desconocido',
            'estado' => $clean_status,
            'prioridad' => $row['priority'] ?? 'Media',
            'direccion_calle' => $row['street_address'] ?? '',
            'ciudad' => $row['city'] ?? '',
            'state_province' => $row['state_province'] ?? '',
            'zip_code' => $row['zip_code'] ?? '',
            'service_id' => $hasServiceCol ? ($row['service_id'] ?? '') : '',
            'created_at' => $row['created_at']
        ];
        
        if (!empty($row['source'])) {
            $source_counts[$row['source']] = ($source_counts[$row['source']] ?? 0) + 1;
        }
    }

    if (!empty($source_counts)) {
        arsort($source_counts);
        $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];
    }

} catch (PDOException $e) {
    $prospects_data_from_db = [];
    error_log("Error PDO: " . $e->getMessage());
} catch (Exception $e) {
    $prospects_data_from_db = [];
    error_log("Error General: " . $e->getMessage());
}

$prospects_json = json_encode($prospects_data_from_db, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$services_json = json_encode($services_data_from_db, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

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

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
</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="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
        
        <?php include 'menu.php'; ?>
        
        <main class="flex-1 overflow-y-auto bg-[var(--color-background)]">
            <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">
                
                <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-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="users" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                        <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                            <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">TOTAL PROSPECTOS</h3>
                            <p id="total-prospectos-count" class="text-5xl font-black text-[var(--color-primary)]"><?php echo count($prospects_data_from_db); ?></p>
                        </div>
                    </div>
                    
                    <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="zap" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                        <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                            <p class="text-3xl lg:text-4xl font-black text-[var(--color-primary)] uppercase leading-none truncate"><?php echo htmlspecialchars($most_frequent_source['name']); ?></p>
                        </div>
                    </div>

                    <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                        <i data-lucide="user-plus" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                        <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                            <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">PROSPECTOS ESTE MES</h3>
                            <p id="monthly-prospectos-count" class="text-5xl font-black text-[var(--color-primary)]">0</p>
                        </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-black text-[var(--color-primary)] flex items-center justify-center gap-2 uppercase">
                                <i data-lucide="trending-up" class="w-7 h-7 text-[var(--color-secondary)]"></i> FLUJO DE CONVERSIÓN
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase font-bold">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 shrink-0">
                                <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="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all hover:-translate-y-0.5" onclick="openPanel('addProspectoPanel')">
                                <i data-lucide="plus" class="w-5 h-5"></i> AGREGAR PROSPECTO
                            </button>
                            
                            <button id="manage-sources-btn" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all hover:-translate-y-0.5" onclick="openPanel('manageSourcesPanel')">
                                <i data-lucide="settings" class="w-4 h-4"></i> GESTIONAR FUENTES
                            </button>
                            
                            <button id="download-prospectos-btn" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all hover:-translate-y-0.5">
                                <i data-lucide="download" class="w-4 h-4"></i> DESCARGAR
                            </button>
                            
                            <div class="mt-2 flex items-center w-full md:w-auto">
                                <select id="month-filter-select" class="w-full p-2.5 border border-gray-300 rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] font-bold uppercase text-gray-600">
                                </select>
                            </div>
                        </div>

                        <div class="flex flex-col md:flex-row justify-between items-center gap-4 w-full mt-4">
                            <div class="relative flex-grow w-full">
                                <input type="text" id="prospect-search" placeholder="BUSCAR PROSPECTO 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)] text-sm uppercase font-semibold">
                                <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 text-sm uppercase font-bold text-gray-600">
                                <option value="all">TODAS LAS ETAPAS</option>
                                <option value="Entrante">ENTRANTE</option>
                                <option value="Nuevo">NUEVO</option>
                                <option value="Contactado">CONTACTADO</option>
                                <option value="En Seguimiento">EN SEGUIMIENTO</option>
                                <option value="Presentar Solución">PRESENTAR SOLUCIÓN</option>
                                <option value="Introducir Servicio">INTRODUCIR SERVICIO</option>
                                <option value="Lead Ganado">LEAD GANADO</option>
                                <option value="Lead Perdido">LEAD PERDIDO</option>
                                <option value="Rechazados">RECHAZADOS</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 text-sm uppercase font-bold text-gray-600">
                                <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">
                            <thead class="bg-gray-50 hidden md:table-header-group">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-black tracking-wider">NOMBRE</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-black tracking-wider">ETAPA</th>
                                    <th class="py-3 px-6 font-black tracking-wider text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="prospectsTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-2xl font-black text-[var(--color-primary)] flex items-center gap-2 uppercase mb-4">
                        <i data-lucide="inbox" class="w-6 h-6 text-[var(--color-secondary)]"></i> Leads Entrantes
                    </h3>
                    <div id="kanban-container" class="grid grid-cols-1 md:grid-cols-3 gap-6 min-h-[200px]"></div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-2xl font-black text-[var(--color-primary)] flex items-center gap-2 uppercase mb-4">
                        <i data-lucide="search-check" class="w-6 h-6 text-[var(--color-secondary)]"></i> Prospectos En Seguimiento (Oportunidad)
                    </h3>
                    <p class="text-xs text-gray-500 uppercase mb-4 font-bold">Fase de Evaluación, Presentación y Negociación de la Solución.</p>
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm text-left">
                            <thead class="bg-gray-50 hidden md:table-header-group">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-black tracking-wider">NOMBRE</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-black tracking-wider">ETAPA</th>
                                    <th class="py-3 px-6 font-black tracking-wider text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody id="table-tracking-body"></tbody>
                        </table>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-lg font-black text-gray-500 mb-4 uppercase flex items-center gap-2">
                            <i data-lucide="bar-chart-3" class="w-5 h-5 text-[var(--color-secondary)]"></i>
                            Captación Mensual de Leads
                        </h3>
                        <div class="relative h-64 w-full">
                            <canvas id="monthlyLeadsChart"></canvas>
                        </div>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-lg font-black text-gray-500 mb-4 uppercase flex items-center gap-2">
                            <i data-lucide="pie-chart" class="w-5 h-5 text-[var(--color-secondary)]"></i>
                            Conversión: Leads vs Clientes
                        </h3>
                        <div class="relative h-64 w-full flex justify-center">
                            <canvas id="conversionChart"></canvas>
                        </div>
                        <div class="mt-4 flex justify-around text-center border-t border-gray-100 pt-4">
                            <div>
                                <span class="block text-xs text-gray-400 uppercase font-bold">Total Leads</span>
                                <span class="text-xl font-black text-gray-700" id="stat-total-leads">0</span>
                            </div>
                            <div>
                                <span class="block text-xs text-gray-400 uppercase font-bold">Clientes Ganados</span>
                                <span class="text-xl font-black text-green-600" id="stat-total-clients">0</span>
                            </div>
                            <div>
                                <span class="block text-xs text-gray-400 uppercase font-bold">Tasa Conv.</span>
                                <span class="text-xl font-black text-[var(--color-primary)]" id="stat-conversion-rate">0%</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-2xl font-black text-[var(--color-primary)] flex items-center gap-2 uppercase mb-4">
                        <i data-lucide="trash-2" class="w-7 h-7 text-[var(--color-secondary)]"></i> PROSPECTOS RECHAZADOS
                    </h3>
                    <p class="text-gray-500 text-sm mb-4 uppercase font-bold">PROSPECTOS DESCARTADOS CATEGORIZADOS COMO SPAM</p>
                    <div id="descartados-table-view" class="overflow-x-auto">
                        <table class="min-w-full bg-white">
                            <thead class="bg-gray-50 hidden md:table-header-group">
                                <tr class="text-left text-gray-500 uppercase text-sm">
                                    <th class="py-3 px-6 font-black tracking-wider">NOMBRE</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden md:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-black tracking-wider hidden lg:table-cell">EMAIL</th>
                                    <th class="py-3 px-6 font-black tracking-wider">ETAPA</th>
                                    <th class="py-3 px-6 font-black tracking-wider text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" id="descartadosTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
        </main>
    </div>

    <div id="addProspectoPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
        <div class="flex flex-col h-full">
            <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
                <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase leading-none">
                    <i data-lucide="clipboard-list" class="w-8 h-8 mr-2 text-white"></i>
                    NUEVO PROSPECTO
                </h3>
                <button onclick="closeAllPanels()" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                    <i data-lucide="x" class="w-8 h-8"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
                <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                    <form id="add-prospecto-form" class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="prospecto-first-name" class="block text-xs font-bold text-gray-600 mb-1 uppercase">Primer Nombre</label>
                                <input type="text" name="first_name" id="prospecto-first-name" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Primer Nombre" required>
                            </div>
                            <div>
                                <label for="prospecto-last-name" class="block text-xs font-bold text-gray-600 mb-1 uppercase">Apellido</label>
                                <input type="text" name="last_name" id="prospecto-last-name" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Apellido" required>
                            </div>
                        </div>
                        <div>
                            <label for="prospecto-empresa-add" class="block text-xs font-bold text-gray-600 mb-1 uppercase">EMPRESA (Opcional)</label>
                            <input type="text" name="company" id="prospecto-empresa-add" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Nombre Del Negocio">
                        </div>
                        <div>
                            <label for="prospecto-email" class="block text-xs font-bold text-gray-600 mb-1 uppercase">EMAIL</label>
                            <input type="email" name="email" id="prospecto-email" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="email@paginaweb.com" required>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="prospecto-telefono" class="block text-xs font-bold text-gray-600 mb-1 uppercase">TELÉFONO FIJO</label>
                                <input type="tel" name="phone" id="prospecto-telefono" class="phone-mask w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="(XXX) XXX-XXXX">
                            </div>
                            <div>
                                <label for="prospecto-celular" class="block text-xs font-bold text-gray-600 mb-1 uppercase">CELULAR</label>
                                <input type="tel" name="mobile" id="prospecto-celular" class="phone-mask w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="(XXX) XXX-XXXX">
                            </div>
                        </div>
                        <div>
                            <label for="prospecto-servicio" class="block text-xs font-bold text-gray-600 mb-1 uppercase">SERVICIO DE INTERÉS</label>
                            <select name="service_id" id="prospecto-servicio" class="service-selector w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                                <option value="">-- SELECCIONAR SERVICIO --</option>
                            </select>
                        </div>
                        <div>
                            <label for="prospecto-fuente" class="block text-xs font-bold text-gray-600 mb-1 uppercase">FUENTE</label>
                            <select name="source" id="prospecto-fuente" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                            </select>
                        </div>
                        <div>
                            <label for="prospecto-prioridad" class="block text-xs font-bold text-gray-600 mb-1 uppercase">PRIORIDAD</label>
                            <select name="priority" id="prospecto-prioridad" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                                <option value="Alta">ALTA</option>
                                <option value="Media" selected>MEDIA</option>
                                <option value="Baja">BAJA</option>
                            </select>
                        </div>
                        <div class="border-t pt-4 mt-2">
                            <label for="prospecto-direccion-calle" class="block text-xs font-bold text-gray-600 mb-1 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                            <input type="text" name="street_address" id="prospecto-direccion-calle" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. 123 Main St">
                        </div>
                        <div class="grid grid-cols-3 gap-3">
                            <div>
                                <label for="prospecto-ciudad" class="block text-xs font-bold text-gray-600 mb-1 uppercase">CIUDAD</label>
                                <input type="text" name="city" id="prospecto-ciudad" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. Springfield">
                            </div>
                            <div>
                                <label for="prospecto-estado-provincia" class="block text-xs font-bold text-gray-600 mb-1 uppercase">ESTADO</label> 
                                <input type="text" name="state_province" id="prospecto-estado-provincia" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. IL">
                            </div>
                            <div>
                                <label for="prospecto-codigo-postal" class="block text-xs font-bold text-gray-600 mb-1 uppercase">ZIP CODE</label>
                                <input type="text" name="zip_code" id="prospecto-codigo-postal" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. 62704">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
                <div class="grid grid-cols-2 gap-3">
                    <button type="button" onclick="closeAllPanels()" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                    </button>
                    <button type="submit" form="add-prospecto-form" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div id="editProspectoPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
        <div class="flex flex-col h-full">
            <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
                <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase leading-none">
                    <i data-lucide="clipboard-pen" class="w-8 h-8 mr-2 text-white"></i>
                    EDITAR PROSPECTO
                </h3>
                <button onclick="closeAllPanels()" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                    <i data-lucide="x" class="w-8 h-8"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
                <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                    <form id="edit-prospecto-form" class="space-y-4">
                        <input type="hidden" name="id" id="edit-prospecto-id">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="edit-prospecto-first-name" class="block text-xs font-bold text-gray-600 mb-1 uppercase">Primer Nombre</label>
                                <input type="text" name="first_name" id="edit-prospecto-first-name" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="PrimerNombre" required>
                            </div>
                            <div>
                                <label for="edit-prospecto-last-name" class="block text-xs font-bold text-gray-600 mb-1 uppercase">Apellido</label>
                                <input type="text" name="last_name" id="edit-prospecto-last-name" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Apellido" required>
                            </div>
                        </div>
                        <div>
                            <label for="edit-prospecto-empresa" class="block text-xs font-bold text-gray-600 mb-1 uppercase">EMPRESA (Opcional)</label>
                            <input type="text" name="company" id="edit-prospecto-empresa" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Nombre Del Negocio">
                        </div>
                        <div>
                            <label for="edit-prospecto-email" class="block text-xs font-bold text-gray-600 mb-1 uppercase">EMAIL</label>
                            <input type="email" name="email" id="edit-prospecto-email" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="email@paginaweb.com">
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label for="edit-prospecto-telefono" class="block text-xs font-bold text-gray-600 mb-1 uppercase">TELÉFONO FIJO</label>
                                <input type="tel" name="phone" id="edit-prospecto-telefono" class="phone-mask w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="(XXX) XXX-XXXX">
                            </div>
                            <div>
                                <label for="edit-prospecto-celular" class="block text-xs font-bold text-gray-600 mb-1 uppercase">CELULAR</label>
                                <input type="tel" name="mobile" id="edit-prospecto-celular" class="phone-mask w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="(XXX) XXX-XXXX">
                            </div>
                        </div>
                        <div>
                            <label for="edit-prospecto-servicio" class="block text-xs font-bold text-gray-600 mb-1 uppercase">SERVICIO DE INTERÉS</label>
                            <select name="service_id" id="edit-prospecto-servicio" class="service-selector w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                                <option value="">-- SELECCIONAR SERVICIO --</option>
                            </select>
                        </div>
                        <div>
                            <label for="edit-prospecto-fuente" class="block text-xs font-bold text-gray-600 mb-1 uppercase">FUENTE</label>
                            <select name="source" id="edit-prospecto-fuente" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                            </select>
                        </div>
                        <div class="border-t pt-4 mt-2">
                            <label for="edit-prospecto-direccion-calle" class="block text-xs font-bold text-gray-600 mb-1 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                            <input type="text" name="street_address" id="edit-prospecto-direccion-calle" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. 123 Main St">
                        </div>
                        <div class="grid grid-cols-3 gap-3">
                            <div>
                                <label for="edit-prospecto-ciudad" class="block text-xs font-bold text-gray-600 mb-1 uppercase">CIUDAD</label>
                                <input type="text" name="city" id="edit-prospecto-ciudad" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. Springfield">
                            </div>
                            <div>
                                <label for="edit-prospecto-estado-provincia" class="block text-xs font-bold text-gray-600 mb-1 uppercase">ESTADO</label> 
                                <input type="text" name="state_province" id="edit-prospecto-estado-provincia" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. IL">
                            </div>
                            <div>
                                <label for="edit-prospecto-codigo-postal" class="block text-xs font-bold text-gray-600 mb-1 uppercase">ZIP CODE</label>
                                <input type="text" name="zip_code" id="edit-prospecto-codigo-postal" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Ej. 62704">
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-4 border-t pt-4 mt-2">
                            <div>
                                <label for="edit-prospecto-prioridad" class="block text-xs font-bold text-gray-600 mb-1 uppercase">PRIORIDAD</label>
                                <select name="priority" id="edit-prospecto-prioridad" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm bg-white">
                                    <option value="Alta">ALTA</option>
                                    <option value="Media">MEDIA</option>
                                    <option value="Baja">BAJA</option>
                                </select>
                            </div>
                            <div>
                                <label for="edit-prospecto-status" class="block text-xs font-bold text-gray-600 mb-1 uppercase">ETAPA</label>
                                <select name="status" id="edit-prospecto-status" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm uppercase bg-white">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
                <div class="grid grid-cols-2 gap-3">
                    <button type="button" onclick="closeAllPanels()" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                    </button>
                    <button type="submit" form="edit-prospecto-form" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="save" class="w-5 h-5"></i> ACTUALIZAR
                    </button>
                </div>
                <div class="mt-4 text-xs text-center text-gray-500 font-bold uppercase">ID del Prospecto: <span id="edit-prospecto-display-id" class="text-gray-700"></span></div>
            </div>
        </div>
    </div>

    <div id="manageSourcesPanel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
        <div class="flex flex-col h-full">
            <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
                <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase leading-none">
                    <i data-lucide="folder-search" class="w-8 h-8 mr-2 text-white"></i>
                    GESTIONAR FUENTES
                </h3>
                <button onclick="closeAllPanels()" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
                    <i data-lucide="x" class="w-8 h-8"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
                <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                    <div class="space-y-6">
                        <div>
                            <h4 class="text-md font-bold text-gray-600 mb-2 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 w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm">
                                <button id="add-source-btn" class="bg-[var(--color-primary)] hover:bg-[var(--color-highlight)] text-white font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase transition duration-200 shadow-md">
                                    <i data-lucide="plus" class="w-5 h-5"></i>
                                </button>
                            </div>
                        </div>
                        <div class="border-t pt-4">
                            <h4 class="text-md font-bold text-gray-600 mb-3 uppercase">Fuentes Existentes</h4>
                            <ul id="sources-list" class="space-y-2 border border-gray-200 rounded-lg p-2 max-h-60 overflow-y-auto bg-gray-50">
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
                <button type="button" class="bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase w-full flex items-center justify-center gap-2" onclick="closeAllPanels()">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR
                </button>
            </div>
        </div>
    </div>

    <div id="confirmDeleteModal" 
         class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
         onclick="if(event.target === this) closeModal('confirmDeleteModal')">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center overflow-hidden">
            <div class="p-4 bg-[var(--color-primary)] border-b border-gray-200 shadow z-20 flex justify-center">
                <h3 class="text-2xl font-black text-[var(--color-highlight)] uppercase leading-none modal-primary-title">ADVERTENCIA</h3>
            </div>
            <div class="p-8">
                <div class="flex justify-center mb-6">
                    <i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
                </div>
                <p class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                    ¿ESTÁS SEGURO DE ELIMINAR A <span id="delete-item-name" class="font-black text-[var(--color-secondary)] text-xl block mt-2">NOMBRE DEL LEAD</span>?
                </p>
                <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
                    <button type="button" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" onclick="closeModal('confirmDeleteModal')">
                        <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                    </button>
                    <button type="button" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" id="confirm-delete-button">
                        <i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR
                    </button>
                </div>
                <p class="mt-6 uppercase text-xs font-black text-gray-500 tracking-wider"> 
                    ESTA ACCIÓN NO SE PUEDE DESHACER
                </p>
            </div>
        </div>
    </div>

    <div id="confirmConvertModal" 
         class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-50"
         onclick="if(event.target === this) closeModal('confirmConvertModal')">
        <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center overflow-hidden">
            <div class="p-4 bg-[var(--color-primary)] border-b border-gray-200 shadow z-20 flex justify-center">
                <h3 class="text-2xl font-black text-[var(--color-highlight)] uppercase leading-none">ADVERTENCIA</h3>
            </div>
            <div class="p-8">
                <div class="flex justify-center mb-6">
                    <i data-lucide="user-check" class="w-16 h-16 text-green-600"></i>
                </div>
                <p class="text-[var(--color-primary)] mb-2 uppercase text-lg font-bold leading-tight">
                    ¿CONVERTIR A <span id="convert-item-name" class="font-black text-[var(--color-secondary)] text-xl block mt-2">NOMBRE DEL LEAD</span> EN CLIENTE?
                </p>
                <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
                    <button type="button" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" onclick="closeModal('confirmConvertModal')">
                        <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                    </button>
                    <button type="button" class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2" id="confirm-convert-button">
                        <i data-lucide="check-circle-2" class="w-5 h-5"></i> CONVERTIR
                    </button>
                </div>
                <p class="mt-6 uppercase text-xs font-black text-gray-500 tracking-wider"> 
                    SE MOVERÁ AL CENTRO DE CLIENTES
                </p>
            </div>
        </div>
    </div>

<script>
// --- CONFIGURACIÓN GLOBAL UNIFICADA (CRMSA) ---
const API_ENDPOINTS = {
    CREATE:       'db/leads-create.php',
    UPDATE:       'db/leads-update.php',
    UPDATE_STATUS:'db/leads-update-status.php',
    DELETE:       'db/leads-delete.php',
    SOURCES_READ: 'db/lead-sources-read.php',
    SOURCES_ADD:  'db/lead-sources-create.php',
    SOURCES_DEL:  'db/lead-sources-delete.php'
};

const prospectsData = <?php echo $prospects_json; ?>;
const servicesData = <?php echo $services_json; ?>; 
const defaultStateFromDB = "<?php echo htmlspecialchars($default_geo_state, ENT_QUOTES, 'UTF-8'); ?>";

let prospectArray = Object.values(prospectsData);
let filteredProspects = [...prospectArray];

const STATUS_MAP = {
    'Entrante': 'kanban', 
    'Nuevo': 'kanban', 
    'Contactado': 'kanban',
    'En Seguimiento': 'tracking',
    'Presentar Solución': 'tracking',
    'Introducir Servicio': 'tracking',
    'Lead Ganado': 'won', 
    'Lead Perdido': 'lost', 
    'Rechazados': 'rejected',
    'Lead Archivado': 'rejected'
};

const KANBAN_COLS = {
    'Entrante': { color: 'border-red-500', title: 'LEAD ENTRANTE', icon: 'bell-ring' },
    'Nuevo': { color: 'border-blue-500', title: 'APROBADO', icon: 'check-square' },
    'Contactado': { color: 'border-green-500', title: 'PRIMER CONTACTO', icon: 'phone-call' }
};

document.addEventListener('DOMContentLoaded', () => {
    setupMonthFilter();
    setupServices(); 
    renderAll();
    updateStats();
    setupSources();
    setupListeners();
    lucide.createIcons();
    document.querySelectorAll('.phone-mask').forEach(el => IMask(el, {mask: '(000) 000-0000'}));
    initCharts();
});

// --- RENDERIZADO ---
function renderAll() {
    const kanbanWrapper = document.getElementById('kanban-container'); 
    
    // Limpieza
    if(kanbanWrapper) kanbanWrapper.innerHTML = ''; 

    // Columnas Kanban
    for(const [key, conf] of Object.entries(KANBAN_COLS)) {
        const col = document.createElement('div');
        col.className = `bg-gray-50 p-4 rounded-xl shadow-inner border-t-4 ${conf.color} kanban-column`;
        col.dataset.status = key;
        col.innerHTML = `
            <h4 class="text-3xl font-black text-gray-700 mb-4 flex items-center gap-2 uppercase"><i data-lucide="${conf.icon}" class="w-5 h-5"></i> ${conf.title}</h4>
            <div id="list-${key}" class="space-y-3 min-h-[100px] kanban-list" data-status-list="${key}"></div>
        `;
        if(kanbanWrapper) kanbanWrapper.appendChild(col);
    }

    const tTracking = document.getElementById('table-tracking-body');
    const tRejected = document.getElementById('descartadosTableBody'); // Tabla rechazada
    const tAll = document.getElementById('prospectsTableBody'); 

    if(tTracking) tTracking.innerHTML = ''; 
    if(tRejected) tRejected.innerHTML = '';
    if(tAll) tAll.innerHTML = '';

    const kanbanFragments = {};
    for (const key in KANBAN_COLS) { kanbanFragments[key] = document.createDocumentFragment(); }

    filteredProspects.forEach(p => {
        // Normalización de estado visual
        let displayStatus = p.estado;
        if(p.estado === 'Lead Archivado') displayStatus = 'Rechazados';

        const type = STATUS_MAP[displayStatus] || 'tracking'; 
        const badge = getPriorityBadge(p.prioridad);
        const rawPhone = p.phone || p.mobile || '';
        const phone = rawPhone ? formatUSAPhone(rawPhone) : '---';
        
        // Tabla General
        if(tAll) tAll.appendChild(createTableRow(p, badge, phone, type));
        
        // Distribución
        if (type === 'kanban' && kanbanFragments[displayStatus]) {
            kanbanFragments[displayStatus].appendChild(createKanbanCard(p, badge, phone));
        } else {
            const row = createTableRow(p, badge, phone, type);
            if(type === 'rejected' && tRejected) {
                tRejected.appendChild(row);
            } else if((type === 'tracking' || type === 'won' || type === 'lost') && tTracking) {
                tTracking.appendChild(row);
            }
        }
    });

    for (const key in kanbanFragments) {
        const list = document.getElementById(`list-${key}`);
        if(list) list.appendChild(kanbanFragments[key]);
    }

    setupDragAndDrop();
    lucide.createIcons();
}

// AQUÍ ESTÁN LAS MODIFICACIONES DE DISEÑO COMPRIMIDO Y BOTONES
function createKanbanCard(p, badge, phone) {
    const el = document.createElement('div');
    // REDUJE PADDING DE p-4 A p-3 PARA COMPRIMIR
    el.className = 'kanban-card bg-white p-3 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-all cursor-grab';
    el.setAttribute('draggable', true);
    el.dataset.prospectId = p.id;

    let btns = '';
    
    // LÓGICA DE BOTONES PARA LEAD ENTRANTE (Rechazar en lugar de Eliminar)
    if(p.estado === 'Entrante') {
        btns = `
        <div class="grid grid-cols-2 gap-2 mt-2 pt-2 border-t border-gray-100">
            <button onclick="updateStatus(${p.id}, 'Rechazados')" class="flex items-center justify-center gap-1 text-[10px] font-bold uppercase text-red-600 bg-red-50 hover:bg-red-100 py-1.5 px-2 rounded transition-colors">
                <i data-lucide="x-circle" class="w-3 h-3"></i> Rechazar
            </button>
            <button onclick="updateStatus(${p.id}, 'Nuevo')" class="flex items-center justify-center gap-1 text-[10px] font-bold uppercase text-white bg-[var(--color-secondary)] hover:opacity-90 py-1.5 px-2 rounded transition-colors">
                <i data-lucide="check" class="w-3 h-3"></i> Aprobar
            </button>
        </div>`;
    } else {
        // Botones normales (Editar / Borrar con Modal)
        btns = `
        <div class="flex justify-end gap-2 mt-2 pt-2 border-t border-gray-100">
            <button onclick="openEdit(${p.id})" class="text-gray-400 hover:text-blue-600"><i data-lucide="edit" class="w-4 h-4"></i></button>
            <button onclick="openDelete(${p.id})" class="text-gray-400 hover:text-red-600"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
        </div>`;
    }
    
    const companyDisplay = p.empresa || 'RESIDENCIAL'; 
    const serviceName = p.service_id ? (servicesData.find(s => s.id == p.service_id)?.name || '') : '';
    // FIX DE SPAM LINES: Si no hay servicio, no mostramos el badge vacío
    const serviceBadge = (serviceName && serviceName !== '-') ? `<div class="mb-1"><span class="bg-blue-50 text-blue-700 text-[10px] px-1.5 py-0.5 rounded border border-blue-100 font-bold uppercase inline-block truncate max-w-full">${serviceName}</span></div>` : '';

    // HTML COMPRIMIDO (Márgenes reducidos mb-1)
    el.innerHTML = `
        <div class="flex justify-between items-start mb-1 pointer-events-none">
            <h5 class="font-bold text-gray-800 text-sm leading-tight truncate pr-2" title="${p.nombre_completo}">${p.nombre_completo}</h5>
            ${badge}
        </div>
        <p class="text-[10px] text-gray-500 font-bold mb-1 uppercase tracking-wide pointer-events-none truncate">${companyDisplay}</p>
        ${serviceBadge}
        <div class="text-xs text-gray-600 space-y-0.5 pointer-events-none">
            <div class="flex items-center truncate"><i data-lucide="phone" class="w-3 h-3 mr-1 text-gray-400"></i> ${phone}</div>
            <div class="flex items-center truncate"><i data-lucide="tag" class="w-3 h-3 mr-1 text-gray-400"></i> ${p.fuente || 'N/A'}</div>
        </div>
        ${btns}
    `;
    return el;
}

function createTableRow(p, badge, phone, type) {
    const tr = document.createElement('tr');
    tr.className = "flex flex-col md:table-row bg-white mb-4 md:mb-0 shadow-sm md:shadow-none rounded-xl md:rounded-none border border-gray-200 md:border-b md:border-x-0 md:border-t-0 hover:bg-gray-50 p-4 md:p-0 transition-colors";
    
    const statusClass = getStatusColorClass(p.estado);
    const emailDisplay = (p.email && p.email !== 'null' && p.email.trim() !== '') 
        ? `<div class="text-sm text-gray-500 truncate max-w-[200px] lg:max-w-[300px]" title="${p.email}">${p.email}</div>` 
        : `<span class="text-xs text-gray-400 italic">Sin Correo Electrónico</span>`;

    let actionsBtn = '';

    // CRMSA: BOTONES ESPECÍFICOS PARA RECHAZADOS (Restaurar y Borrar Definitivamente)
    if (type === 'rejected') {
        actionsBtn = `
            <div class="flex justify-end gap-2">
                <button onclick="updateStatus(${p.id}, 'Nuevo')" class="bg-green-100 text-green-700 hover:bg-green-200 p-2 rounded-lg flex items-center gap-1 font-bold text-[10px] uppercase" title="Restaurar a Nuevo">
                    <i data-lucide="refresh-ccw" class="w-4 h-4"></i> Restaurar
                </button>
                <button onclick="openDelete(${p.id}, true)" class="bg-red-100 text-red-700 hover:bg-red-200 p-2 rounded-lg flex items-center gap-1 font-bold text-[10px] uppercase" title="Borrar Definitivamente">
                    <i data-lucide="trash-2" class="w-4 h-4"></i> Eliminar
                </button>
            </div>
        `;
    } else {
        if(type === 'tracking' || type === 'won') {
             actionsBtn = `<button onclick="openConvertModal(${p.id})" class="text-gray-400 hover:text-green-600" title="Convertir a Cliente"><i data-lucide="user-check" class="w-5 h-5"></i></button>`;
        }
        actionsBtn += `
            <button onclick="openEdit(${p.id})" class="text-gray-400 hover:text-blue-600 ml-2"><i data-lucide="edit" class="w-5 h-5"></i></button>
            <button onclick="openDelete(${p.id})" class="text-gray-400 hover:text-red-600 ml-2"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
        `;
    }
    
    const companyDisplayTable = p.empresa || 'RESIDENCIAL'; 
    const serviceName = p.service_id ? (servicesData.find(s => s.id == p.service_id)?.name || '') : '';
    // Fix Spam Lines: No mostrar badge vacío
    const serviceBadge = (serviceName && serviceName !== '') 
        ? `<span class="text-xs font-bold uppercase text-blue-800 bg-blue-100 px-2 py-1 rounded block mt-1 w-fit">${serviceName}</span>` 
        : '';

    const cellClass = "flex justify-between items-center md:table-cell w-full md:w-auto py-2 md:py-4 px-0 md:px-6 border-b md:border-none last:border-0";
    const labelClass = "block md:hidden font-bold text-xs text-gray-500 uppercase";

    tr.innerHTML = `
        <td class="${cellClass}">
            <span class="${labelClass}">NOMBRE</span>
            <div class="text-right md:text-left">
                <span class="font-bold uppercase block text-gray-800">${p.nombre_completo}</span>
                <span class="text-xs text-gray-500 uppercase">${companyDisplayTable}</span>
                ${serviceBadge}
                <div class="md:hidden mt-1 flex justify-end">${badge}</div>
            </div>
            <div class="hidden md:block mt-1">${badge}</div>
        </td>
        <td class="${cellClass}">
            <span class="${labelClass}">TELÉFONO</span>
            <div class="text-sm font-medium text-gray-700">${phone}</div>
        </td>
        <td class="${cellClass}">
            <span class="${labelClass}">EMAIL</span>
            ${emailDisplay}
        </td>
        <td class="${cellClass}">
            <span class="${labelClass}">ETAPA</span>
            <span class="px-2 py-1 rounded text-xs font-bold uppercase ${statusClass}">${p.estado}</span>
        </td>
        <td class="${cellClass} md:text-center">
            <span class="${labelClass}">ACCIONES</span>
            <div class="flex justify-end gap-3">
                ${actionsBtn}
            </div>
        </td>
    `;
    return tr;
}

// --- DATA HANDLERS ---

async function updateStatus(id, status) {
    try {
        const res = await fetch(API_ENDPOINTS.UPDATE_STATUS, {
            method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id, status})
        });
        const data = await res.json();
        if(data.success) {
            const idx = prospectArray.findIndex(p => p.id == id);
            if(idx > -1) {
                prospectArray[idx].estado = status;
                filterData();
            }
            const msg = status === 'Nuevo' ? 'Prospecto Restaurado' : (status === 'Rechazados' ? 'Archivado a Papelera' : 'Estado Actualizado');
            showToast(msg, 'success');
        } else {
            showToast('Error al actualizar', 'error');
        }
    } catch(e) { showToast('Error de conexión', 'error'); }
}

async function handleAddSubmit(e) {
    e.preventDefault();
    const fd = new FormData(e.target);
    const data = Object.fromEntries(fd.entries());
    data.status = 'Nuevo';
    try {
        const res = await fetch(API_ENDPOINTS.CREATE, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) });
        const json = await res.json();
        if(json.success) { location.reload(); }
        else { showToast(json.message || 'Error', 'error'); }
    } catch(err) { showToast('Error al guardar', 'error'); }
}

async function handleEditSubmit(e) {
    e.preventDefault();
    const fd = new FormData(e.target);
    const data = Object.fromEntries(fd.entries());
    data.id = document.getElementById('edit-prospecto-id').value;
    try {
        const res = await fetch(API_ENDPOINTS.UPDATE, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) });
        const json = await res.json();
        if(json.success) { location.reload(); }
        else { showToast(json.message || 'Error', 'error'); }
    } catch(err) { showToast('Error al actualizar', 'error'); }
}

// Lógica de borrado dual (Soft vs Hard)
let deleteId = null;
let isPermanentDelete = false;

function openDelete(id, permanent = false) {
    deleteId = id;
    isPermanentDelete = permanent;
    const p = prospectArray.find(x => x.id == id);
    if (p) {
        document.getElementById('delete-item-name').textContent = p.nombre_completo;
    } else {
        document.getElementById('delete-item-name').textContent = "ESTE PROSPECTO";
    }
    
    // Cambiar texto del modal dinámicamente según si es borrado definitivo
    const modalTitle = document.querySelector('#confirmDeleteModal .modal-primary-title');
    const modalBtn = document.getElementById('confirm-delete-button');
    
    if(permanent) {
        modalTitle.textContent = "BORRAR DEFINITIVAMENTE";
        modalBtn.innerHTML = '<i data-lucide="trash-2" class="w-5 h-5"></i> ELIMINAR';
    } else {
        modalTitle.textContent = "ADVERTENCIA";
        modalBtn.innerHTML = '<i data-lucide="archive" class="w-5 h-5"></i> ARCHIVAR';
    }

    const modal = document.getElementById('confirmDeleteModal');
    const content = modal.querySelector('div:first-of-type');
    modal.classList.remove('hidden');
    setTimeout(() => { content.classList.remove('scale-95', 'opacity-0'); }, 10);
    lucide.createIcons();
}

async function confirmDeleteAction() {
    if(!deleteId) return;
    
    // Si no es permanente, es un updateStatus a 'Rechazados'
    if(!isPermanentDelete) {
        await updateStatus(deleteId, 'Rechazados');
        closeModal('confirmDeleteModal');
        return;
    }

    // Si es permanente, llamada a DELETE
    try {
        const res = await fetch(API_ENDPOINTS.DELETE, {
            method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id: deleteId})
        });
        const data = await res.json();
        if(data.success) {
            showToast('Prospecto eliminado permanentemente', 'success');
            closeModal('confirmDeleteModal');
            prospectArray = prospectArray.filter(p => p.id != deleteId);
            filterData();
            updateStats();
        } else {
            showToast('Error al eliminar', 'error');
        }
    } catch(e) { showToast('Error de conexión', 'error'); }
}

const btnConfirmDelete = document.getElementById('confirm-delete-button');
if(btnConfirmDelete) {
    btnConfirmDelete.addEventListener('click', confirmDeleteAction);
}

// --- UTILS ---
function getStatusColorClass(status) {
    const s = status.toLowerCase();
    if (s.includes('perdida') || s.includes('perdido') || s.includes('rechazados')) return 'bg-red-100 text-red-800 border border-red-200';
    if (s.includes('ganada') || s.includes('ganado') || s.includes('cliente')) return 'bg-emerald-100 text-emerald-800 border border-emerald-200';
    return 'bg-yellow-100 text-yellow-800 border border-yellow-200';
}
function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}
function formatUSAPhone(str) {
    if(!str) return '';
    var cleaned = ('' + str).replace(/\D/g, '');
    var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
    if (match) return '(' + match[1] + ') ' + match[2] + '-' + match[3];
    return str;
}
function getPriorityBadge(p) {
    if(p === 'Alta') return '<span class="text-[10px] font-bold text-red-600 bg-red-100 px-2 py-0.5 rounded-full uppercase">Alta</span>';
    if(p === 'Media') return '<span class="text-[10px] font-bold text-blue-600 bg-blue-100 px-2 py-0.5 rounded-full uppercase">Media</span>';
    return '<span class="text-[10px] font-bold text-gray-600 bg-gray-100 px-2 py-0.5 rounded-full uppercase">Baja</span>';
}
function updateStats() {
    const totalEl = document.getElementById('total-prospectos-count');
    if(totalEl) totalEl.textContent = prospectArray.length;
    const thisMonth = new Date().toISOString().slice(0,7);
    const monthEl = document.getElementById('monthly-prospectos-count');
    if(monthEl) monthEl.textContent = prospectArray.filter(p => p.created_at.startsWith(thisMonth)).length;
}
function openConvertModal(id) {
    const p = prospectArray.find(x => x.id == id);
    if (p) document.getElementById('convert-item-name').textContent = p.nombre_completo;
    const modal = document.getElementById('confirmConvertModal');
    const content = modal.querySelector('div:first-of-type');
    modal.classList.remove('hidden');
    setTimeout(() => { content.classList.remove('scale-95', 'opacity-0'); }, 10);
    lucide.createIcons();
}
function closeModal(id) {
    const modal = document.getElementById(id);
    const content = modal.querySelector('div:first-of-type');
    content.classList.add('scale-95', 'opacity-0');
    setTimeout(() => modal.classList.add('hidden'), 300);
}
function openPanel(id) { 
    const p = document.getElementById(id);
    const overlay = document.getElementById('task-panel-overlay');
    if(p) { p.classList.remove('translate-x-full'); p.classList.add('translate-x-0'); 
        if(id === 'addProspectoPanel') {
            document.getElementById('add-prospecto-form').reset();
            if(defaultStateFromDB) document.getElementById('prospecto-estado-provincia').value = defaultStateFromDB;
        }
    }
    if(overlay) { overlay.classList.remove('hidden'); overlay.classList.add('block'); }
    document.body.style.overflow = 'hidden';
    lucide.createIcons();
}
function closeAllPanels() { 
    ['addProspectoPanel', 'editProspectoPanel', 'manageSourcesPanel'].forEach(id => {
        const p = document.getElementById(id);
        if(p) { p.classList.remove('translate-x-0'); p.classList.add('translate-x-full'); }
    });
    const overlay = document.getElementById('task-panel-overlay');
    if(overlay) { overlay.classList.remove('block'); overlay.classList.add('hidden'); }
    document.body.style.overflow = '';
}
function openEdit(id) {
    const p = prospectArray.find(x => x.id == id);
    if(!p) return;
    document.getElementById('edit-prospecto-id').value = p.id;
    document.getElementById('edit-prospecto-display-id').textContent = p.id; 
    document.getElementById('edit-prospecto-first-name').value = p.first_name;
    document.getElementById('edit-prospecto-last-name').value = p.last_name;
    document.getElementById('edit-prospecto-empresa').value = p.empresa;
    document.getElementById('edit-prospecto-email').value = p.email;
    document.getElementById('edit-prospecto-telefono').value = p.phone;
    document.getElementById('edit-prospecto-celular').value = p.mobile;
    document.getElementById('edit-prospecto-fuente').value = p.fuente;
    document.getElementById('edit-prospecto-prioridad').value = p.prioridad;
    document.getElementById('edit-prospecto-direccion-calle').value = p.direccion_calle;
    document.getElementById('edit-prospecto-ciudad').value = p.ciudad;
    document.getElementById('edit-prospecto-estado-provincia').value = p.state_province || defaultStateFromDB;
    document.getElementById('edit-prospecto-codigo-postal').value = p.zip_code;
    document.getElementById('edit-prospecto-servicio').value = p.service_id || "";
    const statusSelect = document.getElementById('edit-prospecto-status');
    statusSelect.innerHTML = ''; 
    const currentStatus = p.estado ? p.estado.trim() : ''; 
    const allStatuses = ['Entrante', 'Nuevo', 'Contactado', 'En Seguimiento', 'Presentar Solución', 'Introducir Servicio', 'Lead Ganado', 'Lead Perdido', 'Rechazados'];
    allStatuses.forEach(s => {
        const isSelected = s === currentStatus;
        statusSelect.innerHTML += `<option value="${s}" ${isSelected ? 'selected' : ''}>${s.toUpperCase()}</option>`;
    });
    document.querySelectorAll('.phone-mask').forEach(el => IMask(el, {mask: '(000) 000-0000'}));
    openPanel('editProspectoPanel');
}
function filterData() {
    const term = document.getElementById('prospect-search').value.toLowerCase();
    const status = document.getElementById('prospect-filter-status').value;
    const source = document.getElementById('prospect-filter-source').value;
    const month = document.getElementById('month-filter-select').value;
    filteredProspects = prospectArray.filter(p => {
        const matchName = p.nombre_completo.toLowerCase().includes(term) || p.email.toLowerCase().includes(term) || p.empresa.toLowerCase().includes(term);
        const matchStatus = status === 'all' || p.estado === status;
        const matchSource = source === 'all' || p.fuente === source;
        const matchMonth = month === 'all' || p.created_at.startsWith(month);
        return matchName && matchStatus && matchSource && matchMonth;
    });
    renderAll();
}
function setupServices() {
    const options = servicesData.map(s => `<option value="${s.id}">${s.name.toUpperCase()}</option>`).join('');
    const selects = document.querySelectorAll('.service-selector');
    selects.forEach(select => { select.innerHTML = '<option value="">-- SELECCIONAR SERVICIO --</option>' + options; });
}
function setupMonthFilter() {
    const select = document.getElementById('month-filter-select');
    if(!select) return;
    const dates = new Set(prospectArray.map(p => p.created_at.substring(0, 7)));
    const sortedDates = [...dates].sort().reverse();
    let optionsHtml = '<option value="all">MES: TODOS</option>';
    sortedDates.forEach(date => {
        const [year, month] = date.split('-');
        const dateObj = new Date(year, month - 1);
        const label = dateObj.toLocaleString('es-ES', { month: 'long', year: 'numeric' }).toUpperCase();
        optionsHtml += `<option value="${date}">${label}</option>`;
    });
    select.innerHTML = optionsHtml;
    select.addEventListener('change', filterData);
}
function setupListeners() {
    const searchInput = document.getElementById('prospect-search');
    if(searchInput) searchInput.addEventListener('input', debounce(() => filterData(), 300));
    document.getElementById('prospect-filter-status').addEventListener('change', filterData);
    document.getElementById('prospect-filter-source').addEventListener('change', filterData);
    const btnDownload = document.getElementById('download-prospectos-btn');
    if(btnDownload) btnDownload.addEventListener('click', downloadCSV);
    const btnAddSource = document.getElementById('add-source-btn');
    if(btnAddSource) btnAddSource.addEventListener('click', addSource);
    const addForm = document.getElementById('add-prospecto-form');
    if(addForm) addForm.addEventListener('submit', handleAddSubmit);
    const editForm = document.getElementById('edit-prospecto-form');
    if(editForm) editForm.addEventListener('submit', handleEditSubmit);
    document.getElementById('kanban-view-btn').addEventListener('click', () => toggleView('kanban'));
    document.getElementById('table-view-btn').addEventListener('click', () => toggleView('table'));
}
function toggleView(view) {
    const kanban = document.getElementById('prospectos-kanban-view');
    const table = document.getElementById('prospectos-table-view');
    if(view === 'kanban') {
        kanban.classList.remove('hidden');
        table.classList.add('hidden');
        document.getElementById('kanban-view-btn').classList.add('bg-white');
        document.getElementById('table-view-btn').classList.remove('bg-white');
    } else {
        kanban.classList.add('hidden');
        table.classList.remove('hidden');
        document.getElementById('kanban-view-btn').classList.remove('bg-white');
        document.getElementById('table-view-btn').classList.add('bg-white');
    }
}
async function setupSources() {
    try {
        const res = await fetch(API_ENDPOINTS.SOURCES_READ);
        const d = await res.json();
        const list = d.data || [];
        const opts = list.map(s => `<option value="${s.name}">${s.name.toUpperCase()}</option>`).join('');
        const sAdd = document.getElementById('prospecto-fuente');
        if(sAdd) sAdd.innerHTML = opts;
        const sEdit = document.getElementById('edit-prospecto-fuente');
        if(sEdit) sEdit.innerHTML = opts;
        const sFilter = document.getElementById('prospect-filter-source');
        if(sFilter) sFilter.innerHTML = '<option value="all">TODAS LAS FUENTES</option>' + opts;
        const ul = document.getElementById('sources-list');
        if(ul) {
            ul.innerHTML = list.map(s => `<li class="flex justify-between items-center bg-gray-100 p-2 rounded"><span class="uppercase font-bold text-sm">${s.name}</span><button onclick="deleteSource('${s.id}')" class="text-red-500 hover:text-red-700"><i data-lucide="trash-2" class="w-4 h-4"></i></button></li>`).join('');
        }
        lucide.createIcons();
    } catch(e) { console.error(e); }
}
async function addSource() {
    const nameInput = document.getElementById('new-source-name');
    const name = nameInput.value;
    if(!name) return showToast('Escribe un nombre', 'info');
    try {
        const res = await fetch(API_ENDPOINTS.SOURCES_ADD, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({name}) });
        const data = await res.json();
        if(data.success) { showToast('Fuente agregada', 'success'); nameInput.value = ''; setupSources(); }
    } catch(e) { showToast('Error', 'error'); }
}
async function deleteSource(id) {
    if(!confirm('¿Borrar fuente?')) return;
    try {
        const res = await fetch(API_ENDPOINTS.SOURCES_DEL, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) });
        if((await res.json()).success) { setupSources(); showToast('Fuente eliminada', 'success'); }
    } catch(e) { showToast('Error', 'error'); }
}
function showToast(msg, type='info') {
    const container = document.getElementById('toast-container');
    const el = document.createElement('div');
    el.className = `toast toast-${type}`;
    el.innerHTML = `<i data-lucide="${type === 'success' ? 'check-circle' : 'info'}"></i><span>${msg}</span>`;
    container.appendChild(el);
    lucide.createIcons({ container: el });
    setTimeout(() => el.classList.add('show'), 10);
    setTimeout(() => { el.classList.remove('show'); setTimeout(() => el.remove(), 300); }, 3000);
}
function downloadCSV() {
    if(!filteredProspects.length) return showToast('Nada que exportar', 'info');
    const header = ['ID', 'Nombre', 'Empresa', 'Email', 'Telefono', 'Fuente', 'Etapa', 'Fecha'];
    const rows = filteredProspects.map(p => [p.id, p.nombre_completo, p.empresa, p.email, p.phone, p.fuente, p.estado, p.created_at]);
    const csvContent = "data:text/csv;charset=utf-8," + [header, ...rows].map(e => e.join(",")).join("\n");
    const link = document.createElement("a");
    link.setAttribute("href", encodeURI(csvContent));
    link.setAttribute("download", "leads_export.csv");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
function setupDragAndDrop() {
    const cards = document.querySelectorAll('.kanban-card');
    const lists = document.querySelectorAll('.kanban-list');
    let draggedItem = null;
    cards.forEach(card => {
        card.addEventListener('dragstart', (e) => { draggedItem = card; setTimeout(() => card.classList.add('opacity-50', 'dragging'), 0); e.dataTransfer.effectAllowed = 'move'; });
        card.addEventListener('dragend', () => { card.classList.remove('opacity-50', 'dragging'); draggedItem = null; });
    });
    lists.forEach(list => {
        list.addEventListener('dragover', e => { e.preventDefault(); const afterElement = getDragAfterElement(list, e.clientY); const draggable = document.querySelector('.dragging'); if (!draggable) return; if (afterElement == null) list.appendChild(draggable); else list.insertBefore(draggable, afterElement); });
        list.addEventListener('drop', async (e) => { e.preventDefault(); const draggable = document.querySelector('.dragging'); if (!draggable) return; const pid = draggable.dataset.prospectId; const newStatus = list.dataset.statusList; if (prospectsData[pid] && prospectsData[pid].estado !== newStatus) { const previousStatus = prospectsData[pid].estado; prospectsData[pid].estado = newStatus; const pIndex = prospectArray.findIndex(p => p.id == pid); if(pIndex > -1) prospectArray[pIndex].estado = newStatus; try { await updateStatus(pid, newStatus); } catch(error) { prospectsData[pid].estado = previousStatus; renderAll(); showToast('Error al mover tarjeta', 'error'); } } });
    });
}
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 initCharts() {
    const monthsData = {};
    prospectArray.forEach(p => { const monthKey = p.created_at.substring(0, 7); monthsData[monthKey] = (monthsData[monthKey] || 0) + 1; });
    const sortedMonths = Object.keys(monthsData).sort();
    const labels = sortedMonths.map(m => { const [year, month] = m.split('-'); const date = new Date(year, month - 1); return date.toLocaleString('es-ES', { month: 'short', year: 'numeric' }).toUpperCase(); });
    const dataValues = sortedMonths.map(m => monthsData[m]);
    const totalLeads = prospectArray.length;
    const totalClients = prospectArray.filter(p => p.estado.toLowerCase().includes('ganado') || p.estado.toLowerCase().includes('cliente') || p.estado.toLowerCase().includes('pagada')).length;
    const pendingLeads = totalLeads - totalClients;
    const conversionRate = totalLeads > 0 ? ((totalClients / totalLeads) * 100).toFixed(1) : 0;
    const elTotal = document.getElementById('stat-total-leads'); if(elTotal) elTotal.textContent = totalLeads;
    const elClients = document.getElementById('stat-total-clients'); if(elClients) elClients.textContent = totalClients;
    const elRate = document.getElementById('stat-conversion-rate'); if(elRate) elRate.textContent = conversionRate + '%';
    const ctxMonthly = document.getElementById('monthlyLeadsChart');
    if (ctxMonthly) {
        new Chart(ctxMonthly, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Leads Captados', data: dataValues, backgroundColor: '#07162d', borderColor: '#ffc857', borderWidth: 2, borderRadius: 4, barThickness: 35, hoverBackgroundColor: '#9e1428' }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1, color: '#07080a' }, grid: { color: '#f3f4f6' } }, x: { grid: { display: false }, ticks: { color: '#07162d' } } } } });
    }
    const ctxConversion = document.getElementById('conversionChart');
    if (ctxConversion) {
        new Chart(ctxConversion, { type: 'doughnut', data: { labels: ['En Proceso / Otros', 'Clientes Ganados'], datasets: [{ data: [pendingLeads, totalClients], backgroundColor: [ '#e5e7eb', '#50AF70' ], borderColor: ['#ffffff', '#ffffff'], borderWidth: 2, hoverOffset: 4 }] }, options: { responsive: true, maintainAspectRatio: false, cutout: '75%', plugins: { legend: { position: 'bottom', labels: { usePointStyle: true, color: '#07162d' } } } } });
    }
}
</script>
<script src="files/toast.js"></script>
</body>
</html>