<?php
// Reporte-Financiero.php
// CARGA MAESTRA de CONFIGURACIÓN
require_once(__DIR__ . '/core/init.php');
// Usar $logo_url y $client_business_name de business-information.php
$logo_url_for_spinner = htmlspecialchars($logo_url ?? ''); 
$client_business_name_safe = htmlspecialchars($client_business_name ?? '');
$currentYear = date('Y');
$currentMonth = date('m');
$defaultMonthValue = date('Y-m'); // Valor YYYY-MM por defecto
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Reporte Financiero <?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;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        .chart-bar { transition: width 1s ease-in-out; }
        
        .month-status-container {
            display: flex; 
            justify-content: center; 
            align-items: center; 
            margin-bottom: 1.5rem; 
            padding: 0.5rem 1rem; 
            border-radius: 0.75rem; 
            font-weight: 600; 
            text-align: center;
        }

        #month-select-container {
            position: relative;
        }
        #month-selector {
            padding-right: 3rem; /* Espacio para el icono */
        }
        #month-icon {
            position: absolute;
            right: 1.5rem;
            top: 50%;
            transform: translateY(-50%);
            pointer-events: none; /* No bloquear clics */
        }
    </style>
</head>
<body data-page-title="Reporte Financiero Mensual"
    data-page-subtitle="Auditoría de Ingresos y Egresos"
    data-page-icon="pie-chart">
    
    <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">Reporte Avanzado</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" id="month-select-container">
        <select id="month-selector" 
            class="w-full h-14 p-4 pl-14 pr-4 bg-white
                        focus:outline-none 
                        text-base font-black text-gray-700 uppercase
                        border-none ring-0
                        appearance-none /* FIX: Añadido para ocultar la flecha nativa del select y evitar icono duplicado */
                        " >
                     </select>
        
        <i data-lucide="calendar" class="absolute left-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400 pointer-events-none"></i>
        <i data-lucide="chevron-down" id="month-icon" class="w-5 h-5 text-gray-400"></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-report-btn" 
        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="Generar Reporte">
        <i data-lucide="calculator" class="w-5 h-5 mr-2"></i> Generar Analisis
    </button>
</div>
</div>


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

                <div id="report-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">
                            <h2 class="text-3xl font-black text-black uppercase mb-4 text-center">Balance General del Mes</h2>
                            <div id="month-status-container" class="month-status-container w-full max-w-full hidden">
                        <p id="month-status-message" class="text-md font-bold uppercase"></p>
                    </div>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-8 text-center divide-y md:divide-y-0 md:divide-x divide-gray-100">
                                <div class="p-2">
                                    <p class="text-lg font-black text-gray-700 uppercase">Ingreso Mensual</p>
                                    <p class="text-4xl font-black text-[var(--color-success)] mt-2" id="kpi-income">$0.00</p>
                                </div>
                                <div class="p-2">
                                    <p class="text-lg font-black text-gray-700 uppercase">Egresos Mensuales</p>
                                    <p class="text-4xl font-black text-[var(--color-secondary)] mt-2" id="kpi-expenses">$0.00</p>
                                </div>
                                <div class="p-2">
                                    <p class="text-lg font-black text-gray-700 uppercase">Utilidad Neta</p>
                                    <p class="text-5xl font-black text-[var(--color-secondary)] mt-2" id="kpi-net">$0.00</p>
                                    <div id="kpi-margin-badge" class="mt-2 inline-block px-2 py-1 bg-gray-100 text-xs font-bold rounded text-gray-500">Margen: 0%</div>
                                </div>
                            </div>
                        </div>
                        <div class="w-full h-4 bg-gray-100 flex">
                            <div id="bar-income" class="h-full bg-[var(--color-success)]" style="width: 50%"></div>
                            <div id="bar-expense" class="h-full bg-[var(--color-secondary)]" style="width: 50%"></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 flex gap-2 mb-4 items-center">
                                    <i data-lucide="alert-circle" class="w-6 h-6 text-[var(--color-secondary)]"></i> Finanzas Por Cobrar
                                </h3>
                                <div class="flex justify-between items-end mb-2">
                                    <span class="text-gray-500 font-medium">Facturado pendiente</span>
                                    <span class="text-2xl font-black text-orange-500" id="detail-due">$0.00</span>
                                </div>
                                <p class="text-xs text-gray-400">Facturas emitidas que aún no han sido pagadas este mes.</p>
                            </div>

                            <div class="bg-white p-6 rounded-xl shadow-md border-t-4 border-[var(--color-secondary)]">
                                <h3 class="font-black text-2xl text-black uppercase flex gap-2 mb-4 items-center">
                                    <i data-lucide="trending-down" class="w-6 h-6 text-[var(--color-secondary)]"></i> Desglose de Salidas
                                </h3>
                                <div class="space-y-3">
                                    <div class="flex justify-between items-center p-2 bg-gray-50 rounded">
                                        <span class="font-bold text-gray-700">Gastos Operativos</span>
                                        <span class="font-black text-[var(--color-secondary)]" id="detail-ops">$0.00</span>
                                    </div>
                                    <div class="flex justify-between items-center p-2 bg-purple-50 rounded">
                                        <span class="font-bold text-gray-700">Nómina (Horas)</span>
                                        <span class="font-black text-purple-600" id="detail-payroll">$0.00</span>
                                    </div>
                                    <div class="border-t border-t-2 border-gray-100 pt-2 flex justify-between">
                                        <span class="text-sm font-bold text-gray-400">TOTAL</span>
                                        <span class="font-bold text-gray-800" id="detail-total-out">$0.00</span>
                                    </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-black uppercase flex gap-2 mb-4 items-center">
                                    <i data-lucide="receipt" class="w-6 h-6 text-[var(--color-secondary)]"></i> Últimos Gastos
                                </h3>
                                <div id="list-expenses" class="space-y-2"></div>
                            </div>
                        </div>

                        <div class="lg:col-span-2 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 mb-4 flex items-center gap-2">
                                    <i data-lucide="funnel" class="w-6 h-6 text-[var(--color-secondary)]"></i> DESGLOCE DE META FINANCIERA
                                </h3>
                                <div class="grid grid-cols-3 gap-4 text-center">
                                    <div>
                                        <p class="text-3xl font-black text-blue-600">$<span id="pipe-quoted">0.00</span></p>
                                        <p class="text-md text-gray-500 font-black">TOTAL COTIZADO</p>
                                    </div>
                                    <div>
                                        <p class="text-3xl font-black text-[var(--color-success)]">$<span id="pipe-won">0.00</span></p>
                                        <p class="text-md text-gray-500 font-black">TOTAL GANADO</p>
                                    </div>
                                    <div>
                                        <p class="text-3xl font-black text-gray-700"><span id="pipe-rate">0</span>%</p>
                                        <p class="text-md text-gray-500 font-black">TASA DE CIERRE</p>
                                    </div>
                                </div>
                                <div class="mt-4 w-full bg-gray-100 rounded-full h-2.5">
                                    <div id="pipe-bar" class="bg-blue-600 h-2.5 rounded-full chart-bar" style="width: 0%"></div>
                                </div>
                                <div class="mt-2 text-xs text-gray-400 text-center">
                                    <span id="count-sent">0</span> Enviadas | <span id="count-won">0</span> Ganadas | <span id="count-lost">0</span> Perdidas
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-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-gray-700 uppercase mb-4 flex gap-2 items-center">
                                        <i data-lucide="arrow-up-circle" class="w-6 h-6 text-[var(--color-secondary)]"></i> Ingresos Recientes
                                    </h3>
                                    <div id="list-invoices" 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-gray-700 uppercase mb-4 flex gap-2 items-center">
                                        <i data-lucide="file-text" class="w-6 h-6 text-[var(--color-secondary)]"></i> Cotizaciones Recientes
                                    </h3>
                                    <div id="list-estimates" 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 gap-2 items-center">
                                    <i data-lucide="activity" class="w-6 h-6 text-[var(--color-secondary)]"></i> ACTIVIDAD OPERATIVA
                                </h3>
                                <div class="flex gap-8">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-[var(--color-secondary)] rounded-full flex items-center justify-center text-white"><i data-lucide="calendar-check"></i></div>
                                        <div>
                                            <p class="text-2xl font-black text-gray-800" id="ops-apps">0</p>
                                            <p class="text-md uppercase font-black text-gray-700">Citas Realizadas</p>
                                        </div>
                                    </div>
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-[var(--color-secondary)] rounded-full flex items-center justify-center text-white"><i data-lucide="clock"></i></div>
                                        <div>
                                            <p class="text-2xl font-black text-gray-800" id="ops-hours">0</p>
                                            <p class="text-md uppercase font-black text-gray-700">Horas Trabajadas</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                        
                    </div>
                </div>  
    <?php @include 'brand/powered.php'; ?>
                </div>
        </div>
    </main>

<script>
    lucide.createIcons();
    
    const API_ENDPOINTS = {
        GET_REPORT: 'db/get-financial-report.php',
    };

    const fbiScreen = document.getElementById('fbi-screen');
    const reportView = document.getElementById('report-view');
    const monthSelector = document.getElementById('month-selector');
    const btnGenerate = document.getElementById('trigger-report-btn');
    const statusContainer = document.getElementById('month-status-container');
    const statusMessage = document.getElementById('month-status-message');
    
    const monthNames = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
        "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
    ];
    
    const currentYear = <?php echo $currentYear; ?>;
    const currentMonth = <?php echo (int)$currentMonth; ?>;
    const defaultMonthValue = '<?php echo $defaultMonthValue; ?>';

    
    const formatMoney = (amount) => {
        // *** CORRECCIÓN AUSENCIA DÓLAR: Se añade el signo '$' de vuelta a la función JS ***
        return '$' + parseFloat(amount || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    };

    /**
     * Genera las opciones del dropdown de meses para el año actual y el pasado.
     */
    const populateMonthSelector = () => {
        monthSelector.innerHTML = ''; // Limpiar selector existente
        
        // Generar para 1 año y el mes actual del año pasado
        for (let year = currentYear; year >= currentYear - 1; year--) {
            const startMonth = (year === currentYear) ? currentMonth : 12;
            const endMonth = (year === currentYear - 1) ? currentMonth : 1;
            
            // Recorrer meses hacia atrás
            for (let m = startMonth; m >= endMonth; m--) {
                const monthPadded = String(m).padStart(2, '0');
                const value = `${year}-${monthPadded}`;
                const name = `${monthNames[m - 1]} ${year}`;

                const option = document.createElement('option');
                option.value = value;
                option.text = name;
                
                // Seleccionar el mes actual por defecto
                if (value === defaultMonthValue) {
                    option.selected = true;
                }

                monthSelector.appendChild(option);
            }
        }
    };

    /**
     * Compara el mes seleccionado con el mes actual y actualiza el mensaje de estado.
     */
    const updateStatusMessage = (reportIsLoaded = false) => {
        const selectedMonth = monthSelector.value;
        statusContainer.classList.remove('bg-yellow-100', 'border-orange-500', 'text-orange-700', 'bg-green-100', 'border-green-500', 'text-green-700');
        statusContainer.classList.add('hidden'); 
        
        if (!selectedMonth || !reportIsLoaded) {
            return;
        }

        statusContainer.classList.remove('hidden');
        
        const selectedYear = parseInt(selectedMonth.substring(0, 4), 10);
        const selectedMonthIndex = parseInt(selectedMonth.substring(5, 7), 10) - 1; // 0-indexed
        
        // 1. Si NO es el mes actual, se asume que está completo.
        if (selectedYear !== currentYear || selectedMonthIndex + 1 < currentMonth) {
            statusMessage.innerText = 'Este es un reporte de mes completo. Los datos son finales.';
            statusContainer.classList.add('bg-green-100', 'border-green-500', 'text-green-700');
            return;
        }

        // 2. Es el mes actual - Calcular progreso
        const today = new Date();
        const year = selectedYear;
        const monthIndex = selectedMonthIndex; 
        
        const lastDayOfMonth = new Date(year, monthIndex + 1, 0); 
        const todayDay = today.getDate();
        const totalDays = lastDayOfMonth.getDate();

        // Determinar si el mes ya ha terminado (hoy es el último día o más allá)
        if (todayDay >= totalDays && today.getMonth() === monthIndex) {
             statusMessage.innerText = `El mes de ${monthNames[monthIndex]} ha finalizado. Reporte finalizado.`;
             statusContainer.classList.add('bg-green-100', 'border-green-500', 'text-green-700');
             return;
        }

        // Mostrar el mensaje de progreso
        const percentage = ((todayDay / totalDays) * 100).toFixed(1);
        const progressMsg = `El mes todavía está en curso. Se ha completado el ${percentage}% (Día ${todayDay} de ${totalDays}).`;
        statusMessage.innerText = progressMsg;
        statusContainer.classList.add('bg-yellow-100', 'border-orange-500', 'text-orange-700');
    };

    function startReportGeneration() {
        const month = monthSelector.value;
        if(!month) return alert("Seleccione un mes válido");

        // Ocultar vista del reporte anterior y mostrar spinner
        fbiScreen.classList.remove('hidden');
        reportView.classList.add('hidden');
        statusContainer.classList.add('hidden'); 
        
        // Simulación visual del proceso
        const fbiText = document.getElementById('fbi-text');
        const fbiSub = document.getElementById('fbi-subtext');
        const steps = [
            { t: "CONECTANDO A CONTABILIDAD...", s: "Verificando facturas y pagos" },
            { t: "AUDITANDO GASTOS...", s: "Consolidando egresos operativos" },
            { t: "CALCULANDO NÓMINA...", s: "Procesando horas de staff" },
            { t: "GENERANDO REPORTE...", s: "Finalizando balance mensual" }
        ];
        let step = 0;
        const interval = setInterval(() => {
            if(step < steps.length) {
                fbiText.innerText = steps[step].t;
                fbiSub.innerText = steps[step].s;
                step++;
            }
        }, 500);

        // Fetch
        fetch(`${API_ENDPOINTS.GET_REPORT}?month=${month}`)
            .then(res => {
                if (!res.ok) {
                    return res.json().then(errorData => { throw new Error(errorData.error || `HTTP error! status: ${res.status}`); });
                }
                return res.json();
            })
            .then(data => {
                setTimeout(() => {
                    clearInterval(interval);
                    renderReport(data);
                    fbiScreen.classList.add('hidden');
                    reportView.classList.remove('hidden');
                    updateStatusMessage(true); // Mostrar el mensaje DENTRO del reporte
                }, 2000);
            })
            .catch(e => {
                clearInterval(interval);
                alert(`Error de conexión o en el servidor (HTTP 500): ${e.message}. Verifique los logs del servidor para detalles.`);
                fbiScreen.classList.add('hidden');
                reportView.classList.add('hidden'); 
            });
    }

    function renderReport(data) {
        // 1. KPI
        const inc = parseFloat(data.income.total_paid || 0);
        const exp = parseFloat(data.expenses.general || 0);
        const pay = parseFloat(data.payroll.total_cost || 0);
        const totalOut = exp + pay;
        const net = inc - totalOut;
        let margin = 0;
        if(inc > 0) margin = (net / inc) * 100;

        // *** CORRECCIÓN: NO usamos formatMoney aquí, solo el valor puro, ya que el HTML tiene el signo '$' ***
        // ¡Esperar! El HTML SÍ tiene el signo, pero formatMoney LO SOBREESCRIBE. 
        // ¡El formatMoney corregido en este script SÍ tiene el '$'!
        
        document.getElementById('kpi-income').innerText = formatMoney(inc);
        document.getElementById('kpi-expenses').innerText = formatMoney(totalOut);
        
        const elNet = document.getElementById('kpi-net');
        elNet.innerText = formatMoney(net);
        elNet.className = `text-5xl font-black mt-2 ${net >= 0 ? 'text-[var(--color-success)]' : 'text-[var(--color-secondary)]'}`;
        
        document.getElementById('kpi-margin-badge').innerText = `Margen: ${margin.toFixed(1)}%`;
        
        const maxVal = Math.max(inc, totalOut);
        if(maxVal > 0) {
            document.getElementById('bar-income').style.width = `${(inc/maxVal)*100}%`;
            document.getElementById('bar-expense').style.width = `${(totalOut/maxVal)*100}%`;
        } else {
            document.getElementById('bar-income').style.width = '0%';
            document.getElementById('bar-expense').style.width = '0%';
        }

        // 2. Detalle
        document.getElementById('detail-due').innerText = formatMoney(data.income.total_due);
        document.getElementById('detail-ops').innerText = formatMoney(exp);
        document.getElementById('detail-payroll').innerText = formatMoney(pay);
        document.getElementById('detail-total-out').innerText = formatMoney(totalOut);

        // 3. Pipeline
        const pipe = data.pipeline;
        // El HTML tiene el '$' -> $ <span id="pipe-quoted">0.00</span>
        document.getElementById('pipe-quoted').innerText = formatMoney(pipe.total_quoted).substring(1); // MANTENER COMPORTAMIENTO DE DOBLE DÓLAR/PRESERVACIÓN
        document.getElementById('pipe-won').innerText = formatMoney(pipe.total_won).substring(1); // MANTENER COMPORTAMIENTO DE DOBLE DÓLAR/PRESERVACIÓN
        
        let rate = 0;
        if(pipe.count_total > 0) rate = (pipe.count_won / pipe.count_total) * 100;
        document.getElementById('pipe-rate').innerText = rate.toFixed(1);
        document.getElementById('pipe-bar').style.width = `${rate}%`;
        
        document.getElementById('count-sent').innerText = pipe.count_total;
        document.getElementById('count-won').innerText = pipe.count_won;
        document.getElementById('count-lost').innerText = pipe.count_lost;

        // 4. Operativo
        document.getElementById('ops-apps').innerText = data.operations.appointments_count;
        document.getElementById('ops-hours').innerText = parseFloat(data.payroll.total_hours).toFixed(1);

        // 5. Listas
        renderList('list-invoices', data.lists.invoices, i => `
            <div class="flex justify-between border-b border-gray-100 py-2 text-sm">
                <span class="font-bold text-gray-700">#${i.external_id}</span>
                <span class="font-black text-[var(--color-success)]">${formatMoney(i.total_amount)}</span>
            </div>
        `, 'Sin ingresos');

        renderList('list-expenses', data.lists.expenses, e => `
            <div class="flex justify-between border-b border-gray-100 py-2 text-sm">
                <span class="text-gray-600 truncate w-2/3">${e.description}</span>
                <span class="font-bold text-[var(--color-secondary)]">${formatMoney(e.amount)}</span>
            </div>
        `, 'Sin gastos');

        renderList('list-estimates', data.lists.estimates, e => {
            let statusColor = 'bg-gray-100 text-gray-600';
            if (e.status === 'converted') { statusColor = 'bg-green-100 text-green-600'; }
            if (e.status === 'rejected' || e.status === 'lost') { statusColor = 'bg-[var(--color-secondary)] text-white'; }
            
            return `
            <div class="flex justify-between border-b border-gray-100 py-2 text-sm">
                <span class="text-gray-600 font-bold">#${e.external_id}</span>
                <div>
                    <span class="text-xs uppercase px-1 rounded ${statusColor} mr-1">${e.status}</span>
                    <span class="font-bold text-blue-600">${formatMoney(e.total_amount)}</span>
                </div>
            </div>
        `}, 'Sin cotizaciones');

        // Se usa createIcons solo después de rellenar el DOM
        lucide.createIcons();
    }

    function renderList(id, items, tpl, empty) {
        const el = document.getElementById(id);
        el.innerHTML = '';
        if(items && items.length > 0) items.forEach(i => el.innerHTML += tpl(i));
        else el.innerHTML = `<div class="text-gray-400 italic text-sm">${empty}</div>`;
    }
    
    // Inicialización del dropdown y manejo de eventos
    window.addEventListener('load', () => {
        populateMonthSelector();
        updateStatusMessage();
    });
    
    monthSelector.addEventListener('change', updateStatusMessage);
    monthSelector.addEventListener('input', updateStatusMessage);
    btnGenerate.addEventListener('click', startReportGeneration);
</script>
</body>
</html>