<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
$logo_url_for_spinner = htmlspecialchars($branding['favicon'] ?? ''); 
$logo_url_main = htmlspecialchars($logo_url ?? '');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Perfil Completo De Cliente 360 <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>"> 

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
 
    <style>
        .fbi-overlay {
            position: fixed; inset: 0; 
            background: var(--color-primary); 
            z-index: 9999;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
        }
        .loading-container {
            position: relative;
            width: 200px; 
            height: 200px; 
            margin-bottom: 20px;
        }
        .radar {
            width: 100%; height: 100%; 
            border: 2px solid rgba(158,20,40,0.2);
            border-top: 4px solid var(--color-secondary); 
            border-radius: 50%;
            animation: spin 1s linear infinite;
            box-shadow: 0 0 15px rgba(158,20,40,0.5);
            position: absolute;
            top: 0; left: 0;
        }
        .logo-center {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%);
            width: 70%; 
            height: 70%; 
            border-radius: 50%;
            background-color: white; 
            padding: 5px;
            object-fit: contain;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        .blink { animation: blinker 1s linear infinite; }
        @keyframes blinker { 50% { opacity: 0; } }
        
        #results-dropdown {
            position: absolute; width: 100%; bg: white; z-index: 50;
            max-height: 300px; overflow-y: auto; border: 1px solid #e2e8f0;
            border-radius: 0.5rem; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        }
        .result-item:hover { background-color: #f1f5f9; cursor: pointer; }

        .chart-bar-container {
            display: flex;
            align-items: flex-end;
            gap: 4px;
            height: 150px;
            padding-top: 10px;
            margin-top: 10px;
        }
        .chart-bar {
            width: 8.33%; 
            background-color: var(--color-secondary);
            transition: height 0.5s ease-out;
            border-top-left-radius: 2px;
            border-top-right-radius: 2px;
            position: relative;
            cursor: pointer;
        }
        .chart-bar-label {
            position: absolute;
            bottom: -20px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            font-weight: bold;
            color: #64748b;
        }
        .chart-bar-tooltip {
            position: absolute;
            top: -30px;
            left: 50%;
            transform: translateX(-50%);
            background-color: #1f2937;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 10px;
            font-weight: bold;
            white-space: nowrap;
            opacity: 0;
            transition: opacity 0.2s;
            pointer-events: none;
        }
        .chart-bar:hover .chart-bar-tooltip {
            opacity: 1;
        }
    </style>
</head>
<body data-page-title="Perfil Completo Y Detallado De Clientes"
    data-page-subtitle="Todo Lo Que Necesitas Saber De Tu Cliente"
    data-page-icon="radar">
    
    <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="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
    
    <?php include 'menu.php'; ?>
    
    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-md p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="fbi-screen" class="fbi-overlay hidden">
        <div class="loading-container">
            <div class="radar"></div>
            <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="logo-center">
        </div>
        <div id="fbi-text" class="text-2xl font-bold uppercase tracking-widest mb-2 text-white">INICIANDO...</div>
        <div id="fbi-subtext" class="text-md uppercase font-semibold text-gray-400 ">Esperando conexión segura</div>
    </div>

    <div class="flex min-h-screen">

        <main class="flex-1 p-6 md:p-10">
            
            <div class="flex flex-col items-center text-center mb-8">
                <?php if (!empty($biz['logo_url'])): ?>
                    <div class="max-w-60 mb-4 flex items-center justify-center">
                        <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="max-w-full max-h-full object-contain">
                    </div>
                <?php endif; ?>

                <h1 class="text-4xl font-black uppercase text-[var(--color-primary)] mb-2">Busqueda Avanzada</h1>
            </div>

            <div class="max-w-3xl mx-auto mb-10 relative">
                <div class="relative max-w-xl mx-auto">
    <div class="flex items-center w-full shadow-lg rounded-2xl overflow-hidden border-2 border-gray-200 focus-within:border-[var(--color-secondary)] transition-all duration-300">
    
    <div class="relative flex-grow">
        <input 
            type="text" 
            id="search-input" 
            class="w-full h-14 p-4 pl-14 pr-4 bg-white
                   focus:outline-none 
                   text-base font-semibold text-gray-700 placeholder-gray-500
                   border-none ring-0
                   "
            placeholder="Buscar Cliente..." 
            autocomplete="off"
        >
        
        <i data-lucide="search" class="absolute left-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400 pointer-events-none"></i>
        
        <div id="input-loading" class="absolute right-4 top-1/2 transform -translate-y-1/2 hidden">
            <i data-lucide="loader-2" class="w-6 h-6 animate-spin text-indigo-500"></i>
        </div>

        <button id="clear-search" class="absolute right-4 top-1/2 transform -translate-y-1/2 hidden
                                         text-gray-400 hover:text-[var(--color-secondary)] transition-colors duration-200
                                         focus:outline-none" 
                title="Limpiar búsqueda">
            <i data-lucide="x-circle" class="w-6 h-6"></i>
        </button>
    </div>
    
    <button 
        id="trigger-search-button" 
        class="flex items-center justify-center h-14 px-6 bg-[var(--color-secondary)] uppercase text-white
               font-bold hover:bg-opacity-90 transition-all duration-300 whitespace-nowrap
               focus:outline-none"
        title="Buscar Cliente">
        <i data-lucide="user-search" class="w-5 h-5 mr-2"></i> Buscar Cliente
    </button>
</div>
</div>

                <div id="results-dropdown" class="bg-white hidden mt-1"></div>
            </div>

            <div id="profile-view" class="hidden animate-fade-in">
                
                <div class="bg-white rounded-2xl shadow-xl overflow-hidden mb-6 border-t-4 border-[var(--color-secondary)]">
                    <div class="p-8 flex flex-col md:flex-row items-center gap-6">
                        <div class="w-24 h-24 bg-[var(--color-secondary)] rounded-full flex items-center justify-center text-3xl font-black text-white border-4 border-white shadow">
                            <span id="p-initials">--</span>
                        </div>
                        <div class="text-center md:text-left flex-1">
                            <h2 id="p-name" class="text-4xl font-black text-gray-800 uppercase leading-none mb-1">...</h2>
                            <p id="p-company" class="text-xl text-[var(--color-secondary)] font-bold mb-2">...</p>
                            <span id="p-type" class="px-3 py-1 rounded-full text-xs font-bold uppercase bg-gray-200 text-gray-600">...</span>
                        </div>
                        <div id="p-loyalty-metric" class="text-right p-4 bg-gray-50 rounded-lg shadow-inner border border-gray-200">
                            <p class="text-xs uppercase font-black text-gray-500 mb-1">Fidelidad del Cliente</p>
                            <p class="text-xl font-black uppercase text-[var(--color-secondary)] leading-none" id="p-loyalty-value">--</p>
                        </div>
                        <div class="flex gap-2 hidden">
                             <a id="btn-wa" href="#" target="_blank" class="p-3 bg-[var(--color-success)] text-white rounded-lg hover:bg-[var(--color-success)]"><i data-lucide="message-circle"></i></a>
                             <a id="btn-tel" href="#" class="p-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700"><i data-lucide="phone"></i></a>
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    
                    <div class="space-y-6">
                        
                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase">Información Contacto</h3>
                            <p><span id="p-code-creation" class="text-md uppercase font-bold text-[var(--color-secondary)]"></span></p>
                            <ul class="space-y-4 text-md font-medium text-gray-600">
                                <li class="flex gap-3"><i data-lucide="mail" class="text-[var(--color-secondary)] w-5"></i> <span id="p-email">--</span></li>
                                <li class="flex gap-3"><i data-lucide="phone" class="text-[var(--color-secondary)] w-5"></i> <span id="p-phone-main">--</span></li>
                                <li class="flex gap-3"><i data-lucide="smartphone" class="text-[var(--color-secondary)] w-5"></i> <span id="p-mobile">--</span></li>
                                <li class="flex gap-3"><i data-lucide="map-pin" class="text-[var(--color-secondary)] w-5"></i> <span id="p-address">--</span></li>
                                <li class="flex gap-3"><i data-lucide="award" class="text-[var(--color-secondary)] w-5"></i> Código Del Cliente: <span id="p-access-code" class="font-bold text-[var(--color-secondary)]">--</span></li>
                            </ul>
                        </div>
                        
                        <div id="staff-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 border-b pb-2">Staff Asignado</h3>
                            <div class="flex items-center gap-3">
                                <img id="p-staff-photo" src="/brand/img/Placeholder.webp" alt="Staff" class="w-10 h-10 rounded-full object-cover bg-gray-200">
                                <div>
                                    <span id="p-staff" class="font-bold text-gray-700">--</span>
                                    <p id="p-staff-title" class="text-xs uppercase text-gray-500">Especialista de Servicios</p>
                                </div>
                            </div>
                        </div>

                        <div id="route-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 border-b pb-2 flex items-center gap-2"><i data-lucide="route" class="w-5 h-5 text-[var(--color-secondary)]"></i> Ruta Asignada</h3>
                            <div id="list-route">
                                <div class="text-gray-400 italic text-md">Sin ruta asignada</div>
                            </div>
                        </div>

                        <div id="services-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 border-b pb-2 flex items-center gap-2"><i data-lucide="briefcase" class="w-5 h-5 text-[var(--color-secondary)]"></i> Servicios Adquiridos</h3>
                            <div id="list-services" class="space-y-2">
                                <div class="text-gray-400 italic text-md">Sin servicios registrados</div>
                            </div>
                        </div>
                        
                    </div>

                    <div class="lg:col-span-2 space-y-6">
                        
                        <div id="financial-summary-section" class="bg-white p-6 rounded-2xl shadow-xl overflow-hidden mb-6 border-t-4 border-[var(--color-highlight)]">
                            <h3 id="financial-summary-title" class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                                <i data-lucide="wallet" class="w-6 h-6 text-[var(--color-secondary)]"></i> RESUMEN FINANCIERO
                            </h3>
                            <div class="grid grid-cols-3 gap-4 text-center">
                                <div>
                                    <p class="text-3xl font-black text-[var(--color-success)]">$<span id="p-total-spent">0.00</span></p>
                                    <p class="text-md text-gray-500 font-bold">TOTAL PAGADO (GANADO)</p>
                                </div>
                                <div>
                                    <p class="text-3xl font-black text-[var(--color-secondary)]">$<span id="p-total-due">0.00</span></p>
                                    <p class="text-md text-gray-500 font-bold">TOTAL POR COBRAR</p>
                                </div>
                                <div>
                                    <p class="text-3xl font-black text-[var(--color-highlight)]">$<span id="p-total-estimated">0.00</span></p>
                                    <p class="text-md text-gray-500 font-bold">TOTAL COTIZADO</p>
                                </div>
                            </div>
                            
                            <div class="mt-8 pt-4 border-t border-gray-100">
                                <div id="monthly-financial-behavior" class="relative">
                                    <div class="text-gray-400 italic text-sm">Cargando datos...</div>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                                <i data-lucide="file-text" class="w-6 h-6 text-[var(--color-secondary)]"></i> HISTORIAL DE FACTURAS
                            </h3>
                            <div id="list-invoices" class="space-y-2 mt-4"></div>
                        </div>

                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                                <i data-lucide="clipboard-list" class="w-6 h-6 text-[var(--color-secondary)]"></i> COTIZACIONES ENVIADAS
                            </h3>
                            <div id="list-estimates" class="space-y-2 mt-4"></div>
                        </div>
                        
                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2"><i data-lucide="calendar" class="w-6 h-6 text-[var(--color-secondary)]"></i> HISTORIAL DE CITAS</h3>
                            <div id="list-appointments" class="space-y-2"></div>
                        </div>

                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2"><i data-lucide="alert-triangle" class="w-6 h-6 text-[var(--color-secondary)]"></i> QUEJAS / RECLAMOS</h3>
                            <div id="list-complaints" class="space-y-2"></div>
                        </div>
                        
                    </div>
                    
                </div>
                
                <div class="space-y-6 mt-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        
                        <div id="notes-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2"><i data-lucide="sticky-note" class="w-6 h-6 text-[var(--color-secondary)]"></i> NOTAS INTERNAS</h3>
                            <div id="list-notes" class="space-y-3"></div>
                        </div>
                        
                        <div id="projects-section" class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2"><i data-lucide="folder-open" class="w-6 h-6 text-[var(--color-secondary)]"></i> PROYECTOS</h3>
                            <div id="list-projects" class="space-y-2"></div>
                        </div>
                        
                        <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                            <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex gap-2"><i data-lucide="check-square" class="w-6 h-6 text-[var(--color-secondary)]"></i> TAREAS PENDIENTES</h3>
                            <div id="list-tasks" class="space-y-2"></div>
                        </div>
                    
                    </div>
                    
                    <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-highlight)]">
                        <h3 class="font-black text-2xl text-[var(--color-primary)] uppercase mb-4 flex items-center gap-2">
                            <i data-lucide="star" class="w-6 h-6 text-[var(--color-secondary)]"></i> Reseñas De Satisfacción
                        </h3>
                        <div id="list-reviews" class="space-y-4"></div>
                    </div>
                </div>
            </div>  
            
    <?php @include 'brand/powered.php'; ?>
        
        </main>
    </div>

<script>
    lucide.createIcons();
    
    const searchInput = document.getElementById('search-input');
    const dropdown = document.getElementById('results-dropdown');
    const inputLoading = document.getElementById('input-loading');
    const fbiScreen = document.getElementById('fbi-screen');
    const profileView = document.getElementById('profile-view');
    let debounceTimer;
    
    // Función de formato de número con separador de miles
    const formatNumberWithCommas = (number) => {
        if (typeof number !== 'number') return number;
        return number.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    };

    // Función de formato de fecha (Día Mes Año)
    const formatDateUserFriendly = (dateString) => {
        if (!dateString) return '--';
        try {
            const datePart = dateString.split(' ')[0];
            const date = new Date(datePart.replace(/-/g, '/'));
            const options = { day: '2-digit', month: 'long', year: 'numeric' };
            
            let formattedDate = date.toLocaleDateString('es-ES', options);
            formattedDate = formattedDate.replace(' de ', ' '); 
            formattedDate = formattedDate.replace(/(\s)de(\s\d{4})/, '$2');
            
            return formattedDate;
        } catch {
            return dateString.split(' ')[0] || '--'; 
        }
    };
    
    const calculateClientAge = (creationDateString) => {
        if (!creationDateString) return 'N/A';
        try {
            // Reemplazar '-' por '/' para asegurar compatibilidad de fecha
            const created = new Date(creationDateString.split(' ')[0].replace(/-/g, '/'));
            const now = new Date();
            const diffTime = Math.abs(now - created);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            
            if (diffDays < 30) return `${diffDays} Días`;
            
            const diffMonths = Math.floor(diffDays / 30.44); // Promedio de días al mes
            if (diffMonths < 12) return `${diffMonths} Meses`;

            const diffYears = now.getFullYear() - created.getFullYear();
            
            if (now.getMonth() < created.getMonth() || (now.getMonth() === created.getMonth() && now.getDate() < created.getDate())) {
                 if (diffYears > 0) return `${diffYears - 1} Años +`;
                 return `${Math.floor(diffDays / 30.44)} Meses`;
            }

            return `${diffYears} Años`;
        } catch {
            return 'Inválida';
        }
    };

    // Función para renderizar el gráfico de comportamiento financiero (Nuevo)
    function renderFinancialBehavior(invoices) {
        const container = document.getElementById('monthly-financial-behavior');
        container.innerHTML = '';
        
        // 1. Agrupar las ganancias (total_amount) por mes (año-mes)
        const monthlyData = {};
        const currentYear = new Date().getFullYear();
        
        invoices.filter(i => (i.status || '').toLowerCase() === 'pagada').forEach(i => {
            const date = new Date(i.invoice_date.split(' ')[0].replace(/-/g, '/'));
            const monthKey = `${date.getFullYear()}-${date.getMonth() + 1}`;
            const amount = parseFloat(i.total_amount || 0);

            if (date.getFullYear() === currentYear) { // Solo facturas del año actual
                 if (!monthlyData[monthKey]) {
                     monthlyData[monthKey] = 0;
                 }
                 monthlyData[monthKey] += amount;
            }
        });
        
        if (Object.keys(monthlyData).length === 0) {
            container.innerHTML = '<div class="text-gray-400 italic text-md">No hay facturas pagadas en el año actual para mostrar el comportamiento mensual.</div>';
            return;
        }

        // 2. Determinar el valor máximo para escalar el gráfico
        const allAmounts = Object.values(monthlyData);
        const maxAmount = Math.max(...allAmounts, 0);
        
        // 3. Crear el contenedor del gráfico de barras
        const chartContainer = document.createElement('div');
        chartContainer.className = 'chart-bar-container';

        const monthNames = ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"];

        // 4. Recorrer los 12 meses para construir las barras
        for (let i = 0; i < 12; i++) {
            const monthKey = `${currentYear}-${i + 1}`;
            const amount = monthlyData[monthKey] || 0;
            
            let heightPercent = 0;
            if (maxAmount > 0) {
                heightPercent = (amount / maxAmount) * 100;
                if (amount > 0 && heightPercent < 5) heightPercent = 5;
            }
            
            const bar = document.createElement('div');
            bar.className = 'chart-bar';
            bar.style.height = `${heightPercent}%`;
            
            const tooltip = document.createElement('div');
            tooltip.className = 'chart-bar-tooltip';
            tooltip.innerText = `$${formatNumberWithCommas(amount)}`;
            
            const label = document.createElement('div');
            label.className = 'chart-bar-label';
            label.innerText = monthNames[i];
            
            bar.appendChild(tooltip);
            bar.appendChild(label);
            chartContainer.appendChild(bar);
        }
        
        container.appendChild(chartContainer);
        lucide.createIcons();
    }
    
    // 1. EVENTO: ESCRIBIR EN EL BUSCADOR
    searchInput.addEventListener('input', (e) => {
        const val = e.target.value.trim();
        clearTimeout(debounceTimer);
        dropdown.innerHTML = '';
        dropdown.classList.add('hidden');

        if(val.length < 2) return;

        inputLoading.classList.remove('hidden');

        debounceTimer = setTimeout(() => {
            fetch(`db/search-clients-profile.php?q=${encodeURIComponent(val)}`)
                .then(res => res.json())
                .then(data => {
                    inputLoading.classList.add('hidden');
                    renderDropdown(data);
                });
        }, 300);
    });
    
    function renderDropdown(list) {
        if(list.length === 0) return;
        dropdown.classList.remove('hidden');
        
        list.forEach(item => {
            const div = document.createElement('div');
            div.className = "result-item p-3 border-b border-gray-100 flex justify-between items-center";
            const fullName = `${item.first_name || ''} ${item.last_name || ''}`.trim();
            const typeLabel = item.type === 'client' ? 'CLIENTE' : 'LEAD';
            
            const typeColor = item.type === 'client' ? 'text-white bg-[var(--color-success)]' : 'text-[var(--color-highlight)] bg-[var(--color-highlight)]';

            div.innerHTML = `
                <div>
                    <div class="font-bold text-gray-800 uppercase">${fullName || item.company}</div>
                    <div class="text-md text-gray-500">${item.company || 'Cliente Residencial'} </div>
                </div>
                <span class="text-lg font-black px-2 py-1 rounded ${typeColor}">${typeLabel}</span>
            `;
            
            div.addEventListener('click', () => {
                dropdown.classList.add('hidden');
                searchInput.value = fullName || item.company;
                startFBILoading(item.id, item.type);
            });
            dropdown.appendChild(div);
        });
    }

    function startFBILoading(id, type) {
        fbiScreen.classList.remove('hidden');
        profileView.classList.add('hidden');
        
        const fbiText = document.getElementById('fbi-text');
        const fbiSub = document.getElementById('fbi-subtext');
        
        const steps = [
            { t: "ESTABLECIENDO ENLACE...", s: "Verificando Credenciales De Seguridad" },
            { t: "BUSCANDO EN LA BASE DE DATOS...", s: "Escaneando Todo El Sistema" },
            { t: "RECOPILANDO REGISTROS...", s: "Unificando Historial Y Actividad" },
            { t: "ACCESO CONCEDIDO", s: "Desencriptando Perfil Del Cliente" }
        ];

        let step = 0;
        
        const interval = setInterval(() => {
            if(step < steps.length) {
                fbiText.innerText = steps[step].t;
                fbiSub.innerText = steps[step].s;
                step++;
            }
        }, 600);

        fetch(`db/get-clients-profile.php?id=${id}&type=${type}`)
            .then(res => res.json())
            .then(data => {
                setTimeout(() => {
                    clearInterval(interval);
                    if(data.error) {
                        alert(`Error: ${data.error}`);
                        fbiScreen.classList.add('hidden');
                        return;
                    }
                    renderProfileData(data, type);
                    fbiScreen.classList.add('hidden');
                    profileView.classList.remove('hidden');
                }, 2500); 
            })
            .catch(error => {
                clearInterval(interval);
                alert(`Error de red o servidor: ${error.message}`);
                fbiScreen.classList.add('hidden');
            });
    }

    function renderProfileData(data, type) {
        const p = data.profile;
        if (!p) return alert("Error cargando perfil");

        // --- FUNCIONES DE AYUDA DE FORMATO ---
        const formatDate = formatDateUserFriendly;
        
        const statusColor = (status) => {
            if (!status) return 'bg-gray-100 text-gray-800';
            const s = status.toLowerCase().trim();
            switch(s) {
                case 'pagada': 
                case 'completed': 
                case 'ganada': 
                case 'activo':
                case 'confirmed': 
                case 'aprobado': 
                    return 'bg-[var(--color-success)]/[0.2] text-[var(--color-success)]';
                case 'enviado': 
                case 'pending': 
                case 'negociación':
                case 'tibio':
                case 'contactado':
                case 'nuevo':
                    return 'bg-[var(--color-highlight)]/[0.2] text-[var(--color-highlight)]'; 
                case 'convertida': 
                    return 'bg-[var(--color-secondary)]/[0.2] text-[var(--color-secondary)]'; 
                case 'accion requerida': 
                case 'perdida':
                case 'cancelada':
                case 'lead descartado':
                case 'archivado':
                    return 'bg-[var(--color-secondary)] text-white'; 
                default: 
                    return 'bg-gray-100 text-gray-800';
            }
        };
        const initials = (firstName, lastName) => {
             const first = (firstName || 'X')[0];
             const last = (lastName || 'X')[0];
             return (first + last).toUpperCase();
        };
        
        // --- CÁLCULOS PARA RESUMEN FINANCIERO ---
        let totalEstimated = 0;
        let totalDue = 0; 
        
        if (data.estimates && data.estimates.length > 0) {
            data.estimates.forEach(e => {
                const status = (e.status_seguimiento || e.status || '').toLowerCase();
                if (status !== 'perdida' && status !== 'convertida') {
                    totalEstimated += parseFloat(e.total_amount || 0);
                }
            });
        }
        
        if (data.invoices && data.invoices.length > 0) {
            data.invoices.forEach(i => {
                const status = (i.status || '').toLowerCase();
                if (status !== 'pagada' && status !== 'cancelada') { 
                    totalDue += parseFloat(i.total_amount || 0);
                }
            });
        }

        // --- Rellenar cabecera ---
        const fullName = `${p.first_name || ''} ${p.last_name || ''}`.trim();
        document.getElementById('p-name').innerText = fullName || p.company || 'CONTACTO DESCONOCIDO';
        document.getElementById('p-company').innerText = p.company || 'Cliente Residencial';
        document.getElementById('p-initials').innerText = initials(p.first_name || p.company, p.last_name);
        document.getElementById('p-type').innerText = type === 'client' ? 'CLIENTE ACTIVO' : 'PROSPECTO';
        
        const clientAge = calculateClientAge(p.created_at);
        document.getElementById('p-loyalty-value').innerText = clientAge;
        
        // Botones (Manteniendo colores standard para WA y Teléfono)
        const num = (p.mobile || p.phone || '').replace(/[^0-9]/g, '');
        document.getElementById('btn-wa').href = num ? `https://wa.me/${num}` : '#';
        document.getElementById('btn-tel').href = num ? `tel:${num}` : '#';
        
        // Datos de contacto
        document.getElementById('p-email').innerText = p.email || '--';
        document.getElementById('p-phone-main').innerText = p.phone || '--';
        document.getElementById('p-mobile').innerText = p.mobile || '--';
        const address = [p.street_address, p.city, p.state_province, p.zip_code].filter(Boolean).join(', ');
        document.getElementById('p-address').innerText = address || '--';
        document.getElementById('p-access-code').innerText = (type === 'client' ? p.access_code : p.id) || '--';
        document.getElementById('p-code-creation').innerText = p.created_at ? `Creado: ${formatDate(p.created_at)}` : '';

        // Staff Asignado
        document.getElementById('p-staff').innerText = p.staff_name || 'N/A';
        const staffPhoto = document.getElementById('p-staff-photo');
        staffPhoto.src = p.staff_photo ? p.staff_photo : 'brand/img/Placeholder.webp'; 


        // --- SECCIONES FINANCIERAS ---

        // Resumen Financiero
        document.getElementById('p-total-spent').innerText = formatNumberWithCommas(Number(data.financial_summary.total_spent));
        document.getElementById('p-total-due').innerText = formatNumberWithCommas(totalDue); 
        document.getElementById('p-total-estimated').innerText = formatNumberWithCommas(totalEstimated);
        
        // Renderizar Comportamiento Financiero Mensual
        if (data.invoices) {
            renderFinancialBehavior(data.invoices);
        }

        // 1. Facturas
        const invContainer = document.getElementById('list-invoices');
        invContainer.innerHTML = '';
        if (data.invoices && data.invoices.length > 0) {
            data.invoices.forEach(i => {
                const totalAmountFormatted = formatNumberWithCommas(Number(i.total_amount)); 
                const dateDisplay = formatDate(i.invoice_date);
                invContainer.innerHTML += `
                    <div class="flex justify-between border-b border-gray-100 py-2 items-center">
                        <span class="font-bold text-gray-700 text-md">#${i.external_id} (${dateDisplay})</span>
                        <div class="text-right">
                            <span class="block font-black text-gray-900">$${totalAmountFormatted}</span>
                            <span class="text-xs uppercase font-bold px-2 py-0.5 rounded ${statusColor(i.status)}">${i.status}</span>
                        </div>
                    </div>`;
            });
        } else {
            invContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin facturas registradas.</div>';
        }

        // 2. Cotizaciones
        const estContainer = document.getElementById('list-estimates');
        estContainer.innerHTML = '';
        if (data.estimates && data.estimates.length > 0) {
            data.estimates.forEach(e => {
                const statusText = e.status_seguimiento || e.status;
                const totalAmountFormatted = formatNumberWithCommas(Number(e.total_amount)); 
                const dateDisplay = formatDate(e.estimate_date);
                estContainer.innerHTML += `
                    <div class="flex justify-between border-b border-gray-100 py-2 items-center">
                        <span class="font-bold text-gray-700 text-md">#${e.external_id} (${dateDisplay})</span>
                        <div class="text-right">
                            <span class="block font-black text-gray-900">$${totalAmountFormatted}</span>
                            <span class="text-xs uppercase font-bold px-2 py-0.5 rounded ${statusColor(statusText)}">${statusText}</span>
                        </div>
                    </div>`;
            });
        } else {
            estContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin cotizaciones registradas.</div>';
        }
        
        // --- OTRAS SECCIONES ---

        // 3. Quejas
        const compContainer = document.getElementById('list-complaints');
        compContainer.innerHTML = '';
        if (data.complaints && data.complaints.length > 0) {
            data.complaints.forEach(c => {
                const dateDisplay = formatDate(c.created_at);
                compContainer.innerHTML += `
                    <div class="p-2 bg-gray-100 text-[var(--color-secondary)]  text-md rounded font-bold">
                        ${c.title} 
                        <span class="font-normal text-xs text-[var(--color-primary)] float-right">${dateDisplay} <b> ${c.status}</b></span>
                    </div>`;
            });
        } else {
            compContainer.innerHTML = '<div class="text-[var(--color-success)] text-md font-bold">Sin quejas activas</div>';
        }

        // 4. Tareas Pendientes
        const taskContainer = document.getElementById('list-tasks');
        taskContainer.innerHTML = '';
        if (data.tasks && data.tasks.length > 0) {
            data.tasks.forEach(t => {
                const priorityColor = t.priority === 'Alta' ? 'bg-[var(--color-secondary)] text-white' : (t.priority === 'Media' ? 'bg-[var(--color-highlight)]/[0.2] text-[var(--color-highlight)]' : 'bg-[var(--color-success)]/[0.2] text-[var(--color-success)]');
                const dateDisplay = formatDate(t.due_date);
                taskContainer.innerHTML += `
                    <div class="p-2 ${priorityColor} text-md rounded font-bold">
                        ${t.title} 
                        <span class="font-normal text-xs float-right">Vence: ${dateDisplay}</span>
                    </div>`;
            });
        } else {
            taskContainer.innerHTML = '<div class="text-gray-400 italic text-md">Agenda libre de tareas.</div>';
        }

        // 5. Historial de Citas/Agenda
        const appContainer = document.getElementById('list-appointments');
        appContainer.innerHTML = '';
        const reviewsContainer = document.getElementById('list-reviews');
        reviewsContainer.innerHTML = '';
        let hasReview = false;

        if (data.appointments && data.appointments.length > 0) {
            data.appointments.forEach(a => {
                const appStatusColor = a.status === 'completed' ? 'text-[var(--color-success)]' : (a.status === 'pending' ? 'text-[var(--color-highlight)]' : 'text-gray-600');
                
                const appointmentDatePart = a.appointment_date || '';
                const appointmentTimePart = a.appointment_time ? ` (${a.appointment_time.substring(0, 5)})` : '';
                const dateDisplay = formatDate(appointmentDatePart);
                
                // Mostrar Cita
                appContainer.innerHTML += `
                    <div class="flex justify-between items-center border-b border-gray-100 py-2">
                        <div class="text-md font-bold ${appStatusColor}">
                            ${dateDisplay}${appointmentTimePart}
                        </div>
                        <span class="text-xs font-bold uppercase ${statusColor(a.status)} px-2 py-0.5 rounded">${a.status}</span>
                    </div>`;
                
                // Si hay feedback/reseña, mostrarla (usando Lucide Icons en lugar de Emojis)
                if (a.client_feedback && a.client_feedback.trim().length > 0) {
                    hasReview = true;
                    
                    let starsHTML = '<div class="flex gap-1 mb-1">';
                    const rating = parseInt(a.client_rating) || 5;
                    for (let i = 1; i <= 5; i++) {
                        if (i <= rating) {
                            // Estrella llena (rellena con el color secundario)
                            starsHTML += `<i data-lucide="star" class="w-5 h-5 text-[var(--color-secondary)] fill-[var(--color-secondary)]"></i>`;
                        } else {
                            // Estrella vacía (gris)
                            starsHTML += `<i data-lucide="star" class="w-5 h-5 text-gray-300"></i>`;
                        }
                    }
                    starsHTML += '</div>';

                    const reviewDateDisplay = formatDate(a.appointment_date);
                    reviewsContainer.innerHTML += `
                        <div class="p-4 bg-[var(--color-secondary)]/[0.1] rounded-lg border-l-4 border-[var(--color-secondary)]">
                            ${starsHTML}
                            <p class="font-black text-lg text-[var(--color-secondary)]">${a.client_rating || '5'}/5</p>
                            <p class="italic text-gray-700 text-md">"${a.client_feedback}"</p>
                            <span class="block text-xs text-gray-500 mt-1">Cita del ${reviewDateDisplay}</span>
                        </div>`;
                }
            });
            if (!hasReview) {
                reviewsContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin reseña/feedback registrado de citas completadas.</div>';
            }
        } else {
            appContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin citas/agenda registrada.</div>';
            reviewsContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin reseña/feedback registrado de citas completadas.</div>';
        }

        // 6. Servicios Adquiridos
        const servicesContainer = document.getElementById('list-services');
        servicesContainer.innerHTML = '';
        if (data.services && data.services.length > 0) {
            data.services.forEach(s => {
                servicesContainer.innerHTML += `<div class="p-2 bg-[var(--color-secondary)]/[0.2] text-[var(--color-primary)] text-md rounded font-bold">${s}</div>`;
            });
        } else {
            servicesContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin servicios principales vinculados.</div>';
        }

        // 7. Ruta Asignada
        const routeContainer = document.getElementById('list-route');
        routeContainer.innerHTML = '';
        if (data.route_info) {
            routeContainer.innerHTML = `
                <div class="p-2 bg-[var(--color-highlight)]/[0.2] text-[var(--color-primary)] text-md rounded font-bold">
                    ${data.route_info.route_name} (${data.route_info.route_day})
                </div>`;
        } else {
            routeContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin ruta asignada.</div>';
        }
        
        // 8. Proyectos
        const projContainer = document.getElementById('list-projects');
        projContainer.innerHTML = '';
        if (data.projects && data.projects.length > 0) {
            data.projects.forEach(proj => {
                const dateDisplay = formatDate(proj.due_date);
                projContainer.innerHTML += `
                    <div class="flex justify-between items-center border-b border-gray-100 py-2">
                        <div>
                            <span class="font-bold text-gray-700 text-md">${proj.name}</span>
                            <p class="text-xs text-gray-500">${proj.service_name}</p>
                        </div>
                        <div class="text-right">
                            <span class="text-xs uppercase font-bold px-2 py-0.5 rounded ${statusColor(proj.status)}">${proj.status}</span>
                            <p class="text-xs text-gray-500">Vence: ${dateDisplay}</p>
                        </div>
                    </div>`;
            });
        } else {
            projContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin proyectos activos.</div>';
        }

        // 9. Notas Internas
        const notesContainer = document.getElementById('list-notes');
        notesContainer.innerHTML = '';
        if (data.notes && data.notes.length > 0) {
            data.notes.forEach(note => {
                const dateDisplay = formatDate(note.created_at);
                notesContainer.innerHTML += `
                    <div class="p-3 bg-gray-100 rounded-lg">
                        <p class="text-md text-gray-800">${note.content}</p>
                        <span class="block text-xs text-gray-500 mt-1">${dateDisplay}</span>
                    </div>`;
            });
        } else {
            notesContainer.innerHTML = '<div class="text-gray-400 italic text-md">Sin notas internas.</div>';
        }

        lucide.createIcons();
    }
</script>
</body>
</html>