<?php include 'files/guardiankey.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Dashboard | Inicio | OrozDesign Multiemdia</title>
    <meta name="description" content="Accede a tu panel de tareas en LocalCRM: revisa, organiza y completa tus actividades diarias para mantener tu flujo de trabajo siempre al día">
    <meta name="robots" content="noindex, nofollow">

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

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"> <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    
    <style>
        .off-canvas-panel {
            position: fixed;
            top: 0;
            right: 0;
            width: 100%;
            max-width: 600px;
            height: 100%;
            background-color: white;
            box-shadow: -4px 0 10px rgba(0,0,0,0.1);
            transform: translateX(100%);
            transition: transform 0.3s ease-out;
            z-index: 50;
            display: flex;
            flex-direction: column;
        }
        .off-canvas-panel.is-open {
            transform: translateX(0);
        }
        .off-canvas-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 40;
            display: none;
        }
        .off-canvas-overlay.is-open {
            display: block;
        }
        .autocomplete-suggestions {
            border: 1px solid #ddd;
            background: #fff;
            max-height: 150px;
            overflow-y: auto;
            position: absolute;
            z-index: 100;
            width: 100%;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .autocomplete-suggestion-item {
            padding: 8px 10px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .autocomplete-suggestion-item:last-child {
            border-bottom: none;
        }
        .autocomplete-suggestion-item:hover {
            background-color: #f0f0f0;
        }
    </style>
</head>
<body data-page-title="Tu Centro De Control Empresarial" 
      data-page-subtitle="Gestiona Clientes, Servicios Y Finanzas Desde Un Solo Lugar" 
      data-page-icon="layout-dashboard">
    
    <div id="toast-container" class="toast-container"></div>
    
<?php include 'files/gtm-body.php'; ?>

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

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    <?php include 'menu.php'; ?>

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

        <div id="content-area" class="p-4 md:p-8 space-y-8">
<section id="inicio" class="dashboard-section">
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">

        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
            <i data-lucide="user-plus" class="w-12 h-12 text-gray-700"></i>
            <div>
                <h3 class="text-lg font-extrabold text-gray-500 mb-1">CITAS PENDIENTES</h3>
                <p id="stat-new-prospects" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                <p class="text-sm text-gray-400 mt-1 uppercase">Últimos 30 días</p>
            </div>
        </div>

        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
            <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
            <div>
                <h3 class="text-lg font-extrabold text-gray-500 mb-1">PROSPECTOS EN SEGUIMIENTO</h3>
                <p id="stat-active-clients" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                <p class="text-sm text-gray-400 mt-1 uppercase">Total</p>
            </div>
        </div>

        <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
            <i data-lucide="clipboard-check" class="w-12 h-12 text-gray-700"></i>
            <div>
                <h3 class="text-lg font-extrabold text-gray-500 mb-1">TAREAS PENDIENTES</h3>
                <p id="stat-pending-tasks" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                <p class="text-sm text-gray-400 mt-1 uppercase">Para hoy/atrasadas</p>
            </div>
        </div>
        
    </div>
</section>

            <section id="main-content" class="dashboard-section mt-8">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
                    <div class="lg:col-span-3 bg-white p-6 rounded-xl shadow-md"> 
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="calendar-check" class="w-6 h-6 text-[var(--color-secondary)]"></i> CITAS DE HOY / PRÓXIMAS
                        </h3>
                        <ul id="upcoming-appointments-list" class="space-y-4"></ul>
                        <button id="add-appointment-button" class="mt-6 w-full btn-primary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                            <i data-lucide="plus-circle" class="w-5 h-5"></i> AGENDAR NUEVA CITA
                        </button>
                    </div>

                    <div class="lg:col-span-2 bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="bell" class="w-6 h-6 text-[var(--color-secondary)]"></i> PROSPECTOS EN SEGUIMIENTO
                        </h3>
                        <div id="lista-prospectos-seguimiento" class="space-y-4"></div>
                        <button id="add-prospect-button" class="mt-6 w-full btn-primary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                            <i data-lucide="plus-circle" class="w-5 h-5"></i> AÑADIR NUEVO PROSPECTO
                        </button>
                    </div>
                </div>
            </section>
            
            <section id="tasks-section" class="dashboard-section mt-8">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="clipboard-check" class="w-6 h-6 text-[var(--color-secondary)]"></i> TAREAS PENDIENTES
                        </h3>
                        <ul id="pending-tasks-list" class="space-y-3 mb-6"></ul>
                        <button id="add-task-button" class="w-full btn-primary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                            <i data-lucide="plus-circle" class="w-5 h-5"></i> AÑADIR NUEVA TAREA
                        </button>
                    </div>

                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                            <i data-lucide="check-circle" class="w-6 h-6 text-green-600"></i> TAREAS COMPLETADAS
                        </h3>
                        <ul id="completed-tasks-list" class="space-y-3 mb-6"></ul>
                    </div>
                </div>
            </section>
            
            <?php include 'push.php'; ?>
        </div>
    </main>
</div>

<div id="task-panel" class="off-canvas-panel">
    <div class="flex justify-between items-center p-4 border-b border-gray-200">
        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2"> AGREGAR NUEVA TAREA
            <i data-lucide="list-todo" class="w-6 h-6 text-[var(--color-secondary)]"></i>
        </h3>
        <button id="close-task-panel" class="text-gray-500 hover:text-gray-800">
            <i data-lucide="x" class="w-6 h-6"></i>
        </button>
    </div>
    <div class="p-6 flex-1 overflow-y-auto">
        <form id="add-task-form" class="space-y-4">
            <div>
                <label for="add-task-title" class="block text-sm font-medium text-gray-700 mb-1">Título De La Tarea</label>
                <input type="text" id="add-task-title" name="title" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Eje. Enviar Cotización" required>
            </div>
            <div class="relative">
                <label for="add-task-client-name" class="block text-sm font-medium text-gray-700 mb-1">Cliente (Opcional)</label>
                <input type="text" id="add-task-client-name" name="client_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Buscar Cliente">
                <input type="hidden" id="add-task-client-id" name="client_id">
                <div id="add-client-suggestions" class="autocomplete-suggestions hidden"></div>
            </div>
            <div class="relative">
                <label for="add-task-prospect-name" class="block text-sm font-medium text-gray-700 mb-1">Prospecto (Opcional)</label>
                <input type="text" id="add-task-prospect-name" name="prospect_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Buscar Prospecto">
                <input type="hidden" id="add-task-prospect-id" name="prospect_id">
                <div id="add-prospect-suggestions" class="autocomplete-suggestions hidden"></div>
            </div>
            <div>
                <label for="add-task-description" class="block text-sm font-medium text-gray-700 mb-1">Notas Adicionales</label>
                <textarea id="add-task-description" name="description" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm"></textarea>
            </div>
            <div>
                <label for="add-task-due-date" class="block text-sm font-medium text-gray-700 mb-1">Fecha De Vencimiento</label>
                <input type="date" id="add-task-due-date" name="dueDate" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" required>
            </div>
            <div>
                <label for="add-task-priority" class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
                <select id="add-task-priority" name="priority" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm">
                    <option value="Alta">Alta</option>
                    <option value="Media" selected>Media</option>
                    <option value="Baja">Baja</option>
                </select>
            </div>
            <button type="submit" class="mt-6 w-full btn-primary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                <i data-lucide="save" class="w-5 h-5"></i> GUARDAR TAREA
            </button>
        </form>
    </div>
</div>

<div id="edit-task-panel" class="off-canvas-panel">
    <div class="flex justify-between items-center p-4 border-b border-gray-200">
        <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2"> EDITAR TAREA
        <i data-lucide="list-todo" class="w-6 h-6 text-[var(--color-secondary)]"></i></h3>
        <button id="close-edit-task-panel" class="text-gray-500 hover:text-gray-800">
            <i data-lucide="x" class="w-6 h-6"></i>
        </button>
    </div>
    <div class="p-6 flex-1 overflow-y-auto">
        <form id="edit-task-form" class="space-y-4">
            <input type="hidden" id="edit-task-id">
            <div>
                <label for="edit-task-title" class="block text-sm font-medium text-gray-700 mb-1">Título De La Tarea</label>
                <input type="text" id="edit-task-title" name="title" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Eje. Llamar A Cliente" required>
            </div>
            <div class="relative">
                <label for="edit-task-client-name" class="block text-sm font-medium text-gray-700 mb-1">Cliente (Opcional)</label>
                <input type="text" id="edit-task-client-name" name="client_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Buscar Cliente">
                <input type="hidden" id="edit-task-client-id" name="client_id">
                <div id="edit-client-suggestions" class="autocomplete-suggestions hidden"></div>
            </div>
            <div class="relative">
                <label for="edit-task-prospect-name" class="block text-sm font-medium text-gray-700 mb-1">Prospecto (Opcional)</label>
                <input type="text" id="edit-task-prospect-name" name="prospect_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" placeholder="Buscar Prospecto">
                <input type="hidden" id="edit-task-prospect-id" name="prospect_id">
                <div id="edit-prospect-suggestions" class="autocomplete-suggestions hidden"></div>
            </div>
            <div>
                <label for="edit-task-description" class="block text-sm font-medium text-gray-700 mb-1">Notas Adicionales</label>
                <textarea id="edit-task-description" name="description" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm"></textarea>
            </div>
            <div>
                <label for="edit-task-due-date" class="block text-sm font-medium text-gray-700 mb-1">Fecha De Vencimiento</label>
                <input type="date" id="edit-task-due-date" name="dueDate" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm" required>
            </div>
            <div>
                <label for="edit-task-priority" class="block text-sm font-medium text-gray-700 mb-1">Prioridad</label>
                <select id="edit-task-priority" name="priority" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] sm:text-sm">
                    <option value="Alta">Alta</option>
                    <option value="Media">Media</option>
                    <option value="Baja">Baja</option>
                </select>
            </div>
            <button type="submit" class="mt-6 w-full btn-primary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                <i data-lucide="save" class="w-5 h-5"></i> GUARDAR CAMBIOS
            </button>
        </form>
    </div>
</div>

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


<script>
(function() {
    'use strict';

    let APP_DATA = {
        summaryStats: { pendingAppointments: 0, trackingProspects: 0, pendingTasks: 0 },
        upcomingAppointments: [],
        trackingProspectsList: [],
        allTasks: [],
        allClients: [],
        allProspects: []
    };

    document.addEventListener('DOMContentLoaded', () => {

        const DOMElements = {
            mobileMenuButton: document.getElementById('mobile-menu-button'),
            sidebar: document.getElementById('sidebar'),
            sidebarOverlay: document.getElementById('sidebar-overlay'),
            statNewProspects: document.getElementById('stat-new-prospects'),
            statActiveClients: document.getElementById('stat-active-clients'),
            statPendingTasks: document.getElementById('stat-pending-tasks'),
            upcomingAppointmentsList: document.getElementById('upcoming-appointments-list'),
            listaProspectosSeguimiento: document.getElementById('lista-prospectos-seguimiento'),
            pendingTasksListEl: document.getElementById('pending-tasks-list'),
            completedTasksListEl: document.getElementById('completed-tasks-list'),
            addAppointmentButton: document.getElementById('add-appointment-button'),
            addProspectButton: document.getElementById('add-prospect-button'),
            addTaskButton: document.getElementById('add-task-button'),
            taskPanel: document.getElementById('task-panel'),
            taskPanelOverlay: document.getElementById('task-panel-overlay'),
            closeTaskPanelButton: document.getElementById('close-task-panel'),
            addTaskForm: document.getElementById('add-task-form'),
            editTaskPanel: document.getElementById('edit-task-panel'),
            closeEditTaskPanelButton: document.getElementById('close-edit-task-panel'),
            editTaskForm: document.getElementById('edit-task-form'),
            addTaskTitleInput: document.getElementById('add-task-title'),
            addTaskClientNameInput: document.getElementById('add-task-client-name'),
            addTaskClientIdInput: document.getElementById('add-task-client-id'),
            addTaskProspectNameInput: document.getElementById('add-task-prospect-name'),
            addTaskProspectIdInput: document.getElementById('add-task-prospect-id'),
            addTaskDescriptionInput: document.getElementById('add-task-description'),
            addTaskDueDateInput: document.getElementById('add-task-due-date'),
            addTaskPrioritySelect: document.getElementById('add-task-priority'),
            addClientSuggestionsDiv: document.getElementById('add-client-suggestions'),
            addProspectSuggestionsDiv: document.getElementById('add-prospect-suggestions'),
            editTaskIdInput: document.getElementById('edit-task-id'),
            editTaskTitleInput: document.getElementById('edit-task-title'),
            editTaskClientNameInput: document.getElementById('edit-task-client-name'),
            editTaskClientIdInput: document.getElementById('edit-task-client-id'),
            editTaskProspectNameInput: document.getElementById('edit-task-prospect-name'),
            editTaskProspectIdInput: document.getElementById('edit-task-prospect-id'),
            editTaskDescriptionInput: document.getElementById('edit-task-description'),
            editTaskDueDateInput: document.getElementById('edit-task-due-date'),
            editTaskPrioritySelect: document.getElementById('edit-task-priority'),
            editClientSuggestionsDiv: document.getElementById('edit-client-suggestions'),
            editProspectSuggestionsDiv: document.getElementById('edit-prospect-suggestions'),
            confirmDeleteModal: document.getElementById('confirmDeleteModal'),
            confirmDeleteButton: document.getElementById('confirm-delete-button'),
            cancelDeleteButton: document.getElementById('cancel-delete-button'),
            confirmItemTypeSpan: document.getElementById('confirm-item-type')
        };
        
        const getCssVar = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;

        const updateSummaryCards = () => {
            DOMElements.statNewProspects.textContent = APP_DATA.summaryStats.pendingAppointments || 0;
            DOMElements.statActiveClients.textContent = APP_DATA.summaryStats.trackingProspects || 0;
            DOMElements.statPendingTasks.textContent = APP_DATA.summaryStats.pendingTasks || 0;
            lucide.createIcons();
        };

        const renderUpcomingAppointments = () => {
            const list = DOMElements.upcomingAppointmentsList;
            if (!list) return;
            list.innerHTML = '';
            
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            const filteredAppointments = APP_DATA.upcomingAppointments
                .filter(cita => new Date(`${cita.fecha}T${cita.hora}`) >= today && cita.status === 'confirmed')
                .sort((a, b) => new Date(`${a.fecha}T${a.hora}`) - new Date(`${b.fecha}T${b.hora}`));

            if (filteredAppointments.length === 0) {
                list.innerHTML = `<li class="text-sm text-gray-500 uppercase">No hay citas próximas.</li>`;
            } else {
                const fragment = document.createDocumentFragment();
                filteredAppointments.slice(0, 4).forEach(cita => {
                    const listItem = document.createElement('li');
                    const citaDate = new Date(`${cita.fecha}T${cita.hora}`);
                    const isToday = citaDate.toDateString() === today.toDateString();
                    const borderColor = isToday ? 'border-l-4 border-[var(--color-highlight)]' : 'border-l-4 border-gray-300';
                    const todayBadge = isToday ? `<span class="ml-2 text-xs font-bold uppercase bg-[var(--color-highlight)] text-[var(--color-primary)] px-2 py-1 rounded-full">HOY</span>` : '';
                    
                    listItem.className = `flex items-center space-x-4 p-3 rounded-lg hover:bg-gray-100 transition-all duration-300 shadow-sm ${borderColor} bg-white`;
                    listItem.innerHTML = `
                        <div class="flex-shrink-0">
                            <div class="flex flex-col items-center justify-center bg-gray-100 rounded-lg p-2 w-16 h-16 border">
                                <span class="text-2xl font-black text-[var(--color-secondary)]">${citaDate.toLocaleDateString('es-ES', { day: 'numeric' })}</span>
                                <span class="text-xs font-bold text-gray-500 uppercase">${citaDate.toLocaleDateString('es-ES', { month: 'short' })}</span>
                            </div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="font-extrabold text-lg text-gray-800 uppercase truncate">${cita.associated_name || 'Cita sin asignar'}</p>
                            <p class="text-sm text-gray-600 font-semibold truncate">${cita.servicio}</p>
                            <p class="text-sm text-gray-500 flex items-center mt-1">
                                <i data-lucide="clock" class="w-4 h-4 mr-1.5"></i>
                                ${new Date(`1970-01-01T${cita.hora}`).toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit', hour12: true })}
                                ${todayBadge}
                            </p>
                        </div>
                        <div class="flex-shrink-0">
                            <button class="text-gray-400 hover:text-[var(--color-primary)] transition-colors duration-200 go-to-agenda" title="Ir a la Agenda">
                                <i data-lucide="arrow-right-circle" class="w-7 h-7"></i>
                            </button>
                        </div>`;
                    fragment.appendChild(listItem);
                });
                list.appendChild(fragment);
            }
            lucide.createIcons();
        };

        const renderProspectos = () => {
            const list = DOMElements.listaProspectosSeguimiento;
            if (!list) return;
            list.innerHTML = '';

            const trackingStatuses = ['Cotizacion enviada', 'Seguimiento', 'Recordatorio de seguimiento', 'Ultimo recordatorio'];
            const filteredProspects = APP_DATA.trackingProspectsList
                .filter(p => trackingStatuses.includes(p.estado))
                .sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

            if (filteredProspects.length === 0) {
                list.innerHTML = '<li class="text-sm text-gray-500 uppercase">No Hay Prospectos En Seguimiento Activos.</li>';
                return;
            }

            const fragment = document.createDocumentFragment();
            filteredProspects.forEach(prospecto => {
                const prospectoCard = document.createElement('div');
                let cardClasses = 'bg-gray-50 p-4 rounded-lg shadow-sm border border-gray-200 flex items-center space-x-4 transition-all duration-200';
                let iconColor, bgColor;

                switch (prospecto.estado) {
                    case 'Cotizacion enviada':
                        cardClasses += ' border-l-4 border-green-500'; iconColor = '#10B981'; bgColor = '#ECFDF5'; break;
                    case 'Seguimiento':
                        cardClasses += ' border-l-4 border-yellow-500'; iconColor = '#F59E0B'; bgColor = '#FFFBEB'; break;
                    case 'Recordatorio de seguimiento':
                        cardClasses += ' border-l-4 border-blue-500'; iconColor = '#3B82F6'; bgColor = '#EFF6FF'; break;
                    case 'Ultimo recordatorio':
                        cardClasses += ' border-l-4 border-red-500'; iconColor = '#EF4444'; bgColor = '#FEE2E2'; break;
                    default:
                        cardClasses += ' border-l-4 border-gray-500'; iconColor = '#6B7280'; bgColor = '#F3F4F6'; break;
                }

                const fullName = `${prospecto.first_name || ''} ${prospecto.last_name || ''}`.trim() || prospecto.email || prospecto.phone || prospecto.mobile || prospecto.id;
                const createdDate = prospecto.created_at ? new Date(prospecto.created_at) : null;
                const displayCreatedAt = createdDate ? `Agregado el: ${createdDate.toLocaleDateString('es-US', { day: 'numeric', month: 'short', year: 'numeric' })}` : '';
                
                prospectoCard.className = cardClasses;
                prospectoCard.style.backgroundColor = bgColor;
                prospectoCard.innerHTML = `
                    <div class="flex-shrink-0 p-3 rounded-lg" style="background-color: ${iconColor}20;">
                        <i data-lucide="user" class="w-6 h-6" style="color: ${iconColor};"></i>
                    </div>
                    <div class="flex-1">
                        <p class="font-bold text-gray-800 uppercase">${fullName}</p>
                        <p class="text-sm text-gray-600">Estado: <span class="font-semibold">${prospecto.estado}</span></p>
                        <p class="text-sm text-gray-500 uppercase mt-1">${displayCreatedAt}</p>
                    </div>
                    <button class="text-gray-500 hover:text-[var(--color-secondary)] transition-colors duration-200 edit-prospect-btn" data-prospect-id="${prospecto.id}" title="Editar Prospecto">
                        <i data-lucide="edit" class="w-5 h-5"></i>
                    </button>`;
                fragment.appendChild(prospectoCard);
            });
            list.appendChild(fragment);
            lucide.createIcons();
        };
        
        const createTaskListItem = (tarea) => {
            const listItem = document.createElement('li');
            const dueDate = new Date(tarea.due_date);
            const today = new Date();
            today.setHours(0, 0, 0, 0);

            let textColor = 'text-gray-800', icon = 'clipboard', iconColor = getCssVar('--color-primary', '#07162d'), bgColor = `${iconColor}10`, statusBadge = '';

            if (tarea.status === 'completed') {
                textColor = 'text-green-600 line-through'; icon = 'check-circle'; iconColor = '#10B981'; bgColor = '#ECFDF5';
                statusBadge = '<span class="ml-2 px-2 py-1 bg-green-200 text-green-800 text-xs font-bold rounded-full">COMPLETADA</span>';
            } else if (dueDate < today) {
                textColor = 'text-red-600 font-semibold'; icon = 'alert-circle'; iconColor = '#DC2626'; bgColor = '#FEE2E2';
                statusBadge = '<span class="ml-2 px-2 py-1 bg-red-200 text-red-800 text-xs font-bold rounded-full">ATRASADA</span>';
            } else if (dueDate.toDateString() === today.toDateString()) {
                textColor = 'text-[var(--color-secondary)] font-semibold'; icon = 'calendar-clock'; iconColor = getCssVar('--color-secondary', '#9e1428'); bgColor = `${iconColor}10`;
                statusBadge = '<span class="ml-2 px-2 py-1 bg-yellow-200 text-yellow-800 text-xs font-bold rounded-full">HOY</span>';
            } else if (tarea.priority === 'Alta') {
                icon = 'flag'; iconColor = getCssVar('--color-highlight', '#ffc857'); bgColor = `${iconColor}10`;
            }

            listItem.className = 'flex items-center space-x-3 p-3 rounded-lg transition-colors duration-200 hover:bg-gray-100';
            listItem.style.backgroundColor = bgColor;
            listItem.innerHTML = `
                <div class="flex-shrink-0">
                    <i data-lucide="${icon}" class="w-6 h-6" style="color: ${iconColor};"></i>
                </div>
                <div class="flex-1">
                    <p class="${textColor} text-base font-semibold">
                        ${tarea.title || 'Sin Título'} ${statusBadge}
                    </p>
                    <p class="text-xs text-gray-500 uppercase mt-1">
                        ${tarea.description ? `Notas: ${tarea.description} | ` : ''}
                        Vencimiento: ${new Date(`${tarea.due_date}T00:00:00`).toLocaleDateString('es-US', { day: 'numeric', month: 'short', year: 'numeric'})} | Prioridad: ${tarea.priority}
                        ${(tarea.client_name) ? ` | Contacto: ${tarea.client_name}` : ''}
                    </p>
                </div>
                <div class="flex-shrink-0 flex items-center space-x-2">
                    ${tarea.status === 'pending' ? `
                        <button class="text-gray-400 hover:text-[var(--color-primary)] edit-task-btn" data-task-id="${tarea.id}" title="Editar Tarea">
                            <i data-lucide="edit" class="w-5 h-5"></i>
                        </button>
                        <button class="text-gray-400 hover:text-green-600 complete-task-btn" data-task-id="${tarea.id}" title="Marcar como Completada">
                            <i data-lucide="check-circle" class="w-5 h-5"></i>
                        </button>
                    ` : `
                        <button class="text-gray-400 hover:text-blue-600 uncomplete-task-btn" data-task-id="${tarea.id}" title="Marcar como Pendiente">
                            <i data-lucide="undo-2" class="w-5 h-5"></i>
                        </button>
                    `}
                    <button class="text-gray-400 hover:text-red-600 delete-task-btn" data-task-id="${tarea.id}" title="Eliminar Tarea">
                        <i data-lucide="trash-2" class="w-5 h-5"></i>
                    </button>
                </div>`;
            return listItem;
        };

        const renderTasks = () => {
            DOMElements.pendingTasksListEl.innerHTML = '';
            DOMElements.completedTasksListEl.innerHTML = '';
            
            const pendingTasks = APP_DATA.allTasks.filter(task => task.status === 'pending');
            const completedTasks = APP_DATA.allTasks.filter(task => task.status === 'completed');

            if (pendingTasks.length === 0) {
                DOMElements.pendingTasksListEl.innerHTML = '<li class="text-sm text-gray-500 uppercase">No tienes tareas pendientes. ¡Bien hecho!</li>';
            } else {
                const todayTimestamp = new Date().setHours(0, 0, 0, 0);
                const priorityOrder = { 'Alta': 1, 'Media': 2, 'Baja': 3 };

                const sortedPendingTasks = pendingTasks.map(task => {
                    const dueTimestamp = new Date(task.due_date).setHours(0,0,0,0);
                    return {
                        ...task,
                        _isOverdue: dueTimestamp < todayTimestamp,
                        _isToday: dueTimestamp === todayTimestamp,
                        _priority: priorityOrder[task.priority],
                        _dueDate: dueTimestamp
                    };
                }).sort((a, b) => (b._isOverdue - a._isOverdue) || (b._isToday - a._isToday) || (a._priority - b._priority) || (a._dueDate - b._dueDate));
                
                const fragment = document.createDocumentFragment();
                sortedPendingTasks.forEach(tarea => fragment.appendChild(createTaskListItem(tarea)));
                DOMElements.pendingTasksListEl.appendChild(fragment);
            }

            if (completedTasks.length === 0) {
                DOMElements.completedTasksListEl.innerHTML = '<li class="text-sm text-gray-500 uppercase">Aún no hay tareas completadas.</li>';
            } else {
                const sortedCompletedTasks = completedTasks.sort((a, b) => new Date(b.due_date) - new Date(a.due_date));
                const fragment = document.createDocumentFragment();
                sortedCompletedTasks.forEach(tarea => fragment.appendChild(createTaskListItem(tarea)));
                DOMElements.completedTasksListEl.appendChild(fragment);
            }
            lucide.createIcons();
        };

        const updateTaskStatus = async (taskId, newStatus) => {
            try {
                const response = await fetch('db/tasks-update.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: taskId, status: newStatus }) });
                const result = await response.json();
                if (result.success) {
                    showToast('Estado de la tarea actualizado con éxito.', 'success');
                    await initDashboard();
                } else {
                    showToast(`Error al actualizar estado de tarea: ${result.message || 'Error desconocido.'}`, 'error');
                }
            } catch (error) {
                console.error('Error de conexión al actualizar tarea:', error);
                showToast('Error de conexión al actualizar la tarea.', 'error');
            }
        };

        const deleteTask = async (taskId) => {
            try {
                const response = await fetch('db/tasks-delete.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: taskId }) });
                const result = await response.json();
                if (result.success) {
                    showToast('Tarea eliminada con éxito.', 'success');
                    await initDashboard();
                } else {
                    showToast(`Error al eliminar tarea: ${result.message || 'Error desconocido.'}`, 'error');
                }
            } catch (error) {
                console.error('Error de conexión al eliminar tarea:', error);
                showToast('Error de conexión al eliminar la tarea.', 'error');
            }
        };
        
        const deleteProspect = async (prospectId) => {
            try {
                const response = await fetch('db/leads-delete.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: prospectId }) });
                const result = await response.json();
                if (result.success) {
                    showToast('Prospecto eliminado exitosamente.', 'success');
                    await initDashboard();
                } else {
                    showToast('Error al eliminar prospecto: ' + result.message, 'error');
                }
            } catch (error) {
                showToast('Error de conexión al eliminar prospecto.', 'error');
            }
        };

        const closeModal = (modalId) => {
            const modal = document.getElementById(modalId);
            if (!modal) return;
            const modalBox = modal.querySelector('div:first-of-type');
            modalBox.classList.add('scale-95', 'opacity-0');
            setTimeout(() => { 
                modal.classList.add('hidden'); 
                DOMElements.taskPanelOverlay.classList.remove('is-open');
                document.body.style.overflow = '';
            }, 300);
        };
        
        const openConfirmDeleteModal = (itemId, itemType) => {
            DOMElements.confirmItemTypeSpan.textContent = itemType.toUpperCase();
            
            const deleteHandler = async () => {
                if (itemType === 'tarea') await deleteTask(itemId);
                else if (itemType === 'prospecto') await deleteProspect(itemId);
                closeModal('confirmDeleteModal');
                DOMElements.confirmDeleteButton.removeEventListener('click', deleteHandler);
            };
            
            DOMElements.confirmDeleteButton.addEventListener('click', deleteHandler, { once: true });

            const modal = DOMElements.confirmDeleteModal;
            const modalBox = modal.querySelector('div:first-of-type');
            modal.classList.remove('hidden');
            setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
            DOMElements.taskPanelOverlay.classList.add('is-open');
            document.body.style.overflow = 'hidden';
        };

        const openPanel = (panel, overlay) => {
            panel.classList.add('is-open');
            overlay.classList.add('is-open');
            document.body.style.overflow = 'hidden';
            lucide.createIcons();
        };

        const closePanel = (panel, overlay) => {
            panel.classList.remove('is-open');
            overlay.classList.remove('is-open');
            document.body.style.overflow = '';
        };

        const openTaskPanel = () => {
            DOMElements.addTaskForm.reset();
            DOMElements.addTaskClientIdInput.value = '';
            DOMElements.addClientSuggestionsDiv.innerHTML = '';
            DOMElements.addClientSuggestionsDiv.classList.add('hidden');
            DOMElements.addTaskProspectIdInput.value = '';
            DOMElements.addProspectSuggestionsDiv.innerHTML = '';
            DOMElements.addProspectSuggestionsDiv.classList.add('hidden');
            DOMElements.addTaskDueDateInput.value = new Date().toISOString().split('T')[0];
            DOMElements.addTaskPrioritySelect.value = 'Media';
            DOMElements.addTaskClientNameInput.disabled = false;
            DOMElements.addTaskProspectNameInput.disabled = false;
            openPanel(DOMElements.taskPanel, DOMElements.taskPanelOverlay);
        };

        const openEditTaskPanel = (taskId) => {
            const task = APP_DATA.allTasks.find(t => t.id == taskId);
            if (!task) {
                showToast("Tarea no encontrada para editar.", 'error');
                return;
            }

            DOMElements.editTaskIdInput.value = task.id;
            DOMElements.editTaskTitleInput.value = task.title || '';
            DOMElements.editTaskDescriptionInput.value = task.description || '';
            DOMElements.editTaskDueDateInput.value = task.due_date || '';
            DOMElements.editTaskPrioritySelect.value = task.priority || 'Media';
            DOMElements.editTaskClientIdInput.value = task.client_id || '';
            DOMElements.editTaskClientNameInput.value = task.client_name || '';
            DOMElements.editTaskProspectIdInput.value = task.lead_id || '';
            DOMElements.editTaskProspectNameInput.value = task.prospect_name || '';
            
            DOMElements.editTaskClientNameInput.disabled = !!task.lead_id;
            DOMElements.editTaskProspectNameInput.disabled = !!task.client_id;

            openPanel(DOMElements.editTaskPanel, DOMElements.taskPanelOverlay);
        };

        const saveTask = async (formData, isEdit = false) => {
            const url = isEdit ? 'db/tasks-update.php' : 'db/tasks-create.php';
            try {
                const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) });
                const result = await response.json();
                if (result.success) {
                    showToast(`Tarea ${isEdit ? 'actualizada' : 'agregada'} con éxito.`, 'success');
                    isEdit ? closePanel(DOMElements.editTaskPanel, DOMElements.taskPanelOverlay) : closePanel(DOMElements.taskPanel, DOMElements.taskPanelOverlay);
                    await initDashboard();
                } else {
                    showToast(`Error al ${isEdit ? 'actualizar' : 'agregar'} tarea: ${result.message || 'Error desconocido.'}`, 'error');
                }
            } catch (error) {
                console.error(`Error de conexión al ${isEdit ? 'actualizar' : 'agregar'} tarea:`, error);
                showToast(`Error de conexión al ${isEdit ? 'actualizar' : 'agregar'} la tarea.`, 'error');
            }
        };
        
        const setupAutocomplete = (inputElement, hiddenIdElement, suggestionsDiv, dataList, type) => {
            let selectedSuggestion = null;
            inputElement.addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                suggestionsDiv.innerHTML = '';
                hiddenIdElement.value = '';
                selectedSuggestion = null;

                if (searchTerm.length < 2) { suggestionsDiv.classList.add('hidden'); return; }
                
                const filtered = dataList.filter(item => 
                    (item.name || '').toLowerCase().includes(searchTerm) ||
                    (item.email && item.email.toLowerCase().includes(searchTerm)) ||
                    (item.company && item.company.toLowerCase().includes(searchTerm)) ||
                    (item.phone && item.phone.toLowerCase().includes(searchTerm)) ||
                    (item.mobile && item.mobile.toLowerCase().includes(searchTerm))
                );

                if (filtered.length === 0) { suggestionsDiv.classList.add('hidden'); return; }
                
                suggestionsDiv.classList.remove('hidden');
                filtered.slice(0, 5).forEach(item => {
                    const suggestionItem = document.createElement('div');
                    suggestionItem.className = 'autocomplete-suggestion-item';
                    suggestionItem.textContent = item.name;
                    suggestionItem.addEventListener('click', function() {
                        inputElement.value = item.name;
                        hiddenIdElement.value = item.id;
                        selectedSuggestion = item;
                        suggestionsDiv.classList.add('hidden');

                        const otherInput = (type === 'client') 
                            ? (inputElement === DOMElements.addTaskClientNameInput ? DOMElements.addTaskProspectNameInput : DOMElements.editTaskProspectNameInput)
                            : (inputElement === DOMElements.addTaskProspectNameInput ? DOMElements.addTaskClientNameInput : DOMElements.editTaskClientNameInput);
                        const otherHidden = (type === 'client') 
                            ? (inputElement === DOMElements.addTaskClientNameInput ? DOMElements.addTaskProspectIdInput : DOMElements.editTaskProspectIdInput)
                            : (inputElement === DOMElements.addTaskProspectNameInput ? DOMElements.addTaskClientIdInput : DOMElements.editTaskClientIdInput);
                        
                        otherInput.value = '';
                        otherHidden.value = '';
                        otherInput.disabled = true;
                        showToast(`"${item.name}" seleccionado. El otro campo ha sido deshabilitado.`, 'info');
                    });
                    suggestionsDiv.appendChild(suggestionItem);
                });
            });

            inputElement.addEventListener('blur', function() {
                setTimeout(() => {
                    suggestionsDiv.classList.add('hidden');
                    const selectedNameMatch = selectedSuggestion && (selectedSuggestion.name || '').toLowerCase().trim() === this.value.toLowerCase().trim();
                    if (!selectedNameMatch) { hiddenIdElement.value = ''; }
                }, 150);
            });

            inputElement.addEventListener('focus', function() {
                const otherInput = (type === 'client') 
                    ? (inputElement === DOMElements.addTaskClientNameInput ? DOMElements.addTaskProspectNameInput : DOMElements.editTaskProspectNameInput)
                    : (inputElement === DOMElements.addTaskProspectNameInput ? DOMElements.addTaskClientNameInput : DOMElements.editTaskClientNameInput);
                otherInput.disabled = false;
                if (this.value.length >= 2) { this.dispatchEvent(new Event('input')); }
            });
        };

        const initDashboard = async () => {
            try {
                const cacheBust = new Date().getTime();
                const [dashboardResponse, clientsResponse, prospectsResponse] = await Promise.all([
                    fetch(`db/dashboard-read.php?v=${cacheBust}`),
                    fetch(`db/clients-read-contact-data.php?v=${cacheBust}`),
                    fetch(`db/leads-read-contact-data.php?v=${cacheBust}`)
                ]);

                const dashboardResult = await dashboardResponse.json();
                const clientsResult = await clientsResponse.json();
                const prospectsResult = await prospectsResponse.json();

                if (dashboardResult.success && dashboardResult.data) {
                    APP_DATA.summaryStats = { pendingAppointments: dashboardResult.data.pendingAppointments || 0, trackingProspects: dashboardResult.data.trackingProspects || 0, pendingTasks: dashboardResult.data.pendingTasks || 0 };
                    APP_DATA.upcomingAppointments = dashboardResult.data.upcomingAppointments || [];
                    APP_DATA.allTasks = dashboardResult.data.allTasks || [];
                    APP_DATA.trackingProspectsList = dashboardResult.data.trackingProspectsList || [];
                } else { showToast('Error al cargar datos del dashboard: ' + (dashboardResult.message || 'Error desconocido.'), 'error'); }

                if (clientsResult.success && clientsResult.data) {
                    APP_DATA.allClients = Object.values(clientsResult.data);
                } else { showToast('Error al cargar clientes: ' + (clientsResult.message || 'Error desconocido.'), 'error'); }

                if (prospectsResult.success && prospectsResult.data) {
                    APP_DATA.allProspects = Object.values(prospectsResult.data);
                } else { showToast('Error al cargar prospectos: ' + (prospectsResult.message || 'Error desconocido.'), 'error'); }

            } catch (error) {
                console.error('Error de conexión al cargar datos:', error);
                showToast('Error de conexión al cargar datos del dashboard.', 'error');
            }

            updateSummaryCards();
            renderUpcomingAppointments();
            renderProspectos();
            renderTasks();

            setupAutocomplete(DOMElements.addTaskClientNameInput, DOMElements.addTaskClientIdInput, DOMElements.addClientSuggestionsDiv, APP_DATA.allClients, 'client');
            setupAutocomplete(DOMElements.addTaskProspectNameInput, DOMElements.addTaskProspectIdInput, DOMElements.addProspectSuggestionsDiv, APP_DATA.allProspects, 'prospect');
            setupAutocomplete(DOMElements.editTaskClientNameInput, DOMElements.editTaskClientIdInput, DOMElements.editClientSuggestionsDiv, APP_DATA.allClients, 'client');
            setupAutocomplete(DOMElements.editTaskProspectNameInput, DOMElements.editTaskProspectIdInput, DOMElements.editProspectSuggestionsDiv, APP_DATA.allProspects, 'prospect');
        };

        const handleListClick = (e) => {
            const target = e.target;
            const editBtn = target.closest('.edit-task-btn');
            const completeBtn = target.closest('.complete-task-btn');
            const uncompleteBtn = target.closest('.uncomplete-task-btn');
            const deleteBtn = target.closest('.delete-task-btn');
            const editProspectBtn = target.closest('.edit-prospect-btn');
            const agendaBtn = target.closest('.go-to-agenda');

            if (editBtn) openEditTaskPanel(editBtn.dataset.taskId);
            if (completeBtn) updateTaskStatus(completeBtn.dataset.taskId, 'completed');
            if (uncompleteBtn) updateTaskStatus(uncompleteBtn.dataset.taskId, 'pending');
            if (deleteBtn) openConfirmDeleteModal(deleteBtn.dataset.taskId, 'tarea');
            if (editProspectBtn) window.location.href = `leads.php?edit_id=${editProspectBtn.dataset.prospectId}`;
            if (agendaBtn) window.location.href = 'agenda.php';
        };

        DOMElements.mobileMenuButton.addEventListener('click', () => { DOMElements.sidebar.classList.toggle('-translate-x-full'); DOMElements.sidebarOverlay.classList.toggle('hidden'); });
        DOMElements.sidebarOverlay.addEventListener('click', () => { DOMElements.sidebar.classList.toggle('-translate-x-full'); DOMElements.sidebarOverlay.classList.toggle('hidden'); });
        DOMElements.addAppointmentButton.addEventListener('click', () => { window.location.href = "agenda.php"; });
        DOMElements.addProspectButton.addEventListener('click', () => { window.location.href = "leads.php"; });
        DOMElements.addTaskButton.addEventListener('click', openTaskPanel);
        DOMElements.closeTaskPanelButton.addEventListener('click', () => closePanel(DOMElements.taskPanel, DOMElements.taskPanelOverlay));
        DOMElements.taskPanelOverlay.addEventListener('click', () => { closePanel(DOMElements.taskPanel, DOMElements.taskPanelOverlay); closePanel(DOMElements.editTaskPanel, DOMElements.taskPanelOverlay); });
        
        DOMElements.addTaskForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const taskData = { title: DOMElements.addTaskTitleInput.value, description: DOMElements.addTaskDescriptionInput.value, client_id: DOMElements.addTaskClientIdInput.value || null, lead_id: DOMElements.addTaskProspectIdInput.value || null, due_date: DOMElements.addTaskDueDateInput.value, priority: DOMElements.addTaskPrioritySelect.value, status: 'pending' };
            if (!taskData.title || !taskData.due_date) { showToast('Por favor, completa el título y la fecha de vencimiento.', 'warning'); return; }
            saveTask(taskData, false);
        });

        DOMElements.closeEditTaskPanelButton.addEventListener('click', () => closePanel(DOMElements.editTaskPanel, DOMElements.taskPanelOverlay));
        DOMElements.editTaskForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const taskData = { id: DOMElements.editTaskIdInput.value, title: DOMElements.editTaskTitleInput.value, description: DOMElements.editTaskDescriptionInput.value, client_id: DOMElements.editTaskClientIdInput.value || null, lead_id: DOMElements.editTaskProspectIdInput.value || null, due_date: DOMElements.editTaskDueDateInput.value, priority: DOMElements.editTaskPrioritySelect.value };
            if (!taskData.title || !taskData.due_date) { showToast('Por favor, completa el título y la fecha de vencimiento.', 'warning'); return; }
            saveTask(taskData, true);
        });
        
        DOMElements.cancelDeleteButton.addEventListener('click', () => closeModal('confirmDeleteModal'));

        DOMElements.pendingTasksListEl.addEventListener('click', handleListClick);
        DOMElements.completedTasksListEl.addEventListener('click', handleListClick);
        DOMElements.listaProspectosSeguimiento.addEventListener('click', handleListClick);
        DOMElements.upcomingAppointmentsList.addEventListener('click', handleListClick);
        
        initDashboard();
    });
})();
</script>
</body>
</html>