<?php include 'files/guardiankey.php'; ?>
<?php 
    include 'files/motivational-quotes.php';

    $seed = date('Ymd');
    srand(hexdec(substr(sha1($seed), 0, 8))); 

    $quote_index = rand(0, count($motivational_quotes) - 1);
    
    $daily_quote = $motivational_quotes[$quote_index]['quote'];
    $daily_author = $motivational_quotes[$quote_index]['author'];
    
    srand(time()); 
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>FlowCRM™ Tu Centro De Control Empresarial Powered By OrozCO</title>
  <meta name="description" content="La Plataforma Todo En Uno Para Impulsar Tu Negocio">
  <meta name="robots" content="noindex, nofollow">

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

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    
<style>
        .off-canvas-panel{position:fixed;top:0;right:0;width:100%;max-width:600px;height:100%;background:#fff;box-shadow:-4px 0 10px rgba(0,0,0,.1);transform:translateX(100%);transition:transform .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:rgba(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,.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:#f0f0f0}

        @media (max-width: 768px){ .page-header-container{display:none!important} .dashboard-section:first-of-type,#inicio:first-of-type{margin-top:calc(var(--header-height) + 12px)!important} }
        .stat-card{display:flex;align-items:center;gap:1rem;box-shadow:0 10px 25px rgba(0,0,0,.06);border-left-width:4px}
        .stat-card p.text-5xl{line-height:1}

        @media (max-width:480px){
          .dashboard-section .grid{gap:12px!important}
          .stat-card{padding:14px!important;border-radius:14px!important;box-shadow:0 10px 22px rgba(0,0,0,.06)!important}
          .stat-card [data-lucide]{width:32px!important;height:32px!important}
          .stat-card h3{font-size:.95rem!important;line-height:1.15!important;margin-bottom:.25rem!important}
          .stat-card .text-5xl{font-size:2.25rem!important}
          .stat-card .text-sm{font-size:.75rem!important}
        }
    </style>
    
</head>
<body data-page-title="FlowCRM™ Tu Centro De Control Empresarial" 
      data-page-subtitle="La Plataforma Todo En Uno Para Impulsar Tu Negocio" 
      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>
            
<div class="show-widget-container hidden flex justify-end p-0" id="show-welcome-intro-video-container">
    <button class="show-widget-btn inline-flex items-center gap-3 text-base font-bold text-white bg-[var(--color-primary)] rounded-lg shadow-lg shadow-[var(--color-primary)]/20 py-3 px-6 transform hover:-translate-y-1 hover:shadow-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--color-secondary)]"
        data-widget-id="welcome-intro-video">
        <i data-lucide="eye" class="w-5 h-5"></i>
        <span>VER VIDEO PRESENTACIÓN</span>
    </button>
</div>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            
            <section class="p-6 md:p-10 video-widget" id="welcome-intro-video">
    <div class="blob bl1"></div><div class="blob bl2"></div>
    <div class="relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
        <div>
            <span class="chip"><i data-lucide="laptop-minimal" class="w-4 h-4"></i> BIENVENIDO A FLOWCRM™</span>
            <h1 class="mt-3 text-3xl md:text-4xl font-extrabold leading-tight text-[var(--color-highlight)]">El CRM Para El Manejo Y Crecimiento De Tu Negocio</h1>
            <p class="mt-2 text-white/90 max-w-2xl">Centraliza tus clientes, citas y tareas. Automatiza recordatorios y mantén tu operación avanzando todos los días.</p>
            <div class="mt-4 flex flex-wrap gap-2">
                <a href="#inicio" class="hero-cta"><i data-lucide="list-todo" class="w-5 h-5"></i> TAREAS PENDIENTES</a>
                <a href="/agenda" class="hero-cta secondary"><i data-lucide="calendar" class="w-4 h-4"></i> ABRIR TU AGENDA</a>
            </div>
        </div>
        <div>
            <div class="w-full">
                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload nofullscreen" preload="metadata">
                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                        </video>
                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                            <img src="img/vids/VideoLeccion-Dashboard.webp" alt="VideoLeccion - FlowCRM" class="absolute inset-0 w-full h-full object-cover">
                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                        </div>
                    </div>
                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                        <span class="inline-flex items-center gap-2">
                            <i data-lucide="play-circle" class="w-4 h-4"></i>
                            Video Presentación
                        </span>

                        <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-black text-[var(--color-highlight)] hover:text-[var(--color-highlight)] transition-colors py-1 px-2 rounded-md" 
                                data-widget-id="welcome-intro-video" 
                                title="Ocultar el video de bienvenida">
                            OCULTAR VIDEO
                            <i data-lucide="square-x" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="mb-6">
    <div class="relative p-6 rounded-xl shadow-lg overflow-hidden
                bg-gradient-to-r from-[var(--color-primary)] to-[#1a2b42] text-white">
  <div class="relative z-10 flex flex-col items-center justify-center text-center">
            
            <div class="flex items-center justify-center mb-3">
                <i data-lucide="megaphone" class="w-8 h-8 text-[var(--color-highlight)]"></i>
            </div>
            <div>
                <p class="text-2xl md:text-2xl italic font-bold leading-tight max-w-4xl mx-auto">
                "<?php echo htmlspecialchars($daily_quote); ?>"
            </p>
            
            <p class="text-base font-semibold text-[var(--color-highlight)] mt-4">
                — <?php echo htmlspecialchars($daily_author); ?>
            </p>
            </div>
        </div>
    </div>
</section>

<section id="inicio" class="dashboard-section">
    <div class="grid grid-cols-1 sm: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="users" class="w-12 h-12 text-gray-700"></i>
            <div>
                <h3 class="text-lg font-extrabold text-gray-500 mb-1">LEADS EN SEGUIMIENTO</h3>
                <p id="stat-tracking-prospects" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                <p class="text-sm text-gray-400 mt-1 uppercase">PARA CONVERTIR EN CLIENTES</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 class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
            <i data-lucide="file-text" class="w-12 h-12 text-gray-700"></i>
            <div>
                <h3 class="text-lg font-extrabold text-gray-500 mb-1">ESTIMADOS ENVIADOS</h3>
                <p id="stat-pending-estimates" class="text-5xl font-bold text-[var(--color-primary)]">0</p>
                <p class="text-sm text-gray-400 mt-1 uppercase">PARA DAR SEGUIMIENTO</p>
            </div>
        </div>
    </div>
</section>

            <section id="main-content" class="dashboard-section mt-8">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

        <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md">
            <h3 class="text-2xl 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-1 bg-white p-6 rounded-xl shadow-md">
            <h3 class="text-2xl 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="finances-tracking" class="dashboard-section mt-8">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

        <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md">
            <h3 class="text-2xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                <i data-lucide="file-text" class="w-6 h-6 text-[var(--color-secondary)]"></i> ESTIMADOS PARA SEGUIMIENTO
            </h3>
            <ul id="pending-estimates-list" class="space-y-4"></ul>
            <button id="view-all-estimates-button" class="mt-6 w-full btn-secondary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                <i data-lucide="eye" class="w-5 h-5"></i> VER TODOS LOS ESTIMADOS
            </button>
        </div>

        <div class="lg:col-span-1 bg-white p-6 rounded-xl shadow-md">
            <h3 class="text-2xl font-extrabold text-gray-800 mb-4 flex items-center gap-2">
                <i data-lucide="wallet" class="w-6 h-6 text-[var(--color-secondary)]"></i> FACTURAS VENCIDAS POR COBRAR
            </h3>
            <div id="overdue-invoices-list" class="space-y-4"></div>
            <button id="view-all-invoices-button" class="mt-6 w-full btn-secondary font-bold uppercase text-sm py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                <i data-lucide="file-check-2" class="w-5 h-5"></i> VER TODAS LAS FACTURAS
            </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-2xl 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-secondary 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-2xl 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 w-full md:w-1/3 h-full">
    <div class="flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow">
        <h3 class="text-xl font-extrabold mb-0 flex items-center gap-2"> 
            <i data-lucide="list-todo" class="w-6 h-6 text-[var(--color-highlight)]"></i>
            AGREGAR NUEVA TAREA
        </h3>
        <button id="close-task-panel" class="text-white hover:text-gray-200">
            <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 w-full md:w-1/3 h-full">
    <div class="flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow">
        <h3 class="text-xl font-extrabold mb-0 flex items-center gap-2">
            <i data-lucide="list-todo" class="w-6 h-6 text-[var(--color-highlight)]"></i>
            EDITAR TAREA
        </h3>
        <button id="close-edit-task-panel" class="text-white hover:text-gray-200">
            <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-[var(--color-secondary)]"></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 flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4"> <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="cancel-delete-button">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>

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

    const decodeHtmlEntities = (text) => {
        if (!text) return "";
        const textArea = document.createElement('textarea');
        textArea.innerHTML = text;
        return textArea.value;
    };

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

    document.addEventListener('DOMContentLoaded', () => {
        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');

        if (notificationType && notificationMessage) {
            if (typeof showToast === 'function') {
                showToast(notificationMessage, notificationType);
            } else {
                console.error("showToast function is not defined. Toast notification might not display.");
            }
        }

        const DOMElements = {
            mobileMenuButton: document.getElementById('mobile-menu-button'),
            sidebar: document.getElementById('sidebar'),
            sidebarOverlay: document.getElementById('sidebar-overlay'),
            
            // Se incluyen todos los elementos del DOM necesarios
            statPendingAppointments: document.getElementById('stat-pending-appointments'),
            statTrackingProspects: document.getElementById('stat-tracking-prospects'),
            statPendingTasks: document.getElementById('stat-pending-tasks'),
            statPendingEstimates: document.getElementById('stat-pending-estimates'), 
            statOverdueInvoices: document.getElementById('stat-overdue-invoices'), 

            upcomingAppointmentsList: document.getElementById('upcoming-appointments-list'),
            listaProspectosSeguimiento: document.getElementById('lista-prospectos-seguimiento'),
            
            pendingEstimatesList: document.getElementById('pending-estimates-list'), 
            overdueInvoicesList: document.getElementById('overdue-invoices-list'),
            viewAllEstimatesButton: document.getElementById('view-all-estimates-button'),
            viewAllInvoicesButton: document.getElementById('view-all-invoices-button'),
            
            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 = () => {
            // Se utiliza el operador lógico AND para asegurar que solo se actualicen si el elemento existe
            if(DOMElements.statPendingAppointments) DOMElements.statPendingAppointments.textContent = APP_DATA.summaryStats.pendingAppointments || 0; 
            if(DOMElements.statTrackingProspects) DOMElements.statTrackingProspects.textContent = APP_DATA.summaryStats.trackingProspects || 0; 
            if(DOMElements.statPendingTasks) DOMElements.statPendingTasks.textContent = APP_DATA.summaryStats.pendingTasks || 0;
            if(DOMElements.statPendingEstimates) DOMElements.statPendingEstimates.textContent = APP_DATA.summaryStats.pendingEstimates || 0; 
            if(DOMElements.statOverdueInvoices) DOMElements.statOverdueInvoices.textContent = APP_DATA.summaryStats.overdueInvoices || 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
                .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-base text-gray-500 uppercase">No hay citas próximas</li>`;
            } else {
                const fragment = document.createDocumentFragment();
                filteredAppointments.slice(0, 5).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">${decodeHtmlEntities(cita.associated_name) || 'Cita sin asignar'}</p>
                            <p class="text-sm text-gray-600 font-semibold uppercase truncate">${decodeHtmlEntities(cita.servicio) || 'Servicio no especificado'}</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 Solicitada', 'En Seguimiento','Presentar Solución', 'Introducir Servicio', 'Seguimiento Post Envío', 'Negociación Final'];
            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-base 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-[var(--color-primary)]'; iconColor = '#3B82F6'; bgColor = '#EFF6FF'; break;
                    case 'Ultimo recordatorio':
                        cardClasses += ' border-l-4 border-[var(--color-secondary)]'; 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 || `ID: ${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">${decodeHtmlEntities(fullName)}</p>
                        <p class="text-sm text-gray-600">Estado: <span class="font-semibold capitalize">${decodeHtmlEntities(prospecto.estado)}</span></p>
                        <p class="text-sm text-gray-500 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 renderPendingEstimates = () => {
            const list = DOMElements.pendingEstimatesList;
            if (!list) return;
            list.innerHTML = '';

            const filteredEstimates = APP_DATA.pendingEstimatesList
                .filter(e => ['generado', 'enviado'].includes(e.estado))
                .sort((a, b) => new Date(a.fecha) - new Date(b.fecha)); 

            if (filteredEstimates.length === 0) {
                list.innerHTML = '<li class="text-base text-gray-500 uppercase">No hay estimados pendientes de seguimiento</li>';
                return;
            }

            const fragment = document.createDocumentFragment();
            filteredEstimates.forEach(estimado => {
                const item = document.createElement('li');
                let statusBadgeClasses = 'px-2 py-1 rounded-full text-xs font-bold uppercase ml-2';
                let statusColor = 'bg-gray-200 text-gray-700';

                if (estimado.estado === 'enviado') {
                    statusColor = 'bg-[var(--color-primary)] text-white';
                } else if (estimado.estado === 'generado') {
                    statusColor = 'bg-yellow-100 text-yellow-600';
                }

                item.className = 'flex items-center justify-between space-x-4 p-3 rounded-lg hover:bg-gray-100 transition-all duration-300 shadow-sm border-l-4 border-[var(--color-primary)] bg-white cursor-pointer go-to-estimates-btn';
                item.dataset.estimateId = estimado.id;
                item.innerHTML = `
                    <div class="flex-1 min-w-0">
                        <p class="font-extrabold text-base text-gray-800 uppercase truncate">${decodeHtmlEntities(estimado.associated_name)}</p>
                        <p class="text-sm text-gray-600 font-semibold mt-1 flex items-center">
                            <i data-lucide="hash" class="w-4 h-4 mr-1.5 text-[var(--color-primary)]"></i> ${estimado.id}
                        </p>
                        <p class="text-sm text-gray-500 mt-1">Fecha: ${new Date(`${estimado.fecha}T00:00:00`).toLocaleDateString('es-ES', { day: 'numeric', month: 'short', year: 'numeric'})}</p>
                    </div>
                    <div class="flex-shrink-0 text-right">
                        <p class="text-xl font-black text-[var(--color-primary)]">$${parseFloat(estimado.monto).toFixed(2)}</p>
                        <span class="${statusBadgeClasses} ${statusColor}">${decodeHtmlEntities(estimado.estado)}</span>
                    </div>
                `;
                fragment.appendChild(item);
            });
            list.appendChild(fragment);
            lucide.createIcons();
        };

        const renderOverdueInvoices = () => {
          const list = DOMElements.overdueInvoicesList;
          if (!list) return;
          list.innerHTML = '';

          const today = new Date();
          today.setHours(0, 0, 0, 0);

          // *** CORRECCIÓN AQUÍ: USA LOS DATOS DIRECTOS DEL PHP ***
          // El PHP ya filtró correctamente, solo necesitamos mostrar lo que envió.
          const filteredInvoices = APP_DATA.overdueInvoicesList // Usa la lista que ya mandó el PHP
              .sort((a, b) => {
                  // Ordena por fecha de vencimiento, poniendo las 'atrasada' sin fecha primero
                  const dateA = a.vencimiento ? new Date(`${a.vencimiento}T00:00:00`) : new Date(0); // Fecha muy antigua si es NULL
                  const dateB = b.vencimiento ? new Date(`${b.vencimiento}T00:00:00`) : new Date(0);
                  if (a.estado === 'atrasada' && !a.vencimiento && b.estado !== 'atrasada') return -1; // 'atrasada' sin fecha va primero
                  if (b.estado === 'atrasada' && !b.vencimiento && a.estado !== 'atrasada') return 1;
                  return dateA - dateB; // Luego ordena por fecha
              });

          if (filteredInvoices.length === 0) {
              list.innerHTML = '<li class="text-base text-gray-500 uppercase">¡Felicidades! No hay facturas vencidas por cobrar</li>';
              return;
          }

          const fragment = document.createDocumentFragment();
          filteredInvoices.forEach(factura => {
              const item = document.createElement('li');
              const vencimientoDate = factura.vencimiento ? new Date(`${factura.vencimiento}T00:00:00`) : null;
              let daysOverdueText = 'Vencida'; // Texto por defecto

              if (vencimientoDate) {
                  const daysOverdue = Math.max(0, Math.floor((today - vencimientoDate) / (1000 * 60 * 60 * 24))); // Asegura que no sea negativo
                  daysOverdueText = `${daysOverdue} día${daysOverdue !== 1 ? 's' : ''} vencida`;
              } else if (factura.estado === 'atrasada') {
                  daysOverdueText = 'Atrasada (Sin Fecha)'; // Caso especial 'atrasada' sin fecha
              }

              item.className = 'flex items-center justify-between space-x-4 p-3 rounded-lg hover:bg-red-50 transition-all duration-300 shadow-sm border-l-4 border-[var(--color-secondary)] bg-white cursor-pointer go-to-invoices-btn'; // hover:bg-red-50 para énfasis
              item.dataset.invoiceId = factura.id; // Usa external_id que viene como 'id'
              item.innerHTML = `
                  <div class="flex-1 min-w-0">
                      <p class="font-extrabold text-base text-[var(--color-secondary)] uppercase truncate">${decodeHtmlEntities(factura.associated_name)}</p>
                      <p class="text-sm text-gray-600 font-semibold mt-1 flex items-center">
                          <i data-lucide="hash" class="w-4 h-4 mr-1.5 text-[var(--color-secondary)]"></i> ${factura.id}
                      </p>
                      <p class="text-sm text-gray-500 mt-1">
                          ${factura.vencimiento ? `Vence: ${vencimientoDate.toLocaleDateString('es-ES', { day: 'numeric', month: 'short', year: 'numeric'})}` : 'Fecha Venc.: N/A'}
                      </p>
                  </div>
                  <div class="flex-shrink-0 text-right">
                      <p class="text-xl font-black text-[var(--color-secondary)]">$${parseFloat(factura.monto).toFixed(2)}</p>
                      <span class="px-2 py-1 rounded-full text-xs font-bold uppercase bg-[var(--color-secondary)] text-white">${daysOverdueText}</span>
                  </div>
              `;
              fragment.appendChild(item);
          });
          list.appendChild(fragment);
          lucide.createIcons();
      };

        const createTaskListItem = (tarea) => {
            const listItem = document.createElement('li');
            const dueDate = new Date(`${tarea.due_date}T00:00:00`);
            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 = '';
            let priorityBadgeClasses = 'px-2 py-1 rounded-full text-sm font-bold text-white';
            let priorityBadgeContent = tarea.priority;
            let taskOverallBgColor = '';

            if (tarea.status === 'completed') {
                textColor = 'text-green-600 line-through';
                icon = 'check-circle';
                iconColor = '#10B981';
                taskOverallBgColor = '#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-[var(--color-secondary)] font-semibold';
                icon = 'alert-circle';
                iconColor = '#DC2626';
                taskOverallBgColor = '#FEE2E2';
                statusBadge = '<span class="ml-2 px-2 py-1 bg-[var(--color-secondary)] text-white 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');
                taskOverallBgColor = `${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 {
                taskOverallBgColor = getCssVar('--color-primary', '#07162d') + '10';
            }

            switch (tarea.priority) {
                case 'Alta':
                    icon = 'flag';
                    iconColor = '#EF4444';
                    priorityBadgeClasses += ' bg-[var(--color-secondary)] uppercase task-priority-alta';
                    break;
                case 'Media':
                    icon = 'flag';
                    iconColor = '#F59E0B';
                    priorityBadgeClasses += ' bg-orange-500 uppercase task-priority-media';
                    break;
                case 'Baja':
                    icon = 'flag';
                    iconColor = '#3B82F6';
                    priorityBadgeClasses += ' bg-[var(--color-primary)] uppercase task-priority-baja';
                    break;
                default:
                    icon = 'clipboard';
                    iconColor = getCssVar('--color-primary', '#07162d');
                    priorityBadgeClasses += ' bg-gray-400 task-priority-neutral';
                    break;
            }

            listItem.className = 'flex items-center space-x-3 p-3 rounded-lg transition-colors duration-200 hover:bg-gray-100';
            listItem.style.backgroundColor = taskOverallBgColor;

            const contactNameHtml = (tarea.client_name || tarea.prospect_name)
                ? `<br class="sm:hidden"> | Contacto: <span class="font-normal">${decodeHtmlEntities(tarea.client_name || tarea.prospect_name)}</span>`
                : '';

            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">
                        ${decodeHtmlEntities(tarea.title || 'Sin Título')} ${statusBadge}
                    </p>
                    <p class="text-base text-gray-700 mt-1 leading-snug"> ${tarea.description ? `Notas: <span class="font-normal">${decodeHtmlEntities(tarea.description)}</span> | ` : ''} Vencimiento: <span class="font-normal">${new Date(`${tarea.due_date}T00:00:00`).toLocaleDateString('es-US', { day: 'numeric', month: 'short', year: 'numeric'})}</span> |&nbsp;
                        <br />Prioridad: <span class="${priorityBadgeClasses}">${priorityBadgeContent}</span>
                        ${contactNameHtml}
                    </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-[var(--color-primary)] 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-[var(--color-secondary)] 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-base 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-base 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) {
                    if (typeof showToast === 'function') {
                        showToast('Estado de la tarea actualizado con éxito.', 'success');
                    }
                    await initDashboard();
                } else {
                    if (typeof showToast === 'function') {
                        showToast(`Error al actualizar estado de tarea: ${result.message || 'Error desconocido.'}`, 'error');
                    }
                }
            } catch (error) {
                console.error('Error de conexión al actualizar tarea:', error);
                if (typeof showToast === 'function') {
                    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) {
                    if (typeof showToast === 'function') {
                        showToast('Tarea eliminada con éxito.', 'success');
                    }
                    await initDashboard();
                } else {
                    if (typeof showToast === 'function') {
                        showToast(`Error al eliminar tarea: ${result.message || 'Error desconocido.'}`, 'error');
                    }
                }
            } catch (error) {
                console.error('Error de conexión al eliminar tarea:', error);
                if (typeof showToast === 'function') {
                    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) {
                    if (typeof showToast === 'function') {
                        showToast('Prospecto eliminado exitosamente.', 'success');
                    }
                    await initDashboard();
                } else {
                    if (typeof showToast === 'function') {
                        showToast('Error al eliminar prospecto: ' + result.message, 'error');
                    }
                }
            } catch (error) {
                if (typeof showToast === 'function') {
                    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) {
                if (typeof showToast === 'function') {
                    showToast("Tarea no encontrada para editar.", 'error');
                }
                return;
            }

            DOMElements.editTaskIdInput.value = task.id;
            DOMElements.editTaskTitleInput.value = decodeHtmlEntities(task.title || '');
            DOMElements.editTaskDescriptionInput.value = decodeHtmlEntities(task.description || '');
            DOMElements.editTaskDueDateInput.value = task.due_date || '';
            DOMElements.editTaskPrioritySelect.value = task.priority || 'Media';
            DOMElements.editTaskClientIdInput.value = task.client_id || '';
            DOMElements.editTaskClientNameInput.value = decodeHtmlEntities(task.client_name || '');
            DOMElements.editTaskProspectIdInput.value = task.lead_id || '';
            DOMElements.editTaskProspectNameInput.value = decodeHtmlEntities(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) {
                    if (typeof showToast === 'function') {
                        showToast(`Tarea ${isEdit ? 'actualizada' : 'agregada'} con éxito.`, 'success');
                    }
                    isEdit ? closePanel(DOMElements.editTaskPanel, DOMElements.taskPanelOverlay) : closePanel(DOMElements.taskPanel, DOMElements.taskPanelOverlay);
                    await initDashboard();
                } else {
                    if (typeof showToast === 'function') {
                        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);
                if (typeof showToast === 'function') {
                    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 => {
                    const fullName = (item.name || '').toLowerCase().trim();
                    return fullName.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';
                    
                    const displayName = item.name || '';
                    suggestionItem.textContent = decodeHtmlEntities(displayName);

                    suggestionItem.addEventListener('click', function() {
                        inputElement.value = displayName;
                        hiddenIdElement.value = item.id;
                        selectedSuggestion = item;
                        suggestionsDiv.classList.add('hidden');

                        const otherInput = (type === 'client')
                            ? (inputElement.id.includes('add-') ? document.getElementById('add-task-prospect-name') : document.getElementById('edit-task-prospect-name'))
                            : (inputElement.id.includes('add-') ? document.getElementById('add-task-client-name') : document.getElementById('edit-task-client-name'));
                        
                        const otherHiddenId = (type === 'client')
                            ? (inputElement.id.includes('add-') ? document.getElementById('add-task-prospect-id') : document.getElementById('edit-task-prospect-id'))
                            : (inputElement.id.includes('add-') ? document.getElementById('add-task-client-id') : document.getElementById('edit-task-client-id'));

                        if (otherInput) {
                            otherInput.value = '';
                            otherInput.disabled = true;
                        }
                        if (otherHiddenId) {
                            otherHiddenId.value = '';
                        }
                    });
                    suggestionsDiv.appendChild(suggestionItem);
                });
            });

            inputElement.addEventListener('blur', function() {
                setTimeout(() => {
                    suggestionsDiv.classList.add('hidden');
                    
                    const selectedName = selectedSuggestion ? (selectedSuggestion.name || '') : '';
                    if (selectedSuggestion && selectedName.toLowerCase() !== this.value.toLowerCase()) {
                        hiddenIdElement.value = '';
                    }
                    
                    if (!this.value && hiddenIdElement.value === '') {
                        const otherInput = (type === 'client')
                            ? (inputElement.id.includes('add-') ? document.getElementById('add-task-prospect-name') : document.getElementById('edit-task-prospect-name'))
                            : (inputElement.id.includes('add-') ? document.getElementById('add-task-client-name') : document.getElementById('edit-task-client-name'));
                        if (otherInput) {
                             otherInput.disabled = false;
                        }
                    }
                }, 150);
            });

            inputElement.addEventListener('focus', function() {
                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,
                        pendingEstimates: dashboardResult.data.pendingEstimates || 0, 
                        overdueInvoices: dashboardResult.data.overdueInvoices || 0 
                    };
                    APP_DATA.upcomingAppointments = dashboardResult.data.upcomingAppointments || [];
                    APP_DATA.allTasks = dashboardResult.data.allTasks || [];
                    APP_DATA.trackingProspectsList = dashboardResult.data.trackingProspectsList || [];
                    APP_DATA.pendingEstimatesList = dashboardResult.data.pendingEstimatesList || []; 
                    APP_DATA.overdueInvoicesList = dashboardResult.data.overdueInvoicesList || []; 
                } else {
                    if (typeof showToast === 'function') {
                        showToast('Error al cargar datos del dashboard: ' + (dashboardResult.message || 'Error desconocido.'), 'error');
                    }
                }

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

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

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

            updateSummaryCards();
            renderUpcomingAppointments();
            renderProspectos();
            renderPendingEstimates(); 
            renderOverdueInvoices(); 
            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');
            const estimateBtn = target.closest('.go-to-estimates-btn'); 
            const invoiceBtn = target.closest('.go-to-invoices-btn'); 

            if (editBtn) openEditTaskPanel(editBtn.dataset.taskId);
            else if (completeBtn) updateTaskStatus(completeBtn.dataset.taskId, 'completed');
            else if (uncompleteBtn) updateTaskStatus(uncompleteBtn.dataset.taskId, 'pending');
            else if (deleteBtn) openConfirmDeleteModal(deleteBtn.dataset.taskId, 'tarea');
            else if (editProspectBtn) window.location.href = 'leads.php';
            else if (agendaBtn) window.location.href = 'agenda.php';
            else if (estimateBtn) window.location.href = 'quote.php'; 
            else if (invoiceBtn) window.location.href = 'invoices.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.viewAllEstimatesButton.addEventListener('click', () => { window.location.href = "quotes.php"; });
        DOMElements.viewAllInvoicesButton.addEventListener('click', () => { window.location.href = "invoices.php"; });
        
        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,
                client_name: DOMElements.addTaskClientNameInput.value || null,
                lead_id: DOMElements.addTaskProspectIdInput.value || null,
                prospect_name: DOMElements.addTaskProspectNameInput.value || null,
                due_date: DOMElements.addTaskDueDateInput.value,
                priority: DOMElements.addTaskPrioritySelect.value,
                status: 'pending'
            };
            if (!taskData.title || !taskData.due_date) {
                if (typeof showToast === 'function') {
                    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,
                client_name: DOMElements.editTaskClientNameInput.value || null,
                lead_id: DOMElements.editTaskProspectIdInput.value || null,
                prospect_name: DOMElements.editTaskProspectNameInput.value || null,
                due_date: DOMElements.editTaskDueDateInput.value,
                priority: DOMElements.editTaskPrioritySelect.value
            };

            if (!taskData.title || !taskData.due_date) {
                if (typeof showToast === 'function') {
                    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);
        DOMElements.pendingEstimatesList.addEventListener('click', handleListClick);
        DOMElements.overdueInvoicesList.addEventListener('click', handleListClick);

        initDashboard();
    });
})();
</script>
<script>
document.addEventListener('DOMContentLoaded', () => {

    // Función principal que maneja el ocultamiento, la reaparición y el Local Storage
    const toggleWidgetVisibility = (widgetId, isHidden) => {
        const widget = document.getElementById(widgetId);
        // Encuentra el contenedor del botón de mostrar usando el data-widget-id
        const showContainer = document.querySelector(`.show-widget-container [data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
        const videoPlayer = widget ? widget.querySelector('video') : null;

        if (!widget || !showContainer) return; // Se detiene si no encuentra los elementos

        if (isHidden) {
            // Acción para OCULTAR
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            // IMPORTANTE: Detiene el video para ahorrar recursos
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            // Acción para MOSTRAR
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }

        // Guarda la preferencia en Local Storage, individualmente para cada widget
        localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
    };

    // 1. Configurar los botones de OCULTAR (clase: hide-widget-btn)
    document.querySelectorAll('.hide-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a ocultar
            toggleWidgetVisibility(widgetId, true); 
        });
    });

    // 2. Configurar los botones de MOSTRAR (clase: show-widget-btn)
    document.querySelectorAll('.show-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a mostrar
            toggleWidgetVisibility(widgetId, false); 
        });
    });

    // 3. Comprobar y aplicar el estado guardado al cargar la página para TODOS los widgets
    document.querySelectorAll('.video-widget').forEach(widget => {
        const widgetId = widget.id;
        const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
        if (isHidden) {
            // Si el usuario lo ocultó antes, se aplica el estado de oculto
            toggleWidgetVisibility(widgetId, true);
        }
    });
});
</script>
</body>
</html>