<?php
include 'files/guardiankey.php';
require_once('db/db_connection.php');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Rutas Estratégicas FlowCRM™ | OrozDesign</title>
    <meta name="robots" content="noindex, nofollow">
    <link rel="icon" type="image/png" href="img/favicon.png">
    
    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    
</head>

<body data-page-title="Rutas Estratégicas De Servicios" 
      data-page-subtitle="Optimizador De Eficiencia Para Visitas De Servicios" 
      data-page-icon="git-compare-arrows">
    
    <div id="toast-container" class="toast-container"></div>
    
    <?php include 'files/gtm-body.php'; ?>
    
    <div class="relative min-h-screen md:flex">
        <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
        
    <?php include 'menu.php'; ?>

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

        <div id="content-area" class="p-4 md:p-8">
                
                <div id="create-route-modal" class="hidden fixed inset-0 bg-black bg-opacity-70 overflow-y-auto h-full w-full z-50">
                    <div class="relative mx-auto p-6 border shadow-2xl rounded-xl bg-white max-w-lg mt-[20vh]">
                        <h3 class="text-2xl font-black text-[var(--color-primary)] mb-4">CREAR RUTA PARA LA SEMANA <span id="modal-week-number" class="text-[var(--color-secondary)]"></span></h3>
                        <input type="text" id="new-route-name" placeholder="Ej. Ruta de José" class="w-full p-3 border-2 border-gray-300 rounded-lg mb-4">
                        <select id="new-route-day" class="w-full p-3 border-2 border-gray-300 rounded-lg bg-white mb-6">
                            <option value="">Seleccionar día (Opcional)</option>
                            <option value="Lunes">Lunes</option><option value="Martes">Martes</option><option value="Miércoles">Miércoles</option><option value="Jueves">Jueves</option><option value="Viernes">Viernes</option><option value="Sábado">Sábado</option><option value="Domingo">Domingo</option>
                        </select>
                        <div class="flex justify-end space-x-3">
                            <button class="close-modal-btn bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-lg">CANCELAR</button>
                            <button id="save-new-route-btn" class="bg-[var(--color-secondary)] hover:bg-[#851123] text-white font-bold py-2 px-4 rounded-lg">GUARDAR RUTA</button>
                        </div>
                    </div>
                </div>

                <div id="edit-route-modal" class="hidden fixed inset-0 bg-black bg-opacity-70 overflow-y-auto h-full w-full z-50">
                    <div class="relative mx-auto p-6 border shadow-2xl rounded-xl bg-white max-w-lg mt-[20vh]">
                        <h3 class="text-xl font-black text-[var(--color-primary)] mb-4">EDITAR RUTA</h3>
                        <input type="text" id="edit-route-name" placeholder="Nuevo título para la ruta" class="w-full p-3 border-2 border-gray-300 rounded-lg mb-4">
                        <select id="edit-route-day" class="w-full p-3 border-2 border-gray-300 rounded-lg bg-white mb-6">
                            <option value="">Seleccionar día (Opcional)</option>
                            <option value="Lunes">Lunes</option><option value="Martes">Martes</option><option value="Miércoles">Miércoles</option><option value="Jueves">Jueves</option><option value="Viernes">Viernes</option><option value="Sábado">Sábado</option><option value="Domingo">Domingo</option>
                        </select>
                        <input type="hidden" id="current-edit-route-id">
                        <div class="flex justify-end space-x-3">
                            <button class="close-modal-btn bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 rounded-lg">CANCELAR</button>
                            <button id="save-edit-route-btn" class="bg-[var(--color-secondary)] hover:bg-[#851123] text-white font-bold py-2 px-4 rounded-lg">GUARDAR CAMBIOS</button>
                        </div>
                    </div>
                </div>
                
                <div id="add-client-modal" class="hidden fixed inset-0 bg-black bg-opacity-70 overflow-y-auto h-full w-full z-50">
                    <div class="relative mx-auto p-6 border shadow-2xl rounded-xl bg-white max-w-2xl mt-12">
                        <h3 class="text-2xl font-black text-[var(--color-primary)] mb-4">Agregar Clientes al Panel de Rutas</h3>
                        <div class="relative mb-4">
                            <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                            <input type="text" id="modal-client-search-input" placeholder="Buscar en toda la base de datos de clientes..." class="w-full p-3 pl-10 border-2 border-gray-300 rounded-lg">
                        </div>
                        <div id="modal-search-results" class="space-y-2 max-h-96 overflow-y-auto border rounded-lg p-2 bg-gray-50">
                            <p class="text-center text-gray-500 p-4">Escribe un nombre para buscar clientes.</p>
                        </div>
                        <div class="flex justify-end mt-6">
                            <button class="close-modal-btn bg-gray-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-6 rounded-lg">CERRAR</button>
                        </div>
                    </div>
                </div>
                
<div id="generic-confirm-modal" class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center space-y-0 hidden z-50 font-barlow">
    
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 
                transform transition duration-300 scale-100 text-center">
        
        <div class="flex justify-center mb-4">
            <i data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ACCIÓN</h3>
        
        <p id="confirm-modal-message" class="text-gray-700 mb-6 uppercase font-semibold">
            ¿ESTÁS SEGURO DE QUE DESEAS REALIZAR ESTA ACCIÓN? ESTA ACCIÓN NO SE PUEDE DESHACER.
        </p>
        
        <input type="hidden" id="confirm-action-type">
        <input type="hidden" id="confirm-client-id">
        <input type="hidden" id="confirm-route-id">
        <input type="hidden" id="confirm-week-number">

        <div class="flex flex-col sm:flex-row justify-center space-y-0 sm:space-y-0 sm:space-x-4">
            <button class="close-modal-btn bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto 
                           transition duration-300 transform hover:scale-[1.03] shadow-md hover:shadow-lg">
                CANCELAR
            </button>
            
            <button id="execute-confirm-btn" 
                    class="bg-[var(--color-secondary)] hover:bg-[#8d1124] text-white font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto 
                           transition duration-300 transform hover:scale-[1.03] shadow-lg hover:shadow-xl">
                CONFIRMAR
            </button>
        </div>
    </div>
</div>
                
                
                <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4 mb-6">
                    <div class="bg-white p-2 rounded-lg shadow-md border flex flex-wrap items-center gap-4">
                        <div class="flex items-center gap-2">
                            <span class="font-bold text-sm text-[var(--color-primary)] ml-2">SEMANA:</span>
                            <div id="week-filter-container" class="flex items-center gap-1"></div>
                        </div>
                        <h3 id="week-range-display" class="font-black text-2xl uppercase text-[var(--color-secondary)] pr-2"></h3>
                    </div>
                    <button id="create-route-btn" class="bg-[var(--color-secondary)] text-white font-bold py-3 px-6 rounded-lg shadow-md transition flex items-center justify-center"><i data-lucide="plus-circle" class="w-5 h-5 mr-2"></i> CREAR NUEVA RUTA</button>
                </div>
                
                <div class="grid grid-cols-1 lg:grid-cols-[theme(spacing.96)_1fr] lg:gap-6 space-y-6 lg:space-y-0 pb-6 pt-2">
                    <div id="clients-source-list" class="flex-shrink-0 w-full lg:w-96 bg-white rounded-xl shadow-md p-4 min-h-[70vh] border-l-4 border-[var(--color-highlight)]">
                        <div class="flex justify-between items-center mb-4 border-b pb-2">
                            <h2 class="text-3xl font-black flex items-center text-[var(--color-secondary)]"><i data-lucide="users" class="w-5 h-5 mr-2"></i> PANEL DE RUTAS</h2>
                            <button id="add-client-btn" class="p-2 bg-[var(--color-secondary)] text-white rounded-full hover:bg-[#851123] transition"><i data-lucide="plus" class="w-5 h-5"></i></button>
                        </div>
                        <div class="relative mb-4">
                            <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                            <input type="text" id="client-search-input" placeholder="Filtrar clientes en este panel..." class="w-full p-3 pl-10 border-2 border-gray-300 rounded-lg">
                        </div>
                        <div id="clients-container" class="space-y-4 h-full overflow-y-auto max-h-[calc(100vh-280px)] kanban-list p-1">
                            <p id="clients-placeholder" class="text-sm text-gray-500 italic p-2 bg-gray-100 rounded">Cargando clientes...</p>
                        </div>
                    </div>
                    <div class="min-w-0 w-full"><div id="routes-kanban-container" class="grid grid-cols-1 md:grid-cols-2 gap-6 w-full"></div></div>
                </div>

                 <div class="mt-8 pt-6 border-t-2 border-gray-200">
                    <h3 class="text-3xl font-black text-[var(--color-primary)] mb-6 flex items-center"><i data-lucide="bar-chart-3" class="w-8 h-8 mr-3 text-[var(--color-secondary)]"></i>RESUMEN SEMANA ACTUAL</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 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="route" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Rutas en Semana</h3>
            <p id="summary-routes-count" class="text-5xl font-bold text-[var(--color-primary)]">0</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="clock" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Tiempo Estimado</h3>
            <p id="summary-total-time" class="text-5xl font-bold text-[var(--color-primary)]">0h 0m</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="wallet" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Ingreso en Rutas</h3>
            <p id="summary-total-value" class="text-5xl font-bold text-[var(--color-primary)]">$0.00</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-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">Clientes Asignados</h3>
            <p id="summary-clients-assigned" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
        </div>
    </div>
    
</div>
                </div>
                 <div class="mt-8 pt-6 border-t-2 border-gray-200">
                    <h3 class="text-3xl font-black text-[var(--color-primary)] mb-6 flex items-center"><i data-lucide="calendar-days" class="w-8 h-8 mr-3 text-[var(--color-secondary)]"></i>DESGLOSE DIARIO (SEMANA ACTUAL)</h3>
                    <div id="daily-summary-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-7 gap-4 bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]"></div>
                </div>
            </div>
        </main>
        
<div id="client-detail-panel" 
     class="fixed top-0 right-0 w-full md:w-1/3 h-full z-40 
            transform translate-x-full transition-transform duration-300 
            ease-in-out shadow-2xl overflow-y-auto bg-white">
                <div class="flex flex-col h-full">
                <div class="p-5 bg-gradient-to-r from-[var(--color-primary)] to-[#0f2749] text-white flex-shrink-0" style="padding-top: max(env(safe-area-inset-top), 20px);">
                    <div class="flex justify-between items-center">
                        <h3 class="text-2xl font-black truncate uppercase" id="panel-client-name">Detalles Del Cliente</h3>
                        <button id="close-client-detail-panel" class="p-2 rounded-md hover:bg-white/10 transition">
                            <i data-lucide="x" class="w-6 h-6"></i>
                        </button>
                    </div>
                </div>
                
                <div class="p-6 space-y-6 overflow-y-auto flex-grow">
                    <div class="border p-4 rounded-lg bg-gray-50 shadow-inner">
                        <h4 class="font-black text-lg uppercase text-[var(--color-primary)] flex items-center mb-2"><i data-lucide="info" class="w-4 h-4 mr-2"></i> Información Clave</h4>
                        <p class="text-sm">Dirección: <span id="panel-client-address" class="font-semibold text-gray-700"></span></p>
                        <p class="text-sm mt-1">Valor Servicio: <span id="panel-client-value" class="font-bold text-green-600"></span></p>
                        
                        <h4 class="font-bold text-lg text-[var(--color-primary)] flex items-center mt-4 mb-2"><i data-lucide="clock" class="w-4 h-4 mr-2"></i> Tiempo Estimado</h4>
                        <div class="flex items-center space-x-2">
                            <input type="number" id="input-service-time" class="w-20 p-2 border-2 border-gray-300 rounded-lg text-center" min="0" value="0">
                            <span class="text-gray-600">Minutos</span>
                            <button id="save-service-time-btn" class="btn btn-secondary rounded-lg py-2 px-4 text-sm" disabled>GUARDAR</button>
                        </div>
                        <p id="time-save-status" class="text-xs mt-2 text-[var(--color-secondary)] hidden">Actualizando...</p>
                    </div>

                    <div class="pt-4 border-t">
                        <h4 class="font-black text-lg uppercase text-[var(--color-primary)] flex items-center mb-3"><i data-lucide="briefcase" class="w-4 h-4 mr-2"></i> Servicios Asignados</h4>
                        <div id="panel-assigned-services" class="flex flex-wrap gap-2">
                            <p class="text-sm text-gray-500 italic">Cargando servicios...</p>
                        </div>
                    </div>
                    <div class="pt-4 border-t">
                        <h4 class="font-black text-lg uppercase text-[var(--color-primary)] flex items-center mb-3"><i data-lucide="calendar-check" class="w-4 h-4 mr-2"></i> Citas Recientes</h4>
                        <div id="panel-recent-appointments" class="space-y-3">
                            <p class="text-sm text-gray-500 italic">Cargando citas...</p>
                        </div>
                    </div>
                    <div class="pt-4 border-t">
                        <h4 class="font-black text-lg uppercase text-[var(--color-primary)] flex items-center mb-3"><i data-lucide="file-text" class="w-4 h-4 mr-2"></i> Facturas Pendientes</h4>
                        <div id="panel-pending-invoices" class="space-y-3">
                            <p class="text-sm text-gray-500 italic">Cargando facturas...</p>
                        </div>
                    </div>
                </div>
                <input type="hidden" id="panel-current-client-id">
            </div>
        </div>
    </div>
    
<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- GLOBAL STATE ---
    let draggedItem = null,
        workspaceClients = [],
        masterClientList = [],
        allRoutes = [],
        allAssignments = [],
        selectedWeek = 1;
    let searchTimeout = null;
    const weekStartDates = getDatesForCurrentMonth();
    
    // --- DOM SELECTORS ---
    const clientsContainer = document.getElementById('clients-container');
    const routesContainer = document.getElementById('routes-kanban-container');
    const createRouteModal = document.getElementById('create-route-modal');
    const editRouteModal = document.getElementById('edit-route-modal');
    const addClientModal = document.getElementById('add-client-modal');
    const genericConfirmModal = document.getElementById('generic-confirm-modal');
    const executeConfirmBtn = document.getElementById('execute-confirm-btn');
    const modalClientSearchInput = document.getElementById('modal-client-search-input');
    const modalSearchResults = document.getElementById('modal-search-results');
    const weekFilterContainer = document.getElementById('week-filter-container');
    const weekRangeDisplay = document.getElementById('week-range-display');
    const mainSearchInput = document.getElementById('client-search-input');

    // --- HELPER FUNCTIONS ---
    function showToast(message, type = "success") { const c = document.getElementById("toast-container"), t = document.createElement("div"); t.className = `toast ${"success"===type?"bg-green-500":"bg-[var(--color-secondary)]"} text-white py-2 px-4 rounded-lg shadow-md`, t.textContent = message, c.appendChild(t), setTimeout(() => t.remove(), 4000) }
    function hideAllModals() { [createRouteModal, editRouteModal, addClientModal, genericConfirmModal].forEach(m => m.classList.add("hidden")) }
    function getDatesForCurrentMonth() { let e = new Date, t = e.getFullYear(), o = e.getMonth(), n = { 1: {}, 2: {}, 3: {}, 4: {}, 5: {} }, r = new Date(t, o + 1, 0).getDate(); function a(e) { let t = new Date(e.getFullYear(), e.getMonth(), 1).getDay(); return Math.ceil((e.getDate() + (0 === t ? 6 : t - 1)) / 7) } for (let i = 1; i <= r; i++) { let e = new Date(t, o, i), l = a(e); if (l > 0 && l <= 5) { let t = e.toLocaleDateString("es-ES", { weekday: "long" }); n[l][t.charAt(0).toUpperCase() + t.slice(1)] = e.getDate() } } return n }


    // --- LÓGICA DEL PANEL LATERAL DE DETALLES ---
    const clientDetailPanel = document.getElementById('client-detail-panel');
    const closePanelBtn = document.getElementById('close-client-detail-panel');
    const saveServiceTimeBtn = document.getElementById('save-service-time-btn');
    const inputServiceTime = document.getElementById('input-service-time');
    
    closePanelBtn.addEventListener('click', () => {
        clientDetailPanel.classList.remove('translate-x-0');
        clientDetailPanel.classList.add('translate-x-full');
    });

async function showClientDetails(clientId, clientName) {
        document.getElementById('panel-client-name').textContent = clientName;
        document.getElementById('panel-current-client-id').value = clientId;
        clientDetailPanel.classList.add('translate-x-0');
        clientDetailPanel.classList.remove('translate-x-full');
        saveServiceTimeBtn.disabled = true;

        // Mostrar placeholders de carga
        document.getElementById('panel-client-address').textContent = 'Cargando...';
        document.getElementById('panel-client-value').textContent = 'Cargando...';
        inputServiceTime.value = 0;
        document.getElementById('panel-assigned-services').innerHTML = '<p class="text-sm text-gray-500 italic">Cargando servicios...</p>';
        document.getElementById('panel-recent-appointments').innerHTML = '<p class="text-sm text-gray-500 italic">Cargando citas...</p>';
        document.getElementById('panel-pending-invoices').innerHTML = '<p class="text-sm text-gray-500 italic">Cargando facturas...</p>';
        document.getElementById('time-save-status').classList.add('hidden');
        
        try {
            const response = await fetch(`db/client-route-details-read.php?client_id=${clientId}`);
            const data = await response.json();

            if (data.status === 'success' && data.client) {
                const client = data.client;
                
                // Actualizar info principal: USA full_address y el valor CALCULADO
                document.getElementById('panel-client-address').textContent = client.full_address; 
                document.getElementById('panel-client-value').textContent = `$${data.total_service_value}`; // <-- USA EL VALOR CALCULADO
                inputServiceTime.value = client.service_time || 0;
                saveServiceTimeBtn.disabled = false;
                inputServiceTime.dataset.initialValue = client.service_time || 0;

                // Renderizar Servicios Asignados
                const servicesContainer = document.getElementById('panel-assigned-services');
                servicesContainer.innerHTML = '';
                if (data.services && data.services.length > 0) {
                    data.services.forEach(serviceName => {
                        servicesContainer.innerHTML += `<span class="inline-block bg-[var(--color-primary)] text-white text-xs font-semibold px-2.5 py-0.5 rounded-full mr-2 mb-1">${serviceName}</span>`;
                    });
                } else {
                    servicesContainer.innerHTML = '<p class="text-sm text-gray-500 italic">No hay servicios principales asignados.</p>';
                }

                // Renderizar Citas
                const apptContainer = document.getElementById('panel-recent-appointments');
                apptContainer.innerHTML = '';
                if (data.appointments.length > 0) {
                    data.appointments.forEach(appt => {
                        const statusClass = appt.status === 'confirmed' ? 'bg-blue-100 text-blue-800' : 
                                            appt.status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-[var(--color-secondary)] text-white';
                        apptContainer.innerHTML += `
                            <div class="flex justify-between items-center text-sm border-b pb-1">
                                <span class="font-semibold">${appt.appointment_date} ${appt.appointment_time.substring(0, 5)}</span>
                                <span class="px-2 py-0.5 rounded-full text-xs font-medium ${statusClass}">${appt.status.toUpperCase()}</span>
                            </div>
                        `;
                    });
                } else {
                    apptContainer.innerHTML = '<p class="text-sm text-gray-500 italic">No hay citas recientes (últimos 30 días).</p>';
                }

                // Renderizar Facturas
                const invoiceContainer = document.getElementById('panel-pending-invoices');
                invoiceContainer.innerHTML = '';
                if (data.invoices.length > 0) {
                    data.invoices.forEach(inv => {
                        invoiceContainer.innerHTML += `
                            <div class="flex justify-between items-center text-sm border-b pb-1">
                                <span class="font-semibold">${inv.external_id} (${inv.invoice_date})</span>
                                <span class="font-bold text-[var(--color-secondary)]">$${parseFloat(inv.total_amount).toFixed(2)}</span>
                            </div>
                        `;
                    });
                } else {
                    invoiceContainer.innerHTML = '<p class="text-sm text-gray-500 italic">No hay facturas pendientes (estado: enviada).</p>';
                }

            } else {
                showToast(data.message || 'Error al cargar detalles del cliente.', 'error');
            }
        } catch (error) {
            showToast('Error de conexión al obtener detalles.', 'error');
        }
        lucide.createIcons();
    }
    
    // Escuchador de eventos para el input de tiempo
    inputServiceTime.addEventListener('input', (e) => {
        const value = parseInt(e.target.value);
        const initialValue = parseInt(e.target.dataset.initialValue);
        // Habilitar el botón si el valor ha cambiado y es un número no negativo
        saveServiceTimeBtn.disabled = isNaN(value) || value < 0 || value === initialValue;
    });

    // Escuchador de eventos para guardar el tiempo de servicio
    saveServiceTimeBtn.addEventListener('click', async () => {
        const clientId = document.getElementById('panel-current-client-id').value;
        const newTime = parseInt(inputServiceTime.value);
        
        if (isNaN(newTime) || newTime < 0) {
            showToast('Ingresa un tiempo válido en minutos.', 'error');
            return;
        }

        document.getElementById('time-save-status').textContent = 'Guardando...';
        document.getElementById('time-save-status').classList.remove('hidden', 'text-[var(--color-secondary)]', 'text-green-600');
        document.getElementById('time-save-status').classList.add('text-[var(--color-secondary)]');
        saveServiceTimeBtn.disabled = true;

        const formData = new FormData();
        formData.append('client_id', clientId);
        formData.append('service_time', newTime);

        try {
            // Asegúrate de que 'db/routes-update-client-time.php' exista y funcione.
            const response = await fetch('db/routes-update-client-time.php', { method: 'POST', body: formData });
            const result = await response.json();

            if (result.status === 'success') {
                // 1. Actualizar el estado visual en el panel
                document.getElementById('time-save-status').textContent = '¡Guardado! Actualizando panel de rutas...';
                
                // 2. Actualizar la lista maestra en el JS para reflejar el cambio en los KPIs.
                const clientIndex = masterClientList.findIndex(c => String(c.id) === clientId);
                if (clientIndex !== -1) {
                    masterClientList[clientIndex].service_time = newTime;
                }
                
                // 3. Re-calcular todos los resúmenes y KPIs de las rutas.
                updateAllSummariesForCurrentWeek();
                
                // 4. Finalizar
                inputServiceTime.dataset.initialValue = newTime;
                document.getElementById('time-save-status').textContent = '¡Tiempo de servicio actualizado con éxito!';
                document.getElementById('time-save-status').classList.remove('text-[var(--color-secondary)]');
                document.getElementById('time-save-status').classList.add('text-green-600');
                
                // Ocultar el mensaje después de un tiempo
                setTimeout(() => {
                    document.getElementById('time-save-status').classList.add('hidden');
                }, 3000);
            } else {
                showToast(result.message, 'error');
                document.getElementById('time-save-status').textContent = 'Error al guardar.';
                document.getElementById('time-save-status').classList.remove('text-[var(--color-secondary)]', 'text-green-600');
                document.getElementById('time-save-status').classList.add('text-[var(--color-secondary)]');
            }
        } catch (err) {
            showToast('Error de conexión al guardar el tiempo.', 'error');
            document.getElementById('time-save-status').textContent = 'Error de conexión.';
            document.getElementById('time-save-status').classList.remove('text-[var(--color-secondary)]', 'text-green-600');
            document.getElementById('time-save-status').classList.add('text-[var(--color-secondary)]');
        }
    });

    // --- LÓGICA DE CONFIRMACIÓN PERSONALIZADA ---
    function showCustomConfirm(message, actionType, data = {}) {
        document.getElementById('confirm-modal-message').textContent = message;
        document.getElementById('confirm-action-type').value = actionType;
        document.getElementById('confirm-client-id').value = data.clientId || '';
        document.getElementById('confirm-route-id').value = data.routeId || '';
        document.getElementById('confirm-week-number').value = data.weekNumber || '';
        genericConfirmModal.classList.remove('hidden');
    }

    executeConfirmBtn.addEventListener('click', async () => {
        const actionType = document.getElementById('confirm-action-type').value;
        const clientId = document.getElementById('confirm-client-id').value;
        const routeId = document.getElementById('confirm-route-id').value;
        const weekNumber = document.getElementById('confirm-week-number').value;
        
        hideAllModals();

        if (actionType === 'remove_client_from_route') {
            await handleClientAssignment(clientId, routeId, weekNumber, "delete");
            
        } else if (actionType === 'remove_client_from_workspace') {
            const cardToRemove = document.querySelector(`#clients-container .client-card[data-client-id="${clientId}"]`);
            await handleWorkspaceClient(clientId, "delete", cardToRemove);

        } else if (actionType === 'delete_route') {
            const routeColumn = document.querySelector(`.route-column[data-route-id="${routeId}"]`);
            if (routeColumn) {
                const formData = new FormData();
                formData.append("route_id", routeId);
                try { 
                    const response = await fetch("db/routes-delete.php", { method: "POST", body: formData });
                    const result = await response.json(); 
                    if(result.status === 'success') { 
                        showToast(result.message); 
                        routeColumn.remove();
                        allRoutes = allRoutes.filter(r => String(r.id) !== routeId); 
                        allAssignments = allAssignments.filter(a => String(a.route_id) !== routeId); 
                        updateAllSummariesForCurrentWeek(); 
                    } else { 
                        showToast(result.message, "error"); 
                    } 
                } catch (err) { 
                    showToast("Error de conexión.", "error"); 
                }
            }
        }
    });

    // --- UI RENDERING ---
    function createClientCard(client, isInstance = false, routeId = 0, weekNumber = 0) {
        const card = document.createElement("div");
        card.className = `client-card group p-3 rounded-lg shadow-sm transition duration-150 ease-in-out border-l-4 ${isInstance ? "border-[var(--color-secondary)] bg-white" : "border-gray-300 bg-gray-50"} transform hover:scale-[1.02] hover:shadow-md cursor-grab`;
        card.setAttribute("draggable", true);
        card.dataset.clientId = client.id;
        
        const removeFromRouteBtn = isInstance ? `<button class="remove-client-from-route-btn absolute top-0 right-8 text-gray-400 hover:text-[var(--color-secondary)] group-hover:opacity-100 p-1" data-client-id="${client.id}" data-route-id="${routeId}" data-week-number="${weekNumber}"><i data-lucide="trash-2" class="w-5 h-5"></i></button>` : "";
        const removeFromWorkspaceBtn = !isInstance ? `<button class="remove-client-from-workspace-btn absolute top-0 right-6 text-gray-400 hover:text-[var(--color-secondary)] group-hover:opacity-100 p-1" data-client-id="${client.id}"><i data-lucide="trash-2" class="w-5 h-5"></i></button>` : "";

        card.innerHTML = `<div class="relative flex justify-between items-center">${removeFromRouteBtn}${removeFromWorkspaceBtn}<div class="font-bold text-gray-800 truncate pr-8">${client.name}</div><button class="toggle-client-details p-1 text-gray-500 hover:text-[var(--color-secondary)] transition"><i data-lucide="square-chevron-down" class="w-5 h-5"></i></button></div><div class="collapsible-details hidden mt-2 pt-2 border-t border-gray-200"><div class="text-xs text-gray-500 flex items-center mt-1"><i data-lucide="map-pin" class="w-3 h-3 mr-1.5 flex-shrink-0"></i> ${client.address || "Sin dirección"}</div><div class="text-xs font-semibold mt-1 text-[var(--color-primary)]"><i data-lucide="briefcase" class="w-3 h-3 mr-1.5 inline-block"></i> ${client.service || "SIN SERVICIO"}</div></div>`;
        
        card.querySelector(".toggle-client-details")?.addEventListener("click", e => { e.stopPropagation(); let d = card.querySelector(".collapsible-details"), i = e.currentTarget.querySelector("i"); d.classList.toggle("hidden"), i.setAttribute("data-lucide", d.classList.contains("hidden") ? "square-chevron-down" : "chevron-up"), lucide.createIcons() });
        
        card.querySelector(".remove-client-from-route-btn")?.addEventListener("click", e => { 
            e.stopPropagation(); 
            const { clientId, routeId, weekNumber } = e.currentTarget.dataset; 
            showCustomConfirm("¿Quitar este cliente de la ruta?", 'remove_client_from_route', { clientId, routeId, weekNumber });
        });

        card.querySelector(".remove-client-from-workspace-btn")?.addEventListener("click", e => { 
            e.stopPropagation(); 
            const clientId = e.currentTarget.dataset.clientId;
            const clientName = client.name;
            showCustomConfirm(`¿Quitar a ${clientName} del panel? No se borrará del CRM.`, 'remove_client_from_workspace', { clientId });
        });

        card.addEventListener("click", (e) => {
            // Se asegura de que no se abra el panel si se hizo clic en un botón (eliminar/toggle).
            if (!e.target.closest('button')) {
                const clientData = masterClientList.find(c => String(c.id) === card.dataset.clientId);
                if (clientData) {
                    showClientDetails(card.dataset.clientId, clientData.name);
                } else {
                    showClientDetails(card.dataset.clientId, client.name);
                }
            }
        });

        card.addEventListener("dragstart", handleDragStart);
        card.addEventListener("dragend", handleDragEnd);
        return card;
    }

    function addRouteColumn(route) {
        const column = document.createElement("div");
        column.className = "route-column bg-white rounded-xl shadow-md p-4 h-full border-l-4 border-[var(--color-primary)] flex flex-col";
        column.dataset.routeId = route.id;
        column.innerHTML = `<div class="flex-shrink-0"><div class="flex justify-between items-start mb-4 border-b pb-2"><div class="flex items-start flex-col"><div class="flex items-center"><h2 id="route-title-${route.id}" class="text-2xl font-black text-[var(--color-primary)] mr-2 cursor-grab">${route.route_name.toUpperCase()}</h2><button class="text-[var(--color-secondary)] hover:text-gray-800 edit-route-btn" data-route-id="${route.id}"><i data-lucide="pencil" class="w-4 h-4"></i></button></div><p id="route-day-${route.id}" class="text-sm font-bold uppercase text-gray-500 flex items-center">${route.route_day || "SIN DÍA"}</p></div><button class="text-[var(--color-secondary)] hover:text-[var(--color-secondary)] delete-route-btn" data-route-id="${route.id}"><i data-lucide="trash-2" class="w-5 h-5"></i></button></div></div><div id="route-list-${route.id}" class="space-y-4 kanban-list p-1 flex-grow overflow-y-auto min-h-[200px]" data-route-id="${route.id}"><p class="text-sm text-gray-500 italic p-2 bg-gray-100 rounded">Arrastra Clientes Aquí</p></div><div class="mt-4 pt-2 border-t text-xs flex-shrink-0"><div class="flex justify-between items-center text-gray-600"><span class="font-bold">Clientes:</span><span id="kpi-clients-${route.id}" class="font-semibold bg-gray-200 text-gray-800 px-2 py-0.5 rounded-full">0</span></div><div class="flex justify-between items-center text-gray-600 mt-1"><span class="font-bold">Tiempo Estimado:</span><span id="kpi-time-${route.id}" class="font-semibold">0h 0m</span></div><div class="flex justify-between items-center text-[var(--color-primary)] mt-1"><span class="font-bold">Valor Total:</span><span id="kpi-value-${route.id}" class="font-black text-base">$0.00</span></div></div>`;
        routesContainer.appendChild(column);
        
        const listEl = column.querySelector(".kanban-list");
        listEl.addEventListener("dragover", handleDragOver);
        listEl.addEventListener("drop", handleDrop);

        new Sortable(listEl, {
            group: 'clients',
            animation: 150,
            onAdd: (evt) => {
                const clientId = evt.item.dataset.clientId;
                handleClientAssignment(clientId, route.id, selectedWeek, "create");
            },
            onUpdate: (evt) => {
                const clientIds = Array.from(evt.target.children).map(card => card.dataset.clientId);
                handleClientOrderUpdate(route.id, clientIds);
            }
        });

        column.querySelector(".edit-route-btn").addEventListener("click", e => { const routeId = e.currentTarget.dataset.routeId, routeData = allRoutes.find(r => String(r.id) === routeId); if(routeData){document.getElementById("edit-route-name").value = routeData.route_name; document.getElementById("edit-route-day").value = routeData.route_day || ""; document.getElementById("current-edit-route-id").value = routeData.id; editRouteModal.classList.remove("hidden");} });
        
        column.querySelector(".delete-route-btn").addEventListener("click", e => { 
            const routeId = e.currentTarget.dataset.routeId; 
            showCustomConfirm("¿Eliminar esta ruta? Esta acción eliminará todas las asignaciones de esta ruta en la semana actual y no se puede deshacer.", 'delete_route', { routeId });
        });
    }
    
    function renderRoutesForWeek(weekNum) {
    routesContainer.innerHTML = '';
    const weekRoutes = allRoutes.filter(r => String(r.week_number) === String(weekNum));
    
    if (weekRoutes.length === 0) {
        // Bloque de contenido para "No hay rutas": Cumple con branding y centrado.
        routesContainer.innerHTML = `
            <div class="col-span-1 md:col-span-2 flex flex-col items-center justify-center p-12 bg-white rounded-xl shadow-lg border-2 border-dashed border-gray-300 min-h-[40vh] space-y-4">
                
                <i data-lucide="map-pin-off" class="w-16 h-16 text-[var(--color-secondary)]"></i>
                
                <h4 class="text-3xl font-black text-[var(--color-primary)] uppercase text-center">
                    SIN RUTAS ASIGNADAS
                </h4>
                
                <p class="text-lg text-gray-600 text-center max-w-lg">
                    No hay rutas estratégicas creadas para la <span class="font-bold text-[var(--color-highlight)]">SEMANA ${weekNum}</span>.
                    Utilice el botón "CREAR NUEVA RUTA" para empezar a optimizar los desplazamientos de su equipo.
                </p>

                <button class="bg-gray-100 text-[var(--color-primary)] font-bold py-2 px-4 rounded-lg mt-4 cursor-default uppercase">
                    <i data-lucide="route" class="w-4 h-4 mr-2 inline"></i> ¡COMIENCE A PLANIFICAR!
                </button>
            </div>
        `;
        // Nota: Es crucial volver a llamar a lucide.createIcons() si inyectamos nuevos iconos
        lucide.createIcons();
        
    } else {
        weekRoutes.forEach(route => addRouteColumn(route));
    }
    
    renderAssignmentsForWeek(weekNum);
}

    function renderAssignmentsForWeek(weekNum) {
        document.querySelectorAll('.route-column .client-card').forEach(card => card.remove());
        document.querySelectorAll('.route-column .kanban-list').forEach(list => { if (list.children.length === 0) list.innerHTML = '<p class="text-sm text-gray-500 italic p-2 bg-gray-100 rounded">Arrastra Clientes Aquí</p>'; });
        const weekAssignments = allAssignments.filter(a => String(a.week_number) === String(weekNum));
        
        const assignmentsByRoute = weekAssignments.reduce((acc, assignment) => {
            if (!acc[assignment.route_id]) acc[assignment.route_id] = [];
            acc[assignment.route_id].push(assignment);
            return acc;
        }, {});

        Object.keys(assignmentsByRoute).forEach(routeId => {
            const routeList = document.getElementById(`route-list-${routeId}`);
            if (routeList) {
                routeList.querySelector('p.italic')?.remove();
                
                assignmentsByRoute[routeId].forEach(assignment => {
                    const client = masterClientList.find(c => String(c.id) === String(assignment.client_id));
                    if (client) {
                        routeList.appendChild(createClientCard(client, true, assignment.route_id, assignment.week_number));
                    }
                });
            }
        });
        
        lucide.createIcons();
        updateAllSummariesForCurrentWeek();
    }

    function updateAllSummariesForCurrentWeek() {
        updateGlobalSummary();
        updateDailySummary();
        updateWeekDisplay();
    }

    function updateGlobalSummary() {
        let routesCount = document.querySelectorAll("#routes-kanban-container .route-column").length;
        document.getElementById("summary-routes-count").textContent = routesCount;
        let clientsCount = 0, totalTime = 0, totalValue = 0;
        document.querySelectorAll(".route-column .client-card").forEach(card => {
            clientsCount++;
            const clientData = masterClientList.find(c => String(c.id) === card.dataset.clientId);
            if (clientData) { totalTime += parseFloat(clientData.service_time) || 0; totalValue += parseFloat(clientData.service_value) || 0; }
        });
        const hours = Math.floor(totalTime / 60), minutes = totalTime % 60;
        document.getElementById("summary-clients-assigned").textContent = clientsCount;
        document.getElementById("summary-total-time").textContent = `${hours}h ${minutes}m`;
        document.getElementById("summary-total-value").textContent = `$${totalValue.toFixed(2)}`;
        document.querySelectorAll(".route-column").forEach(col => updateRouteKPIs(col.dataset.routeId));
    }

    function updateRouteKPIs(routeId) {
        const routeList = document.getElementById(`route-list-${routeId}`);
        if (!routeList) return;
        const clientCards = routeList.querySelectorAll(".client-card"), clientCount = clientCards.length;
        let totalTime = 0, totalValue = 0;
        clientCards.forEach(card => {
            const clientData = masterClientList.find(c => String(c.id) === String(card.dataset.clientId));
            if (clientData) { totalTime += parseFloat(clientData.service_time) || 0; totalValue += parseFloat(clientData.service_value) || 0; }
        });
        const hours = Math.floor(totalTime / 60), minutes = totalTime % 60;
        document.getElementById(`kpi-clients-${routeId}`).textContent = clientCount;
        document.getElementById(`kpi-time-${routeId}`).textContent = `${hours}h ${minutes}m`;
        document.getElementById(`kpi-value-${routeId}`).textContent = `$${totalValue.toFixed(2)}`;
    }

    function updateDailySummary() {
        const daysOfWeek = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"];
        const dailyData = daysOfWeek.reduce((acc, day) => ({...acc, [day]: { value: 0, time: 0 }}), {});
        document.querySelectorAll(".route-column").forEach(routeColumn => {
            const routeData = allRoutes.find(r => String(r.id) === String(routeColumn.dataset.routeId));
            if (routeData) {
                const dayName = daysOfWeek.find(d => (routeData.route_day || "").toLowerCase() === d.toLowerCase());
                if (dayName) {
                    routeColumn.querySelectorAll(".client-card").forEach(clientCard => {
                        const clientData = masterClientList.find(c => String(c.id) === clientCard.dataset.clientId);
                        if (clientData) {
                            dailyData[dayName].value += parseFloat(clientData.service_value) || 0;
                            dailyData[dayName].time += parseFloat(clientData.service_time) || 0;
                        }
                    });
                }
            }
        });
        const maxValue = Math.max(0, ...Object.values(dailyData).map(d => d.value));
        document.getElementById("daily-summary-container").innerHTML = daysOfWeek.map(day => {
            const data = dailyData[day], hours = Math.floor(data.time / 60), minutes = data.time % 60;
            const isTopDay = data.value > 0 && data.value === maxValue;
            return `<div class="daily-summary-card p-4 rounded-xl shadow-md transition flex flex-col justify-between min-h-[120px] ${isTopDay ? "bg-yellow-50 border-2 border-[var(--color-highlight)]" : "bg-white border"}"><div><p class="font-black text-lg text-[var(--color-primary)] uppercase">${day}</p></div><div class="text-right"><p class="font-bold text-2xl text-[var(--color-primary)]">$${data.value.toFixed(2)}</p><p class="text-sm text-gray-500 font-semibold">${hours}h ${minutes}m</p></div></div>`;
        }).join("");
    }
    
    function handleDragStart(e) { draggedItem = e.target; setTimeout(() => e.target.classList.add("opacity-50"), 0) }
    function handleDragEnd(e) { if(draggedItem) draggedItem.classList.remove("opacity-50"); draggedItem = null }
    function handleDragOver(e) { e.preventDefault() }
    
    function handleDrop(e) { 
        e.preventDefault(); 
        const list = e.target.closest(".kanban-list"); 
        if (list && draggedItem) { 
            const clientId = draggedItem.dataset.clientId, 
                  routeId = list.dataset.routeId; 
            if (routeId) {
                handleClientAssignment(clientId, routeId, selectedWeek, "create"); 
            }
        } 
    }

    async function handleWorkspaceClient(clientId, action, element = null) {
        const url = action === 'create' ? 'db/routes-workspace-create.php' : 'db/routes-workspace-delete.php';
        const formData = new FormData();
        formData.append('client_id', clientId);
        try {
            const response = await fetch(url, { method: 'POST', body: formData });
            const result = await response.json();
            if (result.status === 'success') {
                showToast(result.message);
                if (action === 'create') {
                    const clientData = masterClientList.find(c => String(c.id) === clientId);
                    if (clientData && !workspaceClients.some(c => String(c.id) === clientId)) {
                        workspaceClients.push(clientData);
                        clientsContainer.querySelector('#clients-placeholder')?.remove();
                        clientsContainer.appendChild(createClientCard(clientData));
                        lucide.createIcons();
                    }
                } else if (action === 'delete') {
                    workspaceClients = workspaceClients.filter(c => String(c.id) !== clientId);
                    if (element) element.remove();
                    if (workspaceClients.length === 0) {
                        clientsContainer.innerHTML = '<p id="clients-placeholder" class="text-sm text-gray-500 italic p-2 bg-gray-100 rounded">Usa el botón + para agregar clientes.</p>';
                    }
                }
            } else { showToast(result.message, 'error'); }
            return result.status === 'success';
        } catch(err) { showToast('Error de conexión.', 'error'); return false; }
    }

    async function handleClientAssignment(clientId, routeId, weekNumber, action) {
        const isAlreadyAssigned = allAssignments.some(a => 
            String(a.client_id) === String(clientId) && 
            String(a.route_id) === String(routeId) && 
            String(a.week_number) === String(weekNumber)
        );

        if (action === 'create' && isAlreadyAssigned) {
            showToast('El cliente ya está asignado a esta ruta en esta semana.', 'error');
            return;
        }
        
        const url = action === 'create' ? 'db/routes-clients-create.php' : 'db/routes-clients-delete.php';
        const formData = new FormData();
        formData.append('client_id', clientId);
        formData.append('route_id', routeId);
        formData.append('week_number', weekNumber);
        
        try {
            const response = await fetch(url, { method: 'POST', body: formData });
            const result = await response.json();
            
            if (result.status === 'success') {
                showToast(result.message);
                if (action === 'create') {
                    allAssignments.push({ client_id: clientId, route_id: routeId, week_number: weekNumber });
                    
                    const client = masterClientList.find(c => String(c.id) === clientId);
                    const routeList = document.getElementById(`route-list-${routeId}`);
                    if (client && routeList) {
                        routeList.querySelector('p.italic')?.remove();
                        routeList.appendChild(createClientCard(client, true, routeId, weekNumber));
                        lucide.createIcons();
                    }
                } else if (action === 'delete') {
                    allAssignments = allAssignments.filter(a => !(String(a.client_id) === clientId && String(a.route_id) === routeId && String(a.week_number) === weekNumber));
                    renderAssignmentsForWeek(selectedWeek);
                }
                updateAllSummariesForCurrentWeek();
            } else {
                showToast(result.message, 'error');
                renderAssignmentsForWeek(selectedWeek);
            }
        } catch(err) { 
            showToast('Error de conexión.', 'error'); 
            renderAssignmentsForWeek(selectedWeek); 
        }
    }

    async function handleClientOrderUpdate(routeId, clientIds) {
        const formData = new FormData();
        formData.append('route_id', routeId);
        clientIds.forEach(id => formData.append('client_ids[]', id));
        try {
            await fetch('db/routes-clients-update-order.php', { method: 'POST', body: formData });
        } catch (err) { showToast('Error al guardar el orden.', 'error'); }
    }
    
    function createWeekFilters() {
        if (!weekFilterContainer) return;
        weekFilterContainer.innerHTML = "";
        for (let week = 1; week <= 5; week++) {
            if (weekStartDates[week] && Object.keys(weekStartDates[week]).length > 0) {
                const button = document.createElement("button");
                button.className = "week-filter-btn px-4 py-2 text-sm font-bold rounded-lg transition";
                button.dataset.week = week;
                button.textContent = week;
                button.addEventListener("click", async () => {
                    selectedWeek = week;
                    
                    document.querySelectorAll(".week-filter-btn").forEach(btn => {
                        btn.classList.remove("bg-[var(--color-secondary)]", "text-white");
                        btn.classList.add("bg-gray-200", "text-gray-700");
                    });
                    button.classList.remove("bg-gray-200", "text-gray-700");
                    button.classList.add("bg-[var(--color-secondary)]", "text-white");
                    
                    await loadRoutesAndAssignmentsForWeek(selectedWeek);
                });
                weekFilterContainer.appendChild(button);
            }
        }
        weekFilterContainer.querySelector(`[data-week='${selectedWeek}']`)?.click();
    }

    async function loadRoutesAndAssignmentsForWeek(weekNum) {
        try {
            // Verifica la ruta de este archivo: 'db/routes-read.php'
            const response = await fetch(`db/routes-read.php?week=${weekNum}`);
            const data = await response.json();
            if (data.status === 'success') {
                allRoutes = data.routes || [];
                allAssignments = data.assignments || [];
                renderRoutesForWeek(weekNum);
            } else { 
                showToast(`Error al cargar datos de la semana: ${data.message}`, 'error'); 
            }
        } catch (error) { 
            showToast("Error de conexión al cargar datos de la semana.", 'error'); 
        }
    }


    function updateWeekDisplay() {
        weekRangeDisplay.textContent = ((week) => { if (!weekStartDates[week]) return ""; const dates = Object.values(weekStartDates[week]).filter(Boolean); if (dates.length === 0) return ""; const min = Math.min(...dates), max = Math.max(...dates); return `Del ${min} al ${max} de ${new Date().toLocaleDateString("es-ES",{month:"long"})}` })(selectedWeek);
        document.querySelectorAll(".route-column").forEach(col => {
            const routeId = col.dataset.routeId, routeData = allRoutes.find(r => String(r.id) === routeId);
            if (routeData) {
                const dayEl = document.getElementById(`route-day-${routeId}`);
                if (dayEl) {
                    const dateNum = weekStartDates[selectedWeek] ? weekStartDates[selectedWeek][routeData.route_day] : "";
                    const dayName = routeData.route_day || "SIN DÍA";
                    const dateBadge = dateNum ? `<span class="ml-2 font-bold text-[var(--color-highlight)] bg-gray-100 px-2 rounded-md">${dateNum}</span>` : "";
                    dayEl.innerHTML = `${dayName}${dateBadge}`;
                }
            }
        });
    }

    mainSearchInput.addEventListener("input", e => {
        let term = e.target.value.toLowerCase().trim();
        clientsContainer.querySelectorAll(".client-card").forEach(card => {
            const isVisible = card.querySelector(".font-bold").textContent.toLowerCase().includes(term);
            card.style.display = isVisible ? "block" : "none";
        });
    });

    document.getElementById("add-client-btn").addEventListener("click", () => {
        modalClientSearchInput.value = "";
        modalSearchResults.innerHTML = '<p class="text-center text-gray-500 p-4">Escribe un nombre para buscar clientes.</p>';
        addClientModal.classList.remove("hidden");
        modalClientSearchInput.focus();
    });

    modalClientSearchInput.addEventListener("input", e => {
        clearTimeout(searchTimeout);
        const term = e.target.value.trim();
        if (term.length < 2) {
            modalSearchResults.innerHTML = '<p class="text-center text-gray-500 p-4">Escribe al menos 2 letras.</p>';
            return;
        }
        searchTimeout = setTimeout(async () => {
            modalSearchResults.innerHTML = '<p class="text-center text-gray-500 p-4">Buscando...</p>';
            try {
                const response = await fetch(`db/routes-search-clients.php?term=${encodeURIComponent(term)}`);
                const results = await response.json();
                modalSearchResults.innerHTML = "";
                if (results.length === 0) {
                    modalSearchResults.innerHTML = '<p class="text-center text-gray-500 p-4">No se encontraron resultados.</p>';
                } else {
                    results.forEach(client => {
                        const isAlreadyInWorkspace = workspaceClients.some(c => String(c.id) === String(client.id));
                        const resultDiv = document.createElement('div');
                        resultDiv.className = 'flex justify-between items-center p-2 rounded-lg';
                        resultDiv.innerHTML = `<div><div class="font-bold text-gray-800">${client.name}</div><div class="text-sm text-gray-500">${client.address || 'Sin dirección'}</div></div><button data-client-id="${client.id}" class="add-client-from-modal-btn p-2 text-white rounded-md ${isAlreadyInWorkspace ? 'bg-green-600' : 'bg-[var(--color-secondary)] hover:bg-[#851123]'}" ${isAlreadyInWorkspace ? 'disabled' : ''}><i data-lucide="${isAlreadyInWorkspace ? 'check' : 'plus'}" class="w-5 h-5"></i></button>`;
                        modalSearchResults.appendChild(resultDiv);
                        if (!isAlreadyInWorkspace) {
                            resultDiv.querySelector('.add-client-from-modal-btn').addEventListener('click', async (e) => {
                                const button = e.currentTarget;
                                const success = await handleWorkspaceClient(client.id, 'create');
                                if (success) {
                                    button.innerHTML = '<i data-lucide="check" class="w-5 h-5"></i>';
                                    button.disabled = true;
                                    button.classList.remove('bg-[var(--color-secondary)]', 'hover:bg-[#851123]');
                                    button.classList.add('bg-green-600');
                                    lucide.createIcons();
                                }
                            });
                        }
                    });
                    lucide.createIcons();
                }
            } catch (error) { showToast("Error de conexión al buscar.", "error"); }
        }, 300);
    });

    document.getElementById("create-route-btn").addEventListener("click", () => { document.getElementById("modal-week-number").textContent = selectedWeek, createRouteModal.classList.remove("hidden") });
    document.querySelectorAll(".close-modal-btn").forEach(btn => btn.addEventListener("click", hideAllModals));
    document.getElementById("save-new-route-btn").addEventListener("click", async () => { const name = document.getElementById("new-route-name").value.trim(), day = document.getElementById("new-route-day").value; if (!name) return showToast("El nombre de la ruta es obligatorio.", "error"); const formData = new FormData(); formData.append("route_name", name); formData.append("route_day", day); formData.append("week_number", selectedWeek); try { const response = await fetch("db/routes-create.php", { method: "POST", body: formData }); const result = await response.json(); if (result.status === 'success' && result.new_route) { showToast(result.message); allRoutes.push(result.new_route); renderRoutesForWeek(selectedWeek); hideAllModals(); } else { showToast(result.message, "error"); } } catch (err) { showToast("Error de conexión.", "error"); } });
    document.getElementById("save-edit-route-btn").addEventListener("click", async () => { const id = document.getElementById("current-edit-route-id").value, name = document.getElementById("edit-route-name").value.trim(), day = document.getElementById("edit-route-day").value, route = allRoutes.find(r => String(r.id) === String(id)); if (!route || !name) return showToast("El nombre es obligatorio.", "error"); const formData = new FormData(); formData.append("route_id", id); formData.append("route_name", name); formData.append("route_day", day); try { const response = await fetch("db/routes-update.php", { method: "POST", body: formData }); const result = await response.json(); if (result.status === 'success') { showToast(result.message); route.route_name = name; route.route_day = day; document.getElementById(`route-title-${id}`).textContent = name.toUpperCase(); updateWeekDisplay(); hideAllModals(); } else { showToast(result.message, "error"); } } catch (err) { showToast("Error de conexión.", "error"); } });

    async function loadInitialData() {
        try {
            // La petición AJAX a 'db/routes-read.php' debe devolver un JSON exitoso.
            const response = await fetch(`db/routes-read.php?week=${selectedWeek}`);
            const data = await response.json();
            if (data.status === 'success') {
                allRoutes = data.routes || [];
                masterClientList = data.master_client_list || [];
                workspaceClients = data.workspace_clients || [];
                allAssignments = data.assignments || [];

                clientsContainer.innerHTML = "";
                if (workspaceClients.length > 0) {
                    // Carga los clientes en el panel, usando la función CORREGIDA.
                    workspaceClients.forEach(client => clientsContainer.appendChild(createClientCard(client)));
                } else {
                    clientsContainer.innerHTML = '<p id="clients-placeholder" class="text-sm text-gray-500 italic p-2 bg-gray-100 rounded">Usa el botón + para agregar clientes.</p>';
                }
                lucide.createIcons();

                createWeekFilters();
                
                new Sortable(routesContainer, { 
                    group: 'routes',
                    animation: 150, 
                    handle: 'h2', 
                    onEnd: function (evt) { 
                        const routeIds = Array.from(routesContainer.children).map(col => col.dataset.routeId);
                        const formData = new FormData(); 
                        routeIds.forEach(id => formData.append('route_ids[]', id));
                        fetch('db/routes-save-order.php', { method: 'POST', body: formData });
                    } 
                });
            } else { 
                showToast(`Error al cargar: ${data.message}`, 'error'); 
            }
        } catch (error) { 
            showToast("Error de conexión al cargar datos iniciales. Revisa 'db/routes-read.php' en tu servidor.", 'error'); 
        }
    }
    
    loadInitialData();
});
</script>
</body>
</html>