<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

define('RENEWAL_DATE', '2025-10-31');
define('WEBSITE_URL', 'demoflow.generamasclientes.com');

// =================================================================
// BLOQUE 2: LÓGICA DE NEGOCIO Y PREPARACIÓN DE DATOS
// =================================================================

$days_left = 0;
$renewal_date_formatted = date("d/m/Y", strtotime(RENEWAL_DATE));
$countdown_style_class = 'bg-gradient-to-r from-[var(--brand-primary)] to-[var(--brand-dark)]'; 

try {
    $renewal_date_obj = new DateTime(RENEWAL_DATE);
    $today = new DateTime("now");
    
    if ($today < $renewal_date_obj) {
        $days_left = $today->diff($renewal_date_obj)->days;
    }

    if ($days_left <= 7) {
        $countdown_style_class = 'bg-gradient-to-r from-red-700 to-red-900';
    } elseif ($days_left <= 30) {
        $countdown_style_class = 'bg-gradient-to-r from-amber-600 to-orange-800';
    }
} catch (Exception $e) {
    error_log("Error al calcular la fecha de renovación: " . $e->getMessage());
    $days_left = 0;
}

$prospects_data_from_db = [];
try {
    $stmt = $pdo->query("SELECT id, first_name, last_name, company, email, phone, mobile, source, status, street_address, city, state_province, zip_code, created_at FROM leads WHERE status <> 'Descartado' ORDER BY created_at DESC, first_name ASC");
    $db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_prospects_rows as $row) {
        $prospects_data_from_db[$row['id']] = [
            'id' => $row['id'],
            'first_name' => $row['first_name'] ?? '',
            'last_name'  => $row['last_name'] ?? '',
            'nombre_completo' => trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? '')),
            'empresa'    => $row['company'] ?? '',
            'email'      => $row['email'],
            'phone'      => $row['phone'],
            'mobile'     => $row['mobile'] ?? '',
            'fuente'     => $row['source'],
            'estado'     => $row['status'],
            'direccion_calle' => $row['street_address'],
            'ciudad'     => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code'   => $row['zip_code'],
            'created_at' => $row['created_at']
        ];
    }
} catch (PDOException $e) {
    error_log("Error al cargar prospectos desde la DB en cms-dashboard.php: " . $e->getMessage());
}
$prospects_json = json_encode($prospects_data_from_db);

$userName  = htmlspecialchars($_SESSION['user_first_name'] ?? 'Usuario');
$leadsHoy  = 0;
$topSource = 'N/A';
try {
    $leadsHoy = $pdo->query("SELECT count(id) FROM leads WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $topSourceStmt = $pdo->query("SELECT source, COUNT(id) as count FROM leads GROUP BY source ORDER BY count DESC LIMIT 1");
    if ($topSourceStmt) {
        $topSourceResult = $topSourceStmt->fetch(PDO::FETCH_ASSOC);
        if ($topSourceResult && !empty($topSourceResult['source'])) {
            $topSource = htmlspecialchars($topSourceResult['source']);
        }
    }
} catch (PDOException $e) {
    error_log("Error en DB para KPIs del dashboard: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Dashboard FlowCMS™  De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">
    
  <?php include 'files/gtm-head.php'; ?>

  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
  <script src="https://unpkg.com/lucide@latest"></script>
  <script src="https://unpkg.com/imask"></script>

  <link rel="stylesheet" href="style.css">
  <script src="files/header-manager.js"></script>

    <style>
        @media (max-width: 768px) {
            .page-header-container,
            #page-title,
            #page-subtitle {
                display: none !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; }

        .toolbar-sticky {
            position: sticky;
            top: calc(var(--header-height) + 12px);
            z-index: 10;
            backdrop-filter: blur(6px);
        }

        @media (max-width: 480px) {
            .dashboard-section .grid { gap: 12px !important; }
            .stat-card, .lead-card, .card, .panel, .box {
                padding: 14px !important;
                border-radius: 14px !important;
                box-shadow: 0 10px 22px rgba(0, 0, 0, .06) !important;
            }
            [data-lucide] {
                width: 32px !important;
                height: 32px !important;
            }
            .stat-card h3, .lead-card h3, .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, .lead-card .text-sm, .card .text-sm { font-size: .75rem !important; }
        }

        @media (max-width: 640px) {
            table.responsive-stack { width: 100% !important; border-collapse: collapse; display: block; }
            table.responsive-stack thead { display: none !important; }
            table.responsive-stack tbody { display: block; width: 100%; }
            table.responsive-stack tbody tr {
                display: block; background: #ffffff; border-radius: 12px; margin: 10px 0;
                box-shadow: 0 8px 18px rgba(0, 0, 0, .06); overflow: hidden;
            }
            table.responsive-stack tbody td {
                display: grid; grid-template-columns: 42% 1fr; gap: 8px; padding: 10px 12px;
                border-bottom: 1px solid rgba(0, 0, 0, .06); align-items: start; white-space: normal;
            }
            table.responsive-stack tbody td:last-child { border-bottom: none; }
            table.responsive-stack tbody td::before {
                content: attr(data-label); font-weight: 800; font-size: .72rem; letter-spacing: .02em;
                text-transform: uppercase; color: #6B7280;
            }
        }

    </style>
</head>
<body data-page-title="Bienvenido Al Dashboard FlowCMS®"
      data-page-subtitle="Administra Tu Página SiteFlow®, Clientes y Prospectos"
      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 'cms-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">
    <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="flowcms-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 id="flowcms-intro-video" class="p-6 md:p-10 video-widget">
                <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="megaphone" class="w-4 h-4"></i> BIENVENIDO A SITE FLOWCMS™</span>
                        <h1 class="mt-3 text-3xl md:text-4xl font-extrabold leading-tight text-[var(--color-highlight)]">Administra Tu Página Web Y Las Oportunidades De Crecimiento</h1>
                        <p class="mt-2 text-white/90 max-w-2xl">
                            Publica y edita contenido, centraliza clientes y leads, y recibe contactos desde tus formularios web en tiempo real.
                        </p>
                        <div class="mt-4 flex flex-wrap gap-2">
                            <a href="#prospectos" class="hero-cta"><i data-lucide="user-pen" class="w-5 h-5"></i> IR A PROSPECTOS</a>
                            <a href="clients.php" class="hero-cta secondary"><i data-lucide="users" class="w-4 h-4"></i> VER CLIENTES</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" 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/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" 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="flowcms-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 id="prospectos" class="dashboard-section">
          <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
            <div class="xl:col-span-8 space-y-6">

              <div class="bg-white/80 ring-1 ring-black/5 rounded-xl p-4 toolbar-sticky">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                  <div class="flex items-center gap-3">
                    <div class="view-toggle inline-flex bg-gray-200 rounded-lg p-1">
                      <button id="kanban-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 active uppercase" title="Vista de Tablero">
                        <i data-lucide="layout-grid" class="w-5 h-5"></i>
                      </button>
                      <button id="table-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold transition-colors duration-200 uppercase" title="Vista de Tabla">
                        <i data-lucide="list" class="w-5 h-5"></i>
                      </button>
                    </div>
                    <button class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center justify-center uppercase"
                            onclick="openPanel('addProspectoPanel')">
                      <i data-lucide="plus" class="w-5 h-5 mr-2"></i> AGREGAR
                    </button>
                  </div>

                  <div class="flex flex-col md:flex-row items-stretch md:items-center gap-3 md:max-w-md md:ml-auto">
                    <div class="relative flex-1">
                      <input type="text" id="prospect-search" placeholder="Buscar Por Nombre..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                      <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i>
                    </div>
                    <select id="prospect-filter-status" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                      <option value="all">TODOS</option>
                      <option value="Nuevo">NUEVO</option>
                      <option value="Contactado">CONTACTADO</option>
                      <option value="Cotizacion enviada">COTIZACIÓN ENVIADA</option>
                      <option value="Seguimiento">SEGUIMIENTO</option>
                      <option value="Recordatorio de seguimiento">RECORDATORIO</option>
                      <option value="Ultimo recordatorio">ÚLTIMO RECORDATORIO</option>
                    </select>
                  </div>
                </div>
              </div>

              <div class="bg-white p-6 rounded-xl shadow-md">
                <div class="flex flex-col items-center text-center mb-6">
                  <h3 class="text-2xl font-extrabold text-gray-800 flex items-center justify-center gap-2">
                    <i data-lucide="trending-up" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                    PANEL DE CLIENTES POTENCIALES
                  </h3>
                  <p class="text-gray-500 text-sm mt-1 uppercase">ORGANIZA, FILTRA Y DA SEGUIMIENTO A TUS LEADS.</p>
                </div>

                <div id="prospectos-kanban-view" class="kanban-board grid grid-cols-1 md:grid-cols-1 gap-6"></div>

                <div id="prospectos-table-view" class="overflow-x-auto hidden">
                  <table class="min-w-full bg-white responsive-stack">
                    <thead class="bg-gray-50">
                      <tr class="text-left text-gray-500 uppercase text-sm">
                        <th class="py-3 px-6 font-semibold">NOMBRE</th>
                        <th class="py-3 px-6 font-semibold hidden md:table-cell">TELÉFONO</th>
                        <th class="py-3 px-6 font-semibold hidden lg:table-cell">EMAIL</th>
                        <th class="py-3 px-6 font-semibold">ESTADO</th>
                        <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                      </tr>
                    </thead>
                    <tbody class="text-gray-700 text-sm" id="prospectsTableBody"></tbody>
                  </table>
                </div>
              </div>

            </div>

            <aside class="xl:col-span-4 space-y-6">

              <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-1 gap-4">
                
                <section class="renewal-widget text-white rounded-2xl shadow-lg p-6 text-center flex flex-col items-center justify-center <?php echo htmlspecialchars($countdown_style_class); ?>">
                    <h2 class="text-sm font-bold uppercase tracking-widest text-white/80">
                        RENOVACIÓN DE TU MEMBRESÍA
                    </h2>
                    <p class="text-xl font-bold text-[var(--color-highlight)] mt-1 mb-2">
                        <?php echo htmlspecialchars(WEBSITE_URL); ?>
                    </p>
                    <div class="flex items-center justify-center gap-4 my-1">
                        <i data-lucide="calendar-clock" class="w-12 h-12 opacity-75"></i>
                        <span class="text-7xl font-extrabold tracking-tighter">
                            <?php echo $days_left; ?>
                        </span>
                    </div>
                    <p class="text-md font-bold uppercase tracking-widest mt-1 mb-4">
                        DÍAS RESTANTES
                    </p>
                    <div class="text-xs text-white/70">
                        Fecha De Renovación: <?php echo $renewal_date_formatted; ?>
                    </div>
                </section>
                <div class="stat-card bg-white p-6 rounded-xl shadow-md border-l-4 border-[var(--color-primary)]">
                  <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
                  <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1">TOTAL PROSPECTOS</h3>
                    <p id="total-prospectos-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                    <p class="text-sm text-gray-400 mt-1 uppercase">Activos</p>
                  </div>
                </div>

                <div class="stat-card bg-white p-6 rounded-xl shadow-md border-l-4 border-blue-500">
                  <i data-lucide="calendar" class="w-12 h-12 text-gray-700"></i>
                  <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1">PROSPECTOS (MES)</h3>
                    <p id="monthly-prospectos-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</p>
                    <div class="mt-2 flex items-center">
                      <select id="month-filter-select" class="p-2 border border-gray-300 rounded-lg text-sm bg-white focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]"></select>
                    </div>
                  </div>
                </div>

                <div class="stat-card bg-white p-6 rounded-xl shadow-md border-l-4 border-green-500">
                  <i data-lucide="calendar-plus" class="w-12 h-12 text-gray-700"></i>
                  <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1">NUEVOS HOY</h3>
                    <p class="text-5xl font-bold text-[var(--color-secondary)]"><?php echo $leadsHoy; ?></p>
                    <p class="text-sm text-gray-400 mt-1 uppercase">Registrados hoy</p>
                  </div>
                </div>

                <div class="stat-card bg-white p-6 rounded-xl shadow-md border-l-4 border-purple-500">
                  <i data-lucide="megaphone" class="w-12 h-12 text-gray-700"></i>
                  <div>
                    <h3 class="text-lg font-extrabold text-gray-500 mb-1">FUENTE PRINCIPAL</h3>
                    <p class="text-3xl font-bold text-[var(--color-secondary)] truncate"><?php echo $topSource; ?></p>
                    <p class="text-sm text-gray-400 mt-1 uppercase">Canal más efectivo</p>
                  </div>
                </div>
              </div>

                <?php include 'push.php'; ?>
            </aside>
            
            <div class="xl:col-span-12 mt-6 bg-white p-6 rounded-xl shadow-md">
              <h3 class="text-2xl font-extrabold text-[var(--color-primary)] mb-2 flex items-center gap-2">
                <i data-lucide="bell" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                PROSPECTOS EN SEGUIMIENTO
              </h3>
              <p class="text-gray-500 text-sm mb-4 uppercase">PROSPECTOS QUE REQUIEREN ATENCIÓN Y SEGUIMIENTO ACTIVO.</p>
              <div id="seguimiento-table-view" class="overflow-x-auto">
                <table class="min-w-full bg-white responsive-stack">
                  <thead class="bg-gray-50">
                    <tr class="text-left text-gray-500 uppercase text-sm">
                      <th class="py-3 px-6 font-semibold">NOMBRE</th>
                      <th class="py-3 px-6 font-semibold hidden md:table-cell">TELÉFONO</th>
                      <th class="py-3 px-6 font-semibold hidden lg:table-cell">EMAIL</th>
                      <th class="py-3 px-6 font-semibold">ESTADO</th>
                      <th class="py-3 px-6 font-semibold text-center actions-cell">ACCIONES</th>
                    </tr>
                  </thead>
                  <tbody class="text-gray-700 text-sm" id="seguimientoTableBody"></tbody>
                </table>
              </div>
            </div>
            
          </div>
        </section>
      </div>
    </main>
  </div>

<div id="addProspectoPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">AGREGAR NUEVO PROSPECTO</h3>
            <button onclick="closePanel('addProspectoPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="add-prospecto-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                <div>
                    <label for="prospecto-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Primer Nombre</label>
                    <input type="text" id="prospecto-first-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Primer Nombre" required>
                </div>
                <div>
                    <label for="prospecto-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label>
                    <input type="text" id="prospecto-last-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido" required>
                </div>
                <div>
                    <label for="prospecto-empresa-add" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMPRESA (Opcional)</label>
                    <input type="text" id="prospecto-empresa-add" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Nombre Del Negocio">
                </div>
                <div>
                    <label for="prospecto-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMAIL</label>
                    <input type="email" id="prospecto-email" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@paginaweb.com" required>
                </div>
                <div>
                    <label for="prospecto-telefono" class="block text-gray-700 text-sm font-bold mb-2 uppercase">TELÉFONO FIJO</label>
                    <input type="tel" id="prospecto-telefono" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>
                <div>
                    <label for="prospecto-celular" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CELULAR</label>
                    <input type="tel" id="prospecto-celular" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>
                <div class="md:col-span-2">
                    <label for="prospecto-fuente" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FUENTE</label>
                    <input type="text" id="prospecto-fuente" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej: Facebook, Referido, etc.">
                </div>
                <div class="md:col-span-2">
                    <label for="prospecto-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                    <input type="text" id="prospecto-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                </div>
                <div class="col-span-1">
                    <label for="prospecto-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CIUDAD</label>
                    <input type="text" id="prospecto-ciudad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                </div>
                <div class="col-span-1">
                    <label for="prospecto-estado-provincia" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label> <input type="text" id="prospecto-estado-provincia" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                </div>
                <div class="md:col-span-2">
                    <label for="prospecto-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CÓDIGO POSTAL</label>
                    <input type="text" id="prospecto-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62704">
                </div>
            </div>
            <div class="mt-8 flex justify-end">
                <button type="submit" class="btn-primary font-bold py-3 px-6 rounded-lg flex items-center justify-center uppercase">
                    <i data-lucide="save" class="w-5 h-5 mr-2"></i> GUARDAR PROSPECTO
                </button>
            </div>
        </form>
    </div>
</div>

<div id="editProspectoPanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">EDITAR PROSPECTO</h3>
            <button onclick="closePanel('editProspectoPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="edit-prospecto-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="edit-prospecto-id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                <div>
                    <label for="edit-prospecto-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Primer Nombre</label>
                    <input type="text" id="edit-prospecto-first-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="PrimerNombre" required>
                </div>
                <div>
                    <label for="edit-prospecto-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label>
                    <input type="text" id="edit-prospecto-last-name" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido" required>
                </div>
                <div>
                    <label for="edit-prospecto-empresa" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMPRESA (Opcional)</label>
                    <input type="text" id="edit-prospecto-empresa" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Nombre Del Negocio">
                </div>
                <div>
                    <label for="edit-prospecto-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">EMAIL</label>
                    <input type="email" id="edit-prospecto-email" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@paginaweb.com">
                </div>
                <div>
                    <label for="edit-prospecto-telefono" class="block text-gray-700 text-sm font-bold mb-2 uppercase">TELÉFONO FIJO</label>
                    <input type="tel" id="edit-prospecto-telefono" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>
                <div>
                    <label for="edit-prospecto-celular" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CELULAR</label>
                    <input type="tel" id="edit-prospecto-celular" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>
                <div class="md:col-span-2">
                    <label for="edit-prospecto-fuente" class="block text-gray-700 text-sm font-bold mb-2 uppercase">FUENTE</label>
                    <input type="text" id="edit-prospecto-fuente" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej: Facebook, Referido, etc.">
                </div>
                <div class="md:col-span-2">
                    <label for="edit-prospecto-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                    <input type="text" id="edit-prospecto-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                </div>
                <div class="col-span-1">
                    <label for="edit-prospecto-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CIUDAD</label>
                    <input type="text" id="edit-prospecto-ciudad" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                </div>
                <div class="col-span-1">
                    <label for="edit-prospecto-estado-provincia" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label> <input type="text" id="edit-prospecto-estado-provincia" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                </div>
                <div class="md:col-span-2">
                    <label for="edit-prospecto-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">CÓDIGO POSTAL</label>
                    <input type="text" id="edit-prospecto-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62704">
                </div>
                <div class="md:col-span-2">
                    <label for="edit-prospecto-status" class="block text-gray-700 text-sm font-bold mb-2 uppercase">ESTADO</label>
                    <select id="edit-prospecto-status" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white"></select>
                </div>
            </div>
            <div class="mt-8 flex justify-end">
                <button type="submit" class="btn-primary font-bold py-3 px-6 rounded-lg flex items-center justify-center uppercase">
                    <i data-lucide="save" class="w-5 h-5 mr-2"></i> GUARDAR CAMBIOS
                </button>
            </div>
        </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 PROSPECTO? ESTA ACCIÓN NO SE PUEDE DESHACER.</p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="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>

<div id="confirmConvertModal" 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="user-check" 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 CONVERSIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿Estás seguro de que deseas convertir a <span id="convert-prospect-name" class="font-semibold">este prospecto</span> en un cliente? </p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmConvertModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-convert-button">CONFIRMAR</button>
        </div>
    </div>
</div>

<script>
// === TU JS ORIGINAL (sin cambios de lógica) ===
let prospectsData = <?php echo $prospects_json; ?>;
let filteredProspects = [];
let currentMonthFilter = '';
let prospectIdToConvert = null;
let currentView = 'kanban';

const prospectSearchInput = document.getElementById('prospect-search');
const prospectFilterStatusSelect = document.getElementById('prospect-filter-status');
const monthFilterSelect = document.getElementById('month-filter-select');
const prospectosKanbanView = document.getElementById('prospectos-kanban-view');
const prospectosTableView = document.getElementById('prospectos-table-view');
const prospectsTableBody = document.getElementById('prospectsTableBody');
const seguimientoTableBody = document.getElementById('seguimientoTableBody');
const kanbanViewBtn = document.getElementById('kanban-view-btn');
const tableViewBtn = document.getElementById('table-view-btn');
const totalProspectosCount = document.getElementById('total-prospectos-count');
const monthlyProspectosCount = document.getElementById('monthly-prospectos-count');
const addProspectoForm = document.getElementById('add-prospecto-form');
const editProspectoForm = document.getElementById('edit-prospecto-form');
const confirmConvertButton = document.getElementById('confirm-convert-button');
const convertProspectNameSpan = document.getElementById('convert-prospect-name');
const mobileMenuButton = document.getElementById('mobile-menu-button');
const sidebar = document.getElementById('sidebar');
const sidebarOverlay = document.getElementById('sidebar-overlay');
const phoneInput = document.getElementById('contact_phone');

const mainStatuses = {
    "Entrante": { title: "LEADS ENTRANTES", icon: "inbox", color: "var(--color-secondary)" },
    "Nuevo": { title: "LEADS NUEVOS", icon: "user-plus", color: "#3B82F6" },
    "Contactado": { title: "LEADS CONTACTADOS", icon: "phone", color: "#F59E0B" }
};
const trackingStatuses = {
    "Cotizacion enviada": { title: "COTIZACIÓN ENVIADA", icon: "file-text", color: "#10B981" },
    "Seguimiento": { title: "SEGUIMIENTO", icon: "bell", color: "#FBBF24" },
    "Recordatorio de seguimiento": { title: "RECORDATORIO", icon: "alarm-check", color: "#60A5FA" },
    "Ultimo recordatorio": { title: "ÚLTIMO RECORDATORIO", icon: "alert-triangle", color: "#EF4444" }
};
const allStatuses = { ...mainStatuses, ...trackingStatuses };

function recreateLucideIcons(element) {
    if (!element) return;
    if (typeof lucide !== 'undefined' && lucide.createIcons) {
        lucide.createIcons({ container: element });
    }
}
function formatPhoneNumber(number) {
    if (!number) return '';
    const cleaned = ('' + number).replace(/\D/g, '');
    const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
    if (match) { return `(${match[1]}) ${match[2]}-${match[3]}`; }
    return cleaned;
}
function applyInputPhoneFormat(inputElement) {
    if (!inputElement) return;
    inputElement.value = formatPhoneNumber(inputElement.value);
    inputElement.addEventListener('input', (e) => {
        let value = e.target.value.replace(/\D/g, '');
        e.target.value = formatPhoneNumber(value);
    });
}
function applyPhoneFormatToInputs() {
    applyInputPhoneFormat(document.getElementById('prospecto-telefono'));
    applyInputPhoneFormat(document.getElementById('prospecto-celular'));
    applyInputPhoneFormat(document.getElementById('edit-prospecto-telefono'));
    applyInputPhoneFormat(document.getElementById('edit-prospecto-celular'));
}
function getMonthName(m){return ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'][m];}

const panelOverlay = document.createElement('div');
panelOverlay.id = 'panel-overlay';
panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
document.body.appendChild(panelOverlay);

function openPanel(panelId){const p=document.getElementById(panelId);if(!p){showToast(`Error: Panel "${panelId}" no encontrado.`,'error');return;}p.classList.remove('translate-x-full');p.classList.add('translate-x-0');panelOverlay.classList.remove('hidden');document.body.style.overflow='hidden';recreateLucideIcons(p);}
function closePanel(panelId){const p=document.getElementById(panelId);if(!p)return;p.classList.remove('translate-x-0');p.classList.add('translate-x-full');panelOverlay.classList.add('hidden');document.body.style.overflow='';}
function openModal(id){const m=document.getElementById(id);if(!m){showToast(`Error: Modal "${id}" no encontrado.`,'error');return;}const b=m.querySelector('div:first-of-type');m.classList.remove('hidden');setTimeout(()=>{b.classList.remove('scale-95','opacity-0');},50);panelOverlay.classList.remove('hidden');document.body.style.overflow='hidden';recreateLucideIcons(m);}
function closeModal(id){const m=document.getElementById(id);if(!m)return;const b=m.querySelector('div:first-of-type');b.classList.add('scale-95','opacity-0');setTimeout(()=>{m.classList.add('hidden');panelOverlay.classList.add('hidden');document.body.style.overflow='';},300);}

window.openConfirmDeleteModal=function(itemId){const btn=document.getElementById('confirm-delete-button');if(!btn){showToast("Error: Botón de confirmación no encontrado.",'error');return;}btn.dataset.itemId=itemId;btn.onclick=async function(){const id=this.dataset.itemId;try{const r=await fetch('db/leads-delete.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id})});const res=await r.json();if(res.success){showToast('Prospecto eliminado con éxito.','success');location.reload();}else{showToast(res.message||'Error al eliminar prospecto.','error');}}catch(e){showToast('Error de conexión al eliminar prospecto.','error');}finally{closeModal('confirmDeleteModal');}};openModal('confirmDeleteModal');};
window.openConfirmConvertModal=function(id){const p=prospectsData[id];if(!p){showToast('Prospecto no encontrado.','error');return;}prospectIdToConvert=id;if(convertProspectNameSpan)convertProspectNameSpan.textContent=p.nombre_completo;openModal('confirmConvertModal');};
window.openEditPanel=function(id){const p=prospectsData[id];if(p){document.getElementById('edit-prospecto-id').value=p.id;document.getElementById('edit-prospecto-first-name').value=p.first_name||'';document.getElementById('edit-prospecto-last-name').value=p.last_name||'';document.getElementById('edit-prospecto-empresa').value=p.empresa||'';document.getElementById('edit-prospecto-email').value=p.email||'';document.getElementById('edit-prospecto-telefono').value=p.phone||'';document.getElementById('edit-prospecto-celular').value=p.mobile||'';document.getElementById('edit-prospecto-fuente').value=p.fuente||'';document.getElementById('edit-prospecto-direccion-calle').value=p.direccion_calle||'';document.getElementById('edit-prospecto-ciudad').value=p.ciudad||'';document.getElementById('edit-prospecto-estado-provincia').value=p.state_province||'';document.getElementById('edit-prospecto-codigo-postal').value=p.zip_code||'';const s=document.getElementById('edit-prospecto-status');if(s){s.innerHTML='';for(const k in allStatuses){const o=document.createElement('option');o.value=k;o.textContent=allStatuses[k].title;s.appendChild(o);}s.value=p.estado;}openPanel('editProspectoPanel');applyPhoneFormatToInputs();}else{showToast('Prospecto no encontrado para editar.','error');}};

async function convertToClientLogic(){if(!prospectIdToConvert){showToast('No se ha seleccionado ningún prospecto.','error');return;}try{showToast('Convirtiendo a cliente...','info');closeModal('confirmConvertModal');const r=await fetch('db/leads-convert-to-client.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({prospect_id:prospectIdToConvert})});const res=await r.json();if(res.success){showToast(res.message||'Prospecto convertido con éxito.','success');location.reload();}else{showToast(res.message||'Error al convertir prospecto.','error');}}catch(e){showToast('Error de conexión al convertir prospecto.','error');}finally{prospectIdToConvert=null;}}
async function updateProspectStatus(id,status){try{const r=await fetch('db/leads-update-status.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,status})});const res=await r.json();if(res.success){showToast('Estado actualizado.','success');location.reload();}else{showToast(res.message||'Error al actualizar estado.','error');}}catch(e){showToast('Error de conexión al actualizar estado.','error');}}

function populateMonthFilter(){const now=new Date();const set=new Set();const ym=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;set.add(ym);Object.values(prospectsData).forEach(p=>{if(p.created_at){const d=new Date(p.created_at);set.add(`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`);}});const sorted=Array.from(set).map(m=>new Date(m+'-02')).sort((a,b)=>b-a);monthFilterSelect.innerHTML='<option value="all">TODOS LOS MESES</option>';sorted.forEach(d=>{const i=d.getMonth();const y=d.getFullYear();const o=document.createElement('option');o.value=`${y}-${String(i+1).padStart(2,'0')}`;o.textContent=`${getMonthName(i).toUpperCase()} ${y}`;monthFilterSelect.appendChild(o);});monthFilterSelect.value=ym;currentMonthFilter=ym;}

function createProspectCard(p){const c=document.createElement('div');c.className='kanban-card bg-white p-4 rounded-lg shadow-sm border border-gray-200 cursor-grab active:cursor-grabbing';c.setAttribute('draggable',true);c.setAttribute('data-prospect-id',p.id);let actions='';if(p.estado==='Entrante'){actions=`<div class="mt-4 flex flex-col space-y-2">
<button class="btn-primary flex items-center justify-center py-2 px-4 rounded-md text-sm uppercase approve-prospecto-btn" data-id="${p.id}" title="Aprobar Prospecto"><i data-lucide="check" class="w-5 h-5 mr-2"></i> APROBAR</button>
<button class="bg-red-500 hover:bg-red-600 text-white flex items-center justify-center py-2 px-4 rounded-md text-sm uppercase discard-prospecto-btn" data-id="${p.id}" title="Desechar Prospecto"><i data-lucide="x" class="w-5 h-5 mr-2"></i> DESECHAR</button></div>`;}else{actions=`<div class="mt-4 flex justify-end space-x-2">
<button class="p-2 text-gray-500 hover:text-[var(--color-primary)] rounded-md edit-prospecto-btn" data-id="${p.id}" title="Editar"><i data-lucide="edit" class="w-5 h-5"></i></button>
<button class="p-2 text-gray-500 hover:text-red-500 rounded-md delete-prospecto-btn" data-id="${p.id}" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
<button class="p-2 text-green-600 hover:text-green-800 rounded-md convert-to-client-btn" data-id="${p.id}" title="Convertir a Cliente"><i data-lucide="user-check" class="w-5 h-5"></i></button></div>`;}
c.innerHTML=`<div class="card-header cursor-pointer flex justify-between items-start pb-2 mb-2">
<div><h5 class="font-semibold text-gray-800">${p.nombre_completo}</h5><p class="text-gray-500 text-sm mt-1">${p.empresa||'N/A'}</p></div>
<button class="toggle-details-btn text-gray-400 hover:text-gray-600 p-1 -mr-1 -mt-1"><i data-lucide="chevron-down" class="w-5 h-5"></i></button></div>
<div class="card-details hidden space-y-2 pt-2 border-t border-gray-100">
<div class="flex items-center text-gray-600 text-sm"><i data-lucide="mail" class="w-4 h-4 mr-2 text-gray-400"></i> ${p.email}</div>
<div class="flex items-center text-gray-600 text-sm"><i data-lucide="phone" class="w-4 h-4 mr-2 text-gray-400"></i> ${formatPhoneNumber(p.phone||p.mobile||'')}</div>
<div class="flex items-center text-gray-600 text-sm"><i data-lucide="tag" class="w-4 h-4 mr-2 text-gray-400"></i> ${p.fuente}</div></div>${actions}`;recreateLucideIcons(c);
if(p.estado==='Entrante'){c.querySelector('.approve-prospecto-btn').addEventListener('click',e=>{e.stopPropagation();updateProspectStatus(p.id,'Nuevo');});c.querySelector('.discard-prospecto-btn').addEventListener('click',e=>{e.stopPropagation();updateProspectStatus(p.id,'Descartado');});}
else{c.querySelector('.edit-prospecto-btn').addEventListener('click',e=>{e.stopPropagation();openEditPanel(p.id);});c.querySelector('.delete-prospecto-btn').addEventListener('click',e=>{e.stopPropagation();window.openConfirmDeleteModal(p.id);});c.querySelector('.convert-to-client-btn').addEventListener('click',e=>{e.stopPropagation();openConfirmConvertModal(p.id);});}
const t=c.querySelector('.toggle-details-btn');const d=c.querySelector('.card-details');const fn=(e)=>{e.stopPropagation();d.classList.toggle('hidden');const ic=t.querySelector('i');ic.setAttribute('data-lucide',d.classList.contains('hidden')?'chevron-down':'chevron-up');recreateLucideIcons(t);};t.addEventListener('click',fn);c.querySelector('.card-header').addEventListener('click',e=>{if(!e.target.closest('button'))fn(e);});return c;}

function setupDragAndDrop(el){let drag=null;el.addEventListener('dragstart',e=>{if(e.target.classList.contains('kanban-card')){drag=e.target;setTimeout(()=>e.target.classList.add('dragging'),0);}});el.addEventListener('dragend',e=>{if(drag){drag.classList.remove('dragging');drag=null;}});el.querySelectorAll('.kanban-column').forEach(col=>{const list=col.querySelector('[data-status-list]');list.addEventListener('dragover',e=>{e.preventDefault();});list.addEventListener('drop',async e=>{e.preventDefault();if(!drag)return;const id=drag.dataset.prospectId;const newStatus=col.dataset.status;if(prospectsData[id] && prospectsData[id].estado!==newStatus){if(newStatus==='Entrante')return;list.appendChild(drag);await updateProspectStatus(id,newStatus);}});});}

function renderMainKanbanBoard(arr){prospectosKanbanView.innerHTML='';const toBoard=arr.filter(p=>mainStatuses[p.estado]);for(const key in mainStatuses){const s=mainStatuses[key];const col=document.createElement('div');col.className='kanban-column bg-gray-50 p-4 rounded-xl shadow-inner border-t-4';col.style.borderColor=s.color;col.setAttribute('data-status',key);col.innerHTML=`<h4 class="text-lg font-extrabold text-gray-700 mb-4 flex items-center gap-2 uppercase">
<i data-lucide="${s.icon}" class="w-6 h-6" style="color:${s.color}"></i> ${s.title}</h4><div class="space-y-4 min-h-[100px]" data-status-list="${key}"></div>`;prospectosKanbanView.appendChild(col);}recreateLucideIcons(prospectosKanbanView);toBoard.forEach(p=>{const card=createProspectCard(p);const list=prospectosKanbanView.querySelector(`[data-status-list="${p.estado}"]`);if(list)list.appendChild(card);});setupDragAndDrop(prospectosKanbanView);}

function renderSeguimientoTable(arr){seguimientoTableBody.innerHTML='';const list=arr.filter(p=>trackingStatuses[p.estado]);if(list.length===0){seguimientoTableBody.innerHTML=`<tr><td colspan="5" class="py-4 text-center text-gray-500">NO HAY PROSPECTOS EN SEGUIMIENTO</td></tr>`;return;}list.forEach(p=>{const tr=document.createElement('tr');tr.className='border-b border-gray-100 hover:bg-gray-50';const s=allStatuses[p.estado]||{};tr.innerHTML=`<td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE">${p.nombre_completo} <p class="text-xs text-gray-500">${p.empresa||''}</p></td>
<td class="py-3 px-6 hidden md:table-cell" data-label="TELÉFONO">${formatPhoneNumber(p.phone||p.mobile||'')}</td>
<td class="py-3 px-6 hidden lg:table-cell" data-label="EMAIL">${p.email}</td>
<td class="py-3 px-6" data-label="ESTADO"><span class="px-3 py-1 rounded-full text-xs font-semibold" style="background-color:${s.color}20; color:${s.color};">${s.title||p.estado.toUpperCase()}</span></td>
<td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES"><div class="flex items-center justify-center space-x-2">
<button class="text-gray-500 hover:text-[var(--color-primary)] edit-prospecto-btn" data-id="${p.id}" title="Editar"><i data-lucide="edit" class="w-5 h-5"></i></button>
<button class="text-gray-500 hover:text-red-500 delete-prospecto-btn" data-id="${p.id}" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
<button class="text-green-600 hover:text-green-800 convert-to-client-btn" data-id="${p.id}" title="Convertir a Cliente"><i data-lucide="user-check" class="w-5 h-5"></i></button></div></td>`;seguimientoTableBody.appendChild(tr);recreateLucideIcons(tr);tr.querySelector('.edit-prospecto-btn').addEventListener('click',()=>openEditPanel(p.id));tr.querySelector('.delete-prospecto-btn').addEventListener('click',()=>window.openConfirmDeleteModal(p.id));tr.querySelector('.convert-to-client-btn').addEventListener('click',()=>openConfirmConvertModal(p.id));});}

function renderTable(arr){prospectsTableBody.innerHTML='';const list=arr.filter(p=>!trackingStatuses[p.estado]);if(list.length===0){prospectsTableBody.innerHTML=`<tr><td colspan="5" class="py-4 text-center text-gray-500">No se encontraron prospectos.</td></tr>`;return;}list.forEach(p=>{const tr=document.createElement('tr');tr.className='border-b border-gray-100 hover:bg-gray-50';const s=allStatuses[p.estado]||{};tr.innerHTML=`<td class="py-3 px-6 font-medium text-gray-900" data-label="NOMBRE">${p.nombre_completo} <p class="text-xs text-gray-500">${p.empresa||''}</p></td>
<td class="py-3 px-6 hidden md:table-cell" data-label="TELÉFONO">${formatPhoneNumber(p.phone||p.mobile||'')}</td>
<td class="py-3 px-6 hidden lg:table-cell" data-label="EMAIL">${p.email}</td>
<td class="py-3 px-6" data-label="ESTADO"><span class="px-3 py-1 rounded-full text-xs font-semibold" style="background-color:${s.color}20; color:${s.color};">${s.title||p.estado.toUpperCase()}</span></td>
<td class="py-3 px-6 text-center actions-cell" data-label="ACCIONES"><div class="flex items-center justify-center space-x-2">
<button class="text-gray-500 hover:text-[var(--color-primary)] edit-prospecto-btn" data-id="${p.id}" title="Editar"><i data-lucide="edit" class="w-5 h-5"></i></button>
<button class="text-gray-500 hover:text-red-500 delete-prospecto-btn" data-id="${p.id}" title="Eliminar"><i data-lucide="trash-2" class="w-5 h-5"></i></button></div></td>`;prospectsTableBody.appendChild(tr);recreateLucideIcons(tr);tr.querySelector('.edit-prospecto-btn').addEventListener('click',()=>openEditPanel(p.id));tr.querySelector('.delete-prospecto-btn').addEventListener('click',()=>window.openConfirmDeleteModal(p.id));});}

function updateProspectCounts(){totalProspectosCount.textContent=Object.keys(prospectsData).length;monthlyProspectosCount.textContent=filteredProspects.length;}
function filterAndRenderProspects(){const q=prospectSearchInput.value.toLowerCase();const s=prospectFilterStatusSelect.value;const m=monthFilterSelect.value;filteredProspects=Object.values(prospectsData).filter(p=>{const ms=p.nombre_completo.toLowerCase().includes(q)||(p.empresa&&p.empresa.toLowerCase().includes(q));const st=s==='all'||p.estado===s;let mm=true;if(m!=='all'&&p.created_at){const d=new Date(p.created_at);const ym=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}`;mm=ym===m;}return ms&&st&&mm;});updateProspectCounts();if(currentView==='kanban'){prospectosKanbanView.classList.remove('hidden');prospectosTableView.classList.add('hidden');renderMainKanbanBoard(filteredProspects);}else{prospectosKanbanView.classList.add('hidden');prospectosTableView.classList.remove('hidden');renderTable(filteredProspects);}renderSeguimientoTable(filteredProspects);}

mobileMenuButton.addEventListener('click',()=>{sidebar.classList.toggle('-translate-x-full');sidebarOverlay.classList.toggle('hidden');});
sidebarOverlay.addEventListener('click',()=>{sidebar.classList.add('-translate-x-full');sidebarOverlay.classList.add('hidden');});

const urlParams=new URLSearchParams(window.location.search);
if(urlParams.has('notification_type')&&urlParams.has('notification_message')){showToast(urlParams.get('notification_message'),urlParams.get('notification_type'));}

if(phoneInput&&typeof IMask!=='undefined'){IMask(phoneInput,{mask:'(000) 000-0000'});}

addProspectoForm.addEventListener('submit',async (e)=>{e.preventDefault();const n={first_name:document.getElementById('prospecto-first-name').value,last_name:document.getElementById('prospecto-last-name').value,company:document.getElementById('prospecto-empresa-add').value||'',email:document.getElementById('prospecto-email').value,phone:document.getElementById('prospecto-telefono').value.replace(/\D/g,''),mobile:document.getElementById('prospecto-celular').value.replace(/\D/g,'')||'',source:document.getElementById('prospecto-fuente').value,status:'Entrante',street_address:document.getElementById('prospecto-direccion-calle').value||'',city:document.getElementById('prospecto-ciudad').value||'',state_province:document.getElementById('prospecto-estado-provincia').value||'',zip_code:document.getElementById('prospecto-codigo-postal').value||'',};try{const r=await fetch('db/leads-create.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(n)});const res=await r.json();if(res.success){showToast('Prospecto agregado.','success');location.reload();}else{showToast(res.message||'Error al agregar prospecto.','error');}}catch(err){showToast('Error de conexión al agregar.','error');}});

editProspectoForm.addEventListener('submit',async (e)=>{e.preventDefault();const n={id:document.getElementById('edit-prospecto-id').value,first_name:document.getElementById('edit-prospecto-first-name').value,last_name:document.getElementById('edit-prospecto-last-name').value,company:document.getElementById('edit-prospecto-empresa').value,email:document.getElementById('edit-prospecto-email').value,phone:document.getElementById('edit-prospecto-telefono').value.replace(/\D/g,''),mobile:document.getElementById('edit-prospecto-celular').value.replace(/\D/g,''),source:document.getElementById('edit-prospecto-fuente').value,status:document.getElementById('edit-prospecto-status').value,street_address:document.getElementById('edit-prospecto-direccion-calle').value,city:document.getElementById('edit-prospecto-ciudad').value,state_province:document.getElementById('edit-prospecto-estado-provincia').value,zip_code:document.getElementById('edit-prospecto-codigo-postal').value};try{const r=await fetch('db/leads-update.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(n)});const res=await r.json();if(res.success){showToast('Prospecto actualizado.','success');location.reload();}else{showToast(res.message||'Error al actualizar prospecto.','error');}}catch(err){showToast('Error de conexión al actualizar.','error');}});

kanbanViewBtn.addEventListener('click',()=>{currentView='kanban';kanbanViewBtn.classList.add('active');tableViewBtn.classList.remove('active');filterAndRenderProspects();});
tableViewBtn.addEventListener('click',()=>{currentView='table';tableViewBtn.classList.add('active');kanbanViewBtn.classList.remove('active');filterAndRenderProspects();});

prospectSearchInput.addEventListener('input',filterAndRenderProspects);
prospectFilterStatusSelect.addEventListener('change',filterAndRenderProspects);
monthFilterSelect.addEventListener('change',filterAndRenderProspects);

panelOverlay.addEventListener('click',()=>{closePanel('addProspectoPanel');closePanel('editProspectoPanel');closeModal('confirmDeleteModal');closeModal('confirmConvertModal');});

document.addEventListener('DOMContentLoaded',()=>{populateMonthFilter();filterAndRenderProspects();applyPhoneFormatToInputs();kanbanViewBtn.classList.add('active');if(confirmConvertButton){confirmConvertButton.addEventListener('click',convertToClientLogic);} if (typeof lucide!=='undefined') lucide.createIcons();});
</script>

<script>
(function(){
  function enhanceTables(ctx){
    (ctx || document).querySelectorAll('table.responsive-stack').forEach(function(tb){
      var heads = Array.from(tb.querySelectorAll('thead th')).map(th => (th.textContent||'').trim());
      tb.querySelectorAll('tbody tr').forEach(function(tr){
        tr.children.forEach(function(td, i){
          if (td && !td.hasAttribute('data-label')) td.setAttribute('data-label', heads[i] || '');
        });
      });
    });
  }
  function enhanceDialogs(ctx){
    (ctx || document).querySelectorAll('[role="dialog"], .modal, .swal2-popup').forEach(function(dlg){
      dlg.querySelectorAll('.actions, .modal-actions, .swal2-actions').forEach(function(row){
        if (row.querySelectorAll('button, .swal2-styled').length >= 2) row.classList.add('modal-actions');
      });
    });
  }
  enhanceTables(document);
  enhanceDialogs(document);
  var mo = new MutationObserver(function(muts){
    muts.forEach(function(m){
      m.addedNodes.forEach(function(n){
        if (n.nodeType === 1){
          if (n.querySelector('table')) enhanceTables(n);
          if (n.querySelector('[role="dialog"]')) enhanceDialogs(n);
        }
      });
    });
  });
  try { mo.observe(document.body, {childList: true, subtree: true}); } catch(e) {}
  try { if (window.lucide) window.lucide.createIcons(); } catch(e){}
})();
</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>