<?php
include 'files/guardiankey.php';
include_once 'db/db_connection.php'; // Conexión a la base de datos

// --- DEFINICIÓN DE FASES (MAPEA A ESTADOS DE LA DB) ---
$kanban_stages = [
    0 => ['id' => 0, 'title' => 'ENVIADAS', 'db_status' => 'Cotización Enviada', 'color_class' => 'text-[var(--color-secondary)]', 'border_class' => 'border-t-[var(--color-highlight)]', 'icon' => 'file-check-2', 'desc' => 'Leads Que Ya Recibieron La Cotización Formal'],
    1 => ['id' => 1, 'title' => 'SEGUIMIENTO POST ENVÍO', 'db_status' => 'Seguimiento Post Envío', 'color_class' => 'text-[var(--color-primary)]', 'border_class' => 'border-l-[var(--color-primary)]', 'icon' => 'badge-check', 'desc' => 'Primer Contacto Después Del Envío'],
    2 => ['id' => 2, 'title' => 'SEGUIMIENTO RECORDATORIO', 'db_status' => 'Seguimiento Recordatorio', 'color_class' => 'text-[var(--color-secondary)]', 'border_class' => 'border-l-[var(--color-secondary)]', 'icon' => 'badge-info', 'desc' => 'Prospectos Que Requieren Un Recordatorio'],
    3 => ['id' => 3, 'title' => 'NEGOCIACIÓN FINAL', 'db_status' => 'Negociación Final', 'color_class' => 'text-[var(--color-secondary)]', 'border_class' => 'border-l-[var(--color-primary)]', 'icon' => 'badge-plus', 'desc' => 'Etapa De Cierre O Gestión Para La Conversión']
];

$won_db_status = 'Ganada';
$lost_db_status = 'Perdida';

$kanban_db_statuses = array_column($kanban_stages, 'db_status');

// --- LÓGICA DE DATOS: LECTURA DESDE LA BASE DE DATOS ---

$sales_leads = [];
$won_quotes = [];
$lost_quotes = [];
$detailed_leads_data = []; // Contendrá todos los datos para el JS

try {

    $legacy_status = 'Cotización Enviada';
    $all_statuses = array_merge($kanban_db_statuses, [$won_db_status, $lost_db_status, $legacy_status]);
    
    $placeholders = implode(',', array_fill(0, count($all_statuses), '?'));
    
    $stmt = $pdo->prepare("
        SELECT 
            l.id, l.first_name, l.last_name, l.company, l.email, l.phone, l.mobile, l.status, 
            l.priority, l.street_address, l.city, l.state_province, l.zip_code, 
            l.created_at, l.updated_at AS last_activity_date, l.next_task_date, l.lost_reason,
            e.total_amount AS amount,
            e.estimate_date AS estimate_creation_date
        FROM leads AS l
        LEFT JOIN estimates AS e ON l.id = e.lead_id
        WHERE l.status IN ($placeholders)
        GROUP BY l.id 
        ORDER BY e.estimate_date DESC
    ");
    
    $stmt->execute($all_statuses);
    $all_leads_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. Obtener cotizaciones y clientes (para los KPIs)
    $total_leads_count_stmt = $pdo->query("SELECT COUNT(id) FROM leads WHERE status NOT IN ('Ganada', 'Perdida', 'Descartado')");
    $total_leads_count = $total_leads_count_stmt->fetchColumn();

    // Contar solo los leads que están en este embudo (estado inicial)
    $total_quotes_sent_stmt = $pdo->prepare("SELECT COUNT(id) FROM leads WHERE status = ?");
    $total_quotes_sent_stmt->execute([ $kanban_stages[0]['db_status'] ]);
    $total_quotes_sent = $total_quotes_sent_stmt->fetchColumn();


    // 3. Procesar y clasificar los leads
    $stage_db_to_id_map = array_column($kanban_stages, 'id', 'db_status');

    foreach ($all_leads_raw as $lead) {
        $name = trim($lead['first_name'] . ' ' . $lead['last_name']);
        
        $amount = $lead['amount'] ? $lead['amount'] : 0.00;
        $date_to_use = $lead['estimate_creation_date'] ? $lead['estimate_creation_date'] : $lead['created_at'];
        
        $js_data = [
            'id' => $lead['id'],
            'name' => $name,
            'amount' => $amount,
            'date' => $date_to_use,
            'stage' => null,
            'phone' => $lead['phone'] ? $lead['phone'] : $lead['mobile'],
            'email' => $lead['email'],
            'company' => $lead['company'],
            'last_activity_date' => $lead['last_activity_date'],
            'next_task_date' => $lead['next_task_date'],
            'status_text' => $lead['status'],
            'lost_reason' => $lead['lost_reason']
        ];
        
        // Clasificar
        if ($lead['status'] == $won_db_status) {
           $won_quotes[] = ['id' => $lead['id'], 'name' => $name, 'amount' => $amount, 'date' => $lead['last_activity_date']];
           $js_data['stage'] = 'won';
        } 
        else if ($lead['status'] == $lost_db_status) {
            $lost_quotes[] = ['id' => $lead['id'], 'name' => $name, 'amount' => $amount, 'date' => $lead['last_activity_date'], 'reason' => $lead['lost_reason'] ? $lead['lost_reason'] : 'No especificada'];
            $js_data['stage'] = 'lost';
        } 
        else if ($lead['status'] == $kanban_stages[0]['db_status'] || $lead['status'] == 'Cotización Enviada') {
            $stage_id = 0; 
            $js_data['stage'] = $stage_id;
            $sales_leads[] = [
                'id' => $lead['id'],
                'name' => $name,
                'amount' => $amount,
                'date' => $date_to_use,
                'stage' => $stage_id
            ];
        } 
        else if (isset($stage_db_to_id_map[$lead['status']])) {
            $stage_id = $stage_db_to_id_map[$lead['status']];
            $js_data['stage'] = $stage_id;
            $sales_leads[] = [
                'id' => $lead['id'],
                'name' => $name,
                'amount' => $amount,
                'date' => $date_to_use,
                'stage' => $stage_id
            ];
        }
        
        $detailed_leads_data[$lead['id']] = $js_data;
    }

} catch (PDOException $e) {
    error_log("Error en quote-tracking.php: ". $e->getMessage());
    // Fallback con datos vacíos
    $sales_leads = [];
    $won_quotes = [];
    $lost_quotes = [];
    $detailed_leads_data = [];
    $total_leads_count = 0;
    $total_quotes_sent = 0;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Seguimiento A Prospectos FlowCRM™  De OrozDesign Powered By OrozCO</title>
	<meta name="robots" content="noindex, nofollow">
    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    <style>
        .alert-stale-lead {
            border-right-width: 4px;
            border-right-color: var(--color-secondary);
            animation: pulse-border 2s infinite;
        }
        @keyframes pulse-border {
            0%, 100% { box-shadow: 0 0 8px -3px var(--color-secondary); }
            50% { box-shadow: 0 0 8px 2px var(--color-secondary); }
        }
        
        .kanban-list:empty {
            min-height: 120px; /* Un poco más de espacio */
            transition: background-color 0.2s ease, outline 0.2s ease;
        }
        
        .kanban-list.drag-over {
             background-color: #f0f7ff; /* Un azul muy claro */
             outline: 2px dashed #007bff; /* Borde azul punteado */
             outline-offset: -4px;
        }
        

    </style>
</head>
<body class="font-barlow" 
    data-page-title="Centro De Seguimiento De Cotizaciones" 
    data-page-subtitle="Seguimiento Estratégico Para Convertir Leads En Clientes" 
    data-page-icon="combine">
    
    <div id="toast-container" class="toast-container"></div>
    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div>

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

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

        <div id="content-area" class="p-4 md:p-8 bg-[var(--color-background)]">
            
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                
                <div class="lg:col-span-2">
                    <div class="grid grid-cols-1 lg:grid-cols-2 lg:gap-8 space-y-8 lg:space-y-0">
                        
                        <div>
                            <?php $stage = $kanban_stages[0]; ?>
                            <div id="stage-<?php echo $stage['id']; ?>" data-stage-id="<?php echo $stage['id']; ?>" class="sales-column bg-white rounded-xl p-4 flex flex-col h-full max-h-[80vh] transition duration-300 transform shadow-lg hover:shadow-xl <?php echo $stage['border_class']; ?>">
                                <div class="flex-shrink-0">
                                    <div class="flex justify-between items-center mb-2 border-b pb-2">
                                        <h2 class="text-4xl font-black flex items-center <?php echo $stage['color_class']; ?>"><i data-lucide="<?php echo $stage['icon']; ?>" class="w-5 h-5 mr-2"></i><?php echo htmlspecialchars($stage['title']); ?></h2>
                                        <span class="text-gray-500 font-bold" id="count-<?php echo $stage['id']; ?>"></span>
                                    </div>
                                    <p class="text-sm text-gray-500 mb-4"><?php echo htmlspecialchars($stage['desc']); ?></p>
                                </div>
                                <div class="kanban-list space-y-4 flex-grow overflow-y pr-2" data-stage-id="<?php echo $stage['id']; ?>"></div>
                            </div>
                        </div>
                        
                        <div class="space-y-6">
                            <?php for ($i = 1; $i <= 3; $i++): $stage = $kanban_stages[$i]; ?>
                                <div id="stage-<?php echo $stage['id']; ?>" data-stage-id="<?php echo $stage['id']; ?>" class="sales-column bg-white rounded-xl p-4 flex flex-col transition duration-300 shadow-lg hover:shadow-xl <?php echo $stage['border_class']; ?>">
                                    <div class="flex-shrink-0">
                                        <div class="flex justify-between items-center mb-2 border-b pb-2">
                                            <h2 class="text-lg font-black flex items-center <?php echo $stage['color_class']; ?>"><i data-lucide="<?php echo $stage['icon']; ?>" class="w-4 h-4 mr-2"></i><?php echo htmlspecialchars($stage['title']); ?></h2>
                                            <span class="text-gray-500 font-bold" id="count-<?php echo $stage['id']; ?>"></span>
                                        </div>
                                        <p class="text-xs text-gray-500 mb-3"><?php echo htmlspecialchars($stage['desc']); ?></p>
                                    </div>
                                    <div class="kanban-list space-y-3 flex-grow overflow-y pr-2" data-stage-id="<?php echo $stage['id']; ?>"></div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div> <div class="space-y-6">
                    <div id="won-column" data-action="win" class="sales-column bg-white rounded-xl p-4 flex flex-col h-1/2 border-emerald-500 transition duration-300 shadow-lg hover:shadow-xl">
                        <div class="flex-shrink-0">
                            <div class="flex justify-between items-center mb-2 border-b pb-2">
                                <h2 class="text-4xl font-black flex items-center text-emerald-600"><i data-lucide="trending-up" class="w-5 h-5 mr-2"></i>GANADAS</h2>
                                <span class="text-gray-500 font-bold" id="count-won"></span>
                            </div>
                        </div>
                        <div id="won-list" class="kanban-list space-y-4 flex-grow overflow-y pr-2"></div>
                    </div>

                    <div id="lost-column" data-action="lost" class="sales-column bg-white rounded-xl p-4 flex flex-col h-1/2 border-[var(--color-secondary)] transition duration-300 shadow-lg hover:shadow-xl">
                        <div class="flex-shrink-0">
                            <div class="flex justify-between items-center mb-2 border-b pb-2">
                                <h2 class="text-4xl font-black flex items-center text-[var(--color-secondary)]"><i data-lucide="trending-down" class="w-5 h-5 mr-2"></i>PERDIDAS</h2>
                                <span class="text-gray-500 font-bold" id="count-lost"></span>
                            </div>
                        </div>
                        <div id="lost-list" class="kanban-list space-y-4 flex-grow overflow-y pr-2"></div>
                    </div>
                </div> </div> <div class="mt-12">
                <h3 class="text-4xl font-black text-[var(--color-primary)] mb-4 flex items-center"><i data-lucide="bar-chart-3" class="w-6 h-6 mr-2"></i>MÉTRICAS CLAVE DE VENTAS</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-6">

            <div class="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 uppercase">Total Leads Activos</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_leads_count; ?></p>
                </div>
            </div>

            <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
                <i data-lucide="send" class="w-12 h-12 text-gray-700"></i>
                <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Cotizaciones Enviadas</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_quotes_sent; ?></p>
                </div>
            </div>

            <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-emerald-500">
                <i data-lucide="trophy" class="w-12 h-12 text-gray-700"></i>
                <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Ventas Ganadas</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo count($won_quotes); ?></p>
                </div>
            </div>

            <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-secondary)]">
                <i data-lucide="thumbs-down" class="w-12 h-12 text-gray-700"></i>
                <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Ventas Perdidas</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo count($lost_quotes); ?></p>
                </div>
            </div>

            <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-secondary)]">
                <i data-lucide="percent-circle" class="w-12 h-12 text-gray-700"></i>
                <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Tasa de Cierre</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php $total_closed = count($won_quotes) + count($lost_quotes); echo ($total_closed > 0) ? round((count($won_quotes) / $total_closed) * 100, 1) . '%' : '0%'; ?></p>
                </div>
            </div>

            <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-sky-500">
                <i data-lucide="target" class="w-12 h-12 text-gray-700"></i>
                <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Tasa de Cotización</h3>
                    <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo ($total_leads_count > 0) ? round(($total_quotes_sent / $total_leads_count) * 100, 1) . '%' : '0%'; ?></p>
                </div>
            </div>
        </div>
            </div>
        </div>
    </main>
</div>

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

<aside id="notes-panel" 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 flex flex-col shadow-2xl">
    <div class="p-4 bg-[var(--color-primary)] border-b border-gray-200 flex-shrink-0 flex justify-between items-center ">
        <h3 class="text-xl font-black text-[var(--color-highlight)] flex items-center">
            <i data-lucide="notebook-pen" class="w-5 h-5 mr-2 text-[var(--color-highlight)]"></i>
            SEGUIMIENTO Y NOTAS
        </h3>
        <button id="close-notes-panel-btn" class="text-gray-500 hover:text-[var(--color-secondary)] p-1 rounded-full transition-colors duration-200">
            <i data-lucide="x" class="w-6 h-6"></i>
        </button>
    </div>

    <div class="p-4 overflow-y-auto flex-grow">
        <div id="client-info-card" class="bg-white p-4 rounded-xl shadow-md mb-6 border-l-4 border-[var(--color-secondary)] transition duration-300">
            <h4 class="text-lg font-black text-[var(--color-secondary)] mb-2 flex items-center">
                <i data-lucide="user" class="w-5 h-5 mr-2"></i>
                <span id="panel-client-name" class="break-words"></span>
            </h4>
            <p class="text-sm text-gray-700 font-semibold mb-1 flex items-center"><i data-lucide="building" class="w-4 h-4 mr-1.5 text-gray-500"></i><span id="panel-client-company" class="break-words"></span></p>
            <p class="text-sm text-gray-700 mb-1 flex items-center"><i data-lucide="mail" class="w-4 h-4 mr-1.5 text-gray-500"></i><span id="panel-client-email" class="break-words"></span></p>
            <p class="text-sm text-gray-700 flex items-center"><i data-lucide="phone" class="w-4 h-4 mr-1.5 text-gray-500"></i><span id="panel-client-phone"></span></p>
            <p class="text-xs font-light text-gray-500 mt-2 text-right">ID Prospecto: <span id="panel-lead-id"></span></p>
            
            <div id="panel-next-task" class="mt-4 pt-2 border-t border-gray-200">
                <p class="text-sm font-bold text-[var(--color-primary)] flex items-center mb-1">
                    <i data-lucide="calendar-clock" class="w-4 h-4 mr-1.5 text-[var(--color-primary)]"></i> PRÓXIMO CONTACTO
                </p>
                <span id="panel-task-date" class="text-base font-black text-[var(--color-highlight)]"></span>
            </div>
        </div>
        
        <h4 class="text-lg font-bold text-[var(--color-primary)] mb-3 flex items-center border-b pb-1">
            <i data-lucide="message-square-plus" class="w-5 h-5 mr-2 text-[var(--color-primary)]"></i>
            NUEVA NOTA DE SEGUIMIENTO
        </h4>
        <div class="bg-white p-4 rounded-xl shadow-lg mb-6 transition duration-300">
            <div class="mb-3">
                <label for="next-task-date" class="block text-sm font-semibold text-[var(--color-primary)] mb-1 flex items-center">
                    <i data-lucide="calendar-check" class="w-4 h-4 mr-1.5 text-[var(--color-highlight)]"></i> Programar Contacto
                </label>
                <input type="date" id="next-task-date" 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">
            </div>
            <textarea id="new-note-content" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-secondary)] focus:ring-[var(--color-secondary)] focus:ring-1 transition duration-150 text-sm" rows="3" placeholder="Escriba aquí el resumen de la interacción o la tarea de seguimiento..."></textarea>
            <button id="save-note-btn" class="w-full mt-3 bg-[var(--color-secondary)] text-white font-black py-2 uppercase px-4 rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300 ease-in-out hover:bg-[var(--color-secondary)]">
                <i data-lucide="save" class="w-5 h-5 mr-2 inline-block"></i>
                Guardar Nota
            </button>
        </div>

        <h4 class="text-lg font-bold text-[var(--color-primary)] mb-3 flex items-center border-b pb-1">
            <i data-lucide="history" class="w-5 h-5 mr-2 text-[var(--color-primary)]"></i>
            HISTORIAL DE SEGUIMIENTO
        </h4>
        <div id="notes-list" class="space-y-4">
        </div>
    </div>
</aside>

<div id="promptLostReasonModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50 transform transition-all duration-300 scale-95 opacity-0">
        <div id="lost-modal-content" 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="help-circle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">¿POR QUÉ SE PERDIÓ?</h3>
        <p class="text-gray-700 mb-4">Por favor, ingrese la razón principal por la que se perdió esta cotización (afectará sus métricas de cierre):</p>
        
        <input type="text" id="lost-reason-input-quote" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-[var(--color-secondary)] focus:border-[var(--color-secondary)] text-sm mb-6" placeholder="Ej: Precio elevado, eligió competencia, Sin respuesta" required>

        <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="window.closeLostModal()"> CANCELAR
            </button>
            <button 
                type="button" 
                class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" 
                id="confirm-lost-reason-quote-btn">
                CONFIRMAR PÉRDIDA
            </button>
        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- DATOS INICIALES (Desde PHP) ---
    let leadsData = <?php echo json_encode($sales_leads); ?>;
    let wonData = <?php echo json_encode($won_quotes); ?>;
    let lostData = <?php echo json_encode($lost_quotes); ?>;
    let detailedLeadsData = <?php echo json_encode($detailed_leads_data); ?>; 
    const stagesData = <?php echo json_encode(array_values($kanban_stages)); ?>;
    const wonDbStatus = '<?php echo $won_db_status; ?>';
    const lostDbStatus = '<?php echo $lost_db_status; ?>';
    
    let draggedItem = null;
    let currentLeadId = null; // Para el panel de notas
    let tempLeadDataForModal = null; // Para el modal de pérdida

    // --- Selectores de Elementos ---
    const notesPanel = document.getElementById('notes-panel');
    const notesOverlay = document.getElementById('notes-panel-overlay');
    const closeNotesPanelBtn = document.getElementById('close-notes-panel-btn');
    const saveNoteBtn = document.getElementById('save-note-btn');
    
    // --- Selectores del Modal de Pérdida ---
    const lostModal = document.getElementById('promptLostReasonModal');
    const lostModalContent = document.getElementById('lost-modal-content');
    const saveLostReasonBtn = document.getElementById('confirm-lost-reason-quote-btn');
    const lostReasonInput = document.getElementById('lost-reason-input-quote');

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

    // --- MANEJO DEL PANEL LATERAL DE NOTAS ---
    window.openNotesPanel = async function(leadId) {
        const lead = detailedLeadsData[leadId];
        if (!lead) {
            showToast('Error: No se encontraron detalles para este lead.', 'error');
            return;
        }

        currentLeadId = leadId;
        
        document.getElementById('panel-client-name').textContent = lead.name;
        document.getElementById('panel-client-company').textContent = lead.company || 'N/A';
        document.getElementById('panel-client-email').textContent = lead.email || 'N/A';
        document.getElementById('panel-client-phone').textContent = lead.phone || 'N/A';
        document.getElementById('panel-lead-id').textContent = lead.id;

        const taskDateElement = document.getElementById('panel-task-date');
        const taskInputField = document.getElementById('next-task-date');
        
        if (lead.next_task_date) {
            const taskDate = new Date(lead.next_task_date + 'T00:00:00'); // Asegurar zona horaria local
            taskDateElement.textContent = taskDate.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
            taskInputField.value = lead.next_task_date; // Formato YYYY-MM-DD
        } else {
            taskDateElement.textContent = 'PENDIENTE DE ASIGNAR';
            taskInputField.value = '';
        }

        await renderNotes(leadId); 

        notesPanel.classList.remove('translate-x-full');
        notesOverlay.classList.remove('opacity-0', 'pointer-events-none');
        notesOverlay.classList.add('opacity-100');
        lucide.createIcons();
    }

    window.closeNotesPanel = function() {
        notesPanel.classList.add('translate-x-full');
        notesOverlay.classList.remove('opacity-100');
        notesOverlay.classList.add('opacity-0', 'pointer-events-none');
        currentLeadId = null;
        document.getElementById('new-note-content').value = '';
        document.getElementById('next-task-date').value = '';
    }

    async function renderNotes(leadId) {
        const notesList = document.getElementById('notes-list');
        notesList.innerHTML = '<p class="text-gray-500 italic text-sm p-3">Cargando notas...</p>';
        try {
            const response = await fetch(`db/leads-get-notes.php?lead_id=${leadId}`);
            const data = await response.json();
            notesList.innerHTML = '';
            if (data.success && data.notes.length > 0) {
                data.notes.forEach(note => {
                    const noteDiv = document.createElement('div');
                    noteDiv.className = 'bg-white p-3 rounded-xl shadow-md border-l-4 border-l-[var(--color-primary)] transition-all duration-200 ease-in-out hover:shadow-lg';
                    noteDiv.innerHTML = `
                        <div class="flex justify-between items-center mb-1 border-b pb-1">
                            <span class="text-xs font-bold text-[var(--color-primary)] flex items-center"><i data-lucide="calendar" class="w-4 h-4 mr-1.5 text-gray-500"></i> ${new Date(note.created_at).toLocaleString('es-ES', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
                            <i data-lucide="tag" class="w-4 h-4 text-[var(--color-highlight)]"></i>
                        </div>
                        <p class="text-sm text-gray-700">${note.content}</p>
                    `;
                    notesList.appendChild(noteDiv);
                });
            } else {
                notesList.innerHTML = '<p class="text-gray-500 italic text-sm p-4 bg-white rounded-xl shadow-md border-l-2 border-gray-300">Aún no hay notas de seguimiento registradas.</p>';
            }
        } catch (error) {
            console.error("Error cargando notas:", error);
            notesList.innerHTML = '<p class="text-[var(--color-secondary)] italic text-sm p-3">Error al cargar notas.</p>';
        }
        lucide.createIcons();
    }
    
    saveNoteBtn.addEventListener('click', async () => {
        const content = document.getElementById('new-note-content').value.trim();
        const nextTaskDate = document.getElementById('next-task-date').value;
        
        if (currentLeadId && (content || nextTaskDate)) {
            showToast('Guardando seguimiento...', 'info');
            try {
                const response = await fetch('db/quotes-add-note-task.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        lead_id: currentLeadId,
                        content: content,
                        next_task_date: nextTaskDate
                    })
                });
                const result = await response.json();
                if (result.success) {
                    showToast('Seguimiento guardado.', 'success');
                    if (result.next_task_date) {
                        detailedLeadsData[currentLeadId].next_task_date = result.next_task_date;
                    }
                    detailedLeadsData[currentLeadId].last_activity_date = new Date().toISOString(); 
                    await window.openNotesPanel(currentLeadId); 
                    renderKanbanCards(); 
                    lucide.createIcons();
                } else {
                    showToast(result.message || 'Error al guardar.', 'error');
                }
            } catch (error) {
                console.error("Error al guardar nota/tarea:", error);
                showToast('Error de conexión al guardar.', 'error');
            }
        } else {
            showToast('Escriba una nota o programe un próximo contacto.', 'warning');
        }
    });

    notesOverlay.addEventListener('click', closeNotesPanel);
    closeNotesPanelBtn.addEventListener('click', closeNotesPanel);

    // --- (FIX) MANEJO DEL MODAL DE PÉRDIDA ---
    saveLostReasonBtn.addEventListener('click', async () => {
        const reason = lostReasonInput.value.trim();
        const leadToMove = tempLeadDataForModal; // Carga el lead que guardamos al abrir el modal

        // 1. Validar que se escribió una razón
        if (!reason) {
            showToast('Por favor, ingrese una razón.', 'warning');
            lostReasonInput.focus();
            return;
        }

        // 2. Verificar que el lead temporal existe
        if (!leadToMove) {
            showToast('Error: No se ha seleccionado ningún lead.', 'error');
            window.closeLostModal();
            return;
        }

        // 3. Llamar a la función 'moveLead' que ya existe para guardar en DB
        await moveLead(
            leadToMove,         // El lead que se está moviendo
            lostDbStatus,       // El status 'Perdida'
            'lost',             // El tipo de destino
            reason,             // La razón que acabamos de escribir
            null,               // No es una 'stage' del funnel
            leadToMove.origin   // De dónde venía ('funnel' o 'won')
        );

        // 4. Cerrar el modal
        window.closeLostModal();
    });

    // --- MANEJO DEL MODAL DE PÉRDIDA (LIMPIO) ---
    window.openLostModal = (lead) => {
        tempLeadDataForModal = lead; 
        lostReasonInput.value = ''; 

        // Wrapper exterior (overlay)
        lostModal.classList.remove('hidden', 'scale-95', 'opacity-0');
        lostModal.classList.add('scale-100', 'opacity-100');
        // Contenido interior (tarjeta blanca)
        lostModalContent.classList.remove('scale-95', 'opacity-0');
        lostModalContent.classList.add('scale-100', 'opacity-100');

        lostReasonInput.focus(); 
    }
    
    window.closeLostModal = () => {
        // Wrapper exterior (overlay)
        lostModal.classList.add('hidden', 'scale-95', 'opacity-0');
        lostModal.classList.remove('scale-100', 'opacity-100');
        // Contenido interior (tarjeta blanca)
        lostModalContent.classList.add('scale-95', 'opacity-0');
        lostModalContent.classList.remove('scale-100', 'opacity-100');

        tempLeadDataForModal = null;
    }

    // --- RENDERIZADO DEL KANBAN ---
    function renderAll() {
        renderKanbanCards();
        renderWonCards();
        renderLostCards();
        updateAllCounts();
        lucide.createIcons();
    }
    
    function renderKanbanCards() {
        document.querySelectorAll('.kanban-list[data-stage-id]').forEach(list => list.innerHTML = '');
        leadsData.forEach(lead => {
            const stageInfo = stagesData[lead.stage];
            const targetList = document.querySelector(`.kanban-list[data-stage-id="${lead.stage}"]`);
            if (targetList) targetList.appendChild(createLeadCard(lead, stageInfo));
        });
    }

    function createLeadCard(lead, stage) {
        const borderColorClass = lead.stage === 0 ? stage.border_class.replace('border-t-', 'border-l-') : stage.border_class;
        const leadDetails = detailedLeadsData[lead.id];
        if (!leadDetails) return document.createElement('div'); // Safety check

        const lastActivityDate = new Date(leadDetails.last_activity_date);
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        const isStale = lastActivityDate < sevenDaysAgo;
        let staleClass = (lead.stage !== undefined && isStale) ? ' alert-stale-lead' : '';
        
        const classList = `sales-card bg-white p-3 rounded-lg shadow-md hover:shadow-lg border-l-4 cursor-grab transition-all duration-200 ease-in-out hover:-translate-y-0.5 ${borderColorClass} ${staleClass}`;

        const nextTask = leadDetails.next_task_date;
        let taskHTML = '';
        if (nextTask) {
            const nextTaskDate = new Date(nextTask + 'T00:00:00');
            const formattedDate = nextTaskDate.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' });
            taskHTML = `<div class="mt-2 text-sm font-semibold text-[var(--color-highlight)] flex items-center justify-end"><i data-lucide="bell" class="w-4 h-4 mr-1.5 text-[var(--color-highlight)]"></i> Próx. Contacto: ${formattedDate}</div>`;
        } else {
             taskHTML = `<div class="mt-2 text-xs text-gray-400 flex items-center justify-end"><i data-lucide="plus-circle" class="w-4 h-4 mr-1.5"></i> Sin Tarea Programada</div>`;
        }
        
        const innerHTML = `
            <div class="flex justify-between items-start">
                <span class="font-bold text-gray-800 text-base">${lead.name}</span>
                <span class="text-base font-black ${stage.color_class}">$${parseFloat(lead.amount).toFixed(2)}</span>
            </div>
            <div class="text-sm text-gray-500 mt-1 flex items-center"><i data-lucide="calendar" class="w-4 h-4 mr-1.5"></i> Estimado: ${new Date(lead.date).toLocaleDateString('es-ES', { month: 'short', day: 'numeric' })}</div>
            ${taskHTML}
            <div class="mt-3 text-right">
                <button data-action="open-panel" class="inline-flex items-center text-xs font-bold text-white bg-[var(--color-primary)] py-1 px-2.5 rounded-full shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 ease-in-out hover:bg-[var(--color-secondary)] focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)] focus:ring-opacity-50">
                    VER DETALLES
                    <i data-lucide="chevron-right" class="w-3 h-3 ml-1"></i>
                </button>
            </div>
        `;
        
        const card = document.createElement('div');
        card.className = classList;
        card.dataset.leadId = lead.id;
        card.dataset.stageId = lead.stage;
        card.dataset.origin = 'funnel';
        card.setAttribute('draggable', true);
        card.innerHTML = innerHTML;
        
        card.addEventListener('dragstart', handleDragStart);
        card.addEventListener('dragend', handleDragEnd);
        card.querySelector('[data-action="open-panel"]').addEventListener('click', (e) => {
             e.stopPropagation(); 
             openNotesPanel(lead.id);
        });
        return card;
    }

    function createWonCard(quote) {
        const classList = 'sales-card bg-white p-3 rounded-lg shadow-md border-l-4 border-emerald-500 cursor-grab transition-all duration-200 ease-in-out hover:-translate-y-0.5';
        const innerHTML = `
            <div class="flex justify-between items-start">
                <span class="font-bold text-gray-800 text-base">${quote.name}</span>
                <span class="text-base font-black text-emerald-600">$${parseFloat(quote.amount).toFixed(2)}</span>
            </div>
            <div class="text-sm text-gray-500 mt-1 flex items-center text-emerald-600"><i data-lucide="check-circle" class="w-4 h-4 mr-1.5"></i> Ganada: ${new Date(quote.date).toLocaleDateString('es-ES', { month: 'short', day: 'numeric' })}</div>`;
        
        const card = document.createElement('div');
        card.className = classList;
        card.dataset.leadId = quote.id;
        card.dataset.origin = 'won';
        card.setAttribute('draggable', true);
        card.innerHTML = innerHTML;
        card.addEventListener('dragstart', handleDragStart);
        card.addEventListener('dragend', handleDragEnd);
        card.addEventListener('click', () => openNotesPanel(quote.id));
        return card;
    }
    
    function createLostCard(quote) {
        const classList = 'sales-card bg-white p-3 rounded-lg shadow-md border-l-4 border-[var(--color-secondary)] cursor-grab transition-all duration-200 ease-in-out hover:-translate-y-0.5';
        const innerHTML = `
            <div class="flex justify-between items-start">
                <span class="font-bold text-gray-800 text-base">${quote.name}</span>
                <span class="text-base font-black text-[var(--color-secondary)]">$${parseFloat(quote.amount).toFixed(2)}</span>
            </div>
            <div class="text-sm font-bold text-[var(--color-secondary)] mt-2 flex items-start"><i data-lucide="info" class="w-4 h-4 mr-1.5 flex-shrink-0 mt-0.5"></i>Razón: ${quote.reason}</div>`;

        const card = document.createElement('div');
        card.className = classList;
        card.dataset.leadId = quote.id;
        card.dataset.origin = 'lost';
        card.setAttribute('draggable', true);
        card.innerHTML = innerHTML;
        card.addEventListener('dragstart', handleDragStart);
        card.addEventListener('dragend', handleDragEnd);
        card.addEventListener('click', () => openNotesPanel(quote.id));
        return card;
    }

    function renderWonCards() {
        const wonList = document.getElementById('won-list');
        wonList.innerHTML = '';
        wonData.forEach(quote => wonList.appendChild(createWonCard(quote)));
    }

    function renderLostCards() {
        const lostList = document.getElementById('lost-list');
        lostList.innerHTML = '';
        lostData.forEach(quote => lostList.appendChild(createLostCard(quote)));
    }

    // --- LÓGICA DE DRAG AND DROP ---
    
    function handleDragStart(e) {
        draggedItem = e.target;
        const dragData = {
            leadId: e.target.dataset.leadId,
            origin: e.target.dataset.origin
        };
        e.dataTransfer.setData('text/plain', JSON.stringify(dragData));
        setTimeout(() => e.target.classList.add('opacity-50'), 0);
    }
    
    function handleDragEnd(e) {
        if (draggedItem && draggedItem.classList) {
            draggedItem.classList.remove('opacity-50');
        }
        draggedItem = null; 
        
        document.querySelectorAll('.kanban-list.drag-over').forEach(list => {
            list.classList.remove('drag-over');
        });
    }
    
    function handleDragOver(e) { 
        e.preventDefault(); 
        e.currentTarget.classList.add('drag-over'); 
    }
    
    function handleDragLeave(e) { 
        e.currentTarget.classList.remove('drag-over'); 
    }

    async function handleDrop(e) {
        e.preventDefault();
        e.currentTarget.classList.remove('drag-over'); 
        
        const dropzoneList = e.currentTarget; 
        const dropzoneColumn = dropzoneList.closest('.sales-column');
        
        let data;
        try {
            data = JSON.parse(e.dataTransfer.getData('text/plain'));
        } catch (err) {
            console.error("Error al parsear datos de drag:", err);
            return; 
        }

        const leadId = parseInt(data.leadId);
        const origin = data.origin;
        
        const action = dropzoneColumn.dataset.action;
        const newStageId = parseInt(dropzoneColumn.dataset.stageId, 10);
        
        let lead;
        if (origin === 'funnel') {
            lead = leadsData.find(l => l.id === leadId);
        } else if (origin === 'won') {
            lead = wonData.find(l => l.id === leadId);
        } else if (origin === 'lost') {
            lead = lostData.find(l => l.id === leadId);
        }

        if (!lead || !draggedItem) return;

        lead.origin = origin;
        let newDbStatus = null;

        if (action === 'win') {
            if (origin === 'win') return;
            newDbStatus = wonDbStatus;
            moveLead(lead, newDbStatus, 'win', null, null, origin);

        } else if (action === 'lost') {
            if (origin === 'lost') return;
            openLostModal(lead); 
            
        } else if (!isNaN(newStageId)) {
            if (origin === 'funnel' && lead.stage === newStageId) return; 
            newDbStatus = stagesData[newStageId].db_status;
            moveLead(lead, newDbStatus, 'funnel', null, newStageId, origin);

        } else {
            return;
        }
    }
    
    async function moveLead(lead, newDbStatus, targetType, lostReason = null, newStageId = null, origin = 'funnel') {
        const leadId = lead.id;
        showToast(`Moviendo a ${newDbStatus}...`, 'info');
        
        try {
            const response = await fetch('db/quotes-update-status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    id: leadId,
                    status: newDbStatus,
                    lost_reason: lostReason
                })
            });
            const result = await response.json();

            if (result.success) {
                showToast('¡Estado actualizado!', 'success');
                
                // Remover de la lista de origen
                if (origin === 'funnel') {
                    leadsData = leadsData.filter(l => l.id !== leadId);
                } else if (origin === 'won') {
                    wonData = wonData.filter(l => l.id !== leadId);
                } else if (origin === 'lost') {
                    lostData = lostData.filter(l => l.id !== leadId);
                }
                
                // Actualizar datos locales
                detailedLeadsData[leadId].status_text = newDbStatus;
                detailedLeadsData[leadId].last_activity_date = new Date().toISOString();
                
                // Añadir a la nueva lista
                if (targetType === 'win') {
                    lead.date = new Date().toISOString().split('T')[0];
                    wonData.push(lead);
                    detailedLeadsData[leadId].stage = 'won';
                } else if (targetType === 'lost') {
                    lead.reason = lostReason;
                    lead.date = new Date().toISOString().split('T')[0];
                    lostData.push(lead);
                    detailedLeadsData[leadId].stage = 'lost';
                    detailedLeadsData[leadId].lost_reason = lostReason;
                } else if (targetType === 'funnel') {
                    lead.stage = newStageId; 
                    leadsData.push(lead); 
                    detailedLeadsData[leadId].stage = newStageId;
                }
                
                renderAll(); 

            } else {
                showToast(result.message || 'Error al actualizar.', 'error');
                renderAll(); 
            }

        } catch (error) {
            console.error("Error en moveLead fetch:", error);
            showToast('Error de conexión al mover.', 'error');
            renderAll(); 
        }
    }

    function updateAllCounts() {
        stagesData.forEach(stage => {
            const count = leadsData.filter(l => l.stage == stage.id).length;
            const countEl = document.getElementById(`count-${stage.id}`);
            if (countEl) countEl.textContent = `(${count})`;
        });
        document.getElementById('count-won').textContent = `(${wonData.length})`;
        document.getElementById('count-lost').textContent = `(${lostData.length})`;
    }

    // --- INICIALIZACIÓN ---
    renderAll();
    
    document.querySelectorAll('.kanban-list').forEach(list => {
        list.addEventListener('dragover', handleDragOver);
        list.addEventListener('dragleave', handleDragLeave);
        list.addEventListener('drop', handleDrop);
    });

    // --- Manejo Menú Móvil ---
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    
    if (mobileMenuButton && sidebar && sidebarOverlay) {
        mobileMenuButton.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            sidebarOverlay.classList.toggle('hidden');
        });
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.add('-translate-x-full');
            sidebarOverlay.classList.add('hidden');
        });
    }
});
</script>
</body>
</html>