/**
 * JavaScript para el Módulo de Inventario en Tiempo Real
 * SufarmaERP
 */

document.addEventListener('DOMContentLoaded', function() {
    let currentPage = 1;
    let searchQuery = '';
    let sucursalId = 0;
    let searchDebounceTimeout = null;

    // Elementos del DOM
    const filtroSucursal = document.getElementById('filtroSucursal');
    const buscarProducto = document.getElementById('buscarProducto');
    const filtroExistencias = document.getElementById('filtroExistencias');
    const totalItemsCount = document.getElementById('totalItemsCount');
    const totalStockText = document.getElementById('totalStockText');
    const totalValorizadoText = document.getElementById('totalValorizadoText');
    const tablaHeader = document.getElementById('tablaHeader');
    const tablaBody = document.getElementById('tablaBody');
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationControls = document.getElementById('paginationControls');

    // 1. Inicialización sincronizada con el selector global de sucursales
    inicializarSucursal();

    // 2. Cargar inventario por primera vez
    loadInventory();

    // 3. Registrar Eventos
    filtroSucursal.addEventListener('change', function() {
        sucursalId = parseInt(this.value);
        currentPage = 1;
        
        // Sincronizar con localStorage de layout.php para mantener coherencia en todo el ERP
        try {
            localStorage.setItem('sucursal_id', sucursalId);
            // Si el selector global de sucursales en el layout existe, actualizarlo también
            const globalSel = document.getElementById('globalSucursalSelect');
            if (globalSel) {
                globalSel.value = sucursalId;
            }
        } catch(e) {
            console.error("No se pudo guardar la sucursal seleccionada", e);
        }

        loadInventory();
    });

    filtroExistencias.addEventListener('change', function() {
        currentPage = 1;
        loadInventory();
    });

    buscarProducto.addEventListener('input', function() {
        clearTimeout(searchDebounceTimeout);
        searchQuery = this.value.trim();
        currentPage = 1;

        searchDebounceTimeout = setTimeout(() => {
            loadInventory();
        }, 300);
    });

    // === FUNCIONES PRINCIPALES ===

    function inicializarSucursal() {
        try {
            // Sincronizar y bloquear la sucursal según el filtro de la barra lateral
            const activeSuc = typeof getSucursalId === 'function' ? getSucursalId() : 0;
            if (activeSuc > 0) {
                filtroSucursal.value = activeSuc;
                filtroSucursal.disabled = true;
                sucursalId = activeSuc;
            } else {
                filtroSucursal.disabled = false;
                const savedSuc = localStorage.getItem('sucursal_id');
                if (savedSuc !== null) {
                    sucursalId = parseInt(savedSuc);
                    if (filtroSucursal.querySelector(`option[value="${sucursalId}"]`)) {
                        filtroSucursal.value = sucursalId;
                    } else {
                        filtroSucursal.value = 0;
                        sucursalId = 0;
                    }
                } else {
                    sucursalId = parseInt(filtroSucursal.value || 0);
                }
            }
        } catch(e) {
            sucursalId = 0;
        }
    }

    function loadInventory() {
        renderCargando();

        const soloExistencias = filtroExistencias.checked ? 1 : 0;
        const url = `api/inventario/productos/real_time.php?query=${encodeURIComponent(searchQuery)}&sucursal_id=${sucursalId}&page=${currentPage}&solo_existencias=${soloExistencias}`;
        
        fetch(url)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    renderizarTabla(data.data);
                    renderizarPaginacion(data.data);
                    actualizarMetricas(data.data);
                } else {
                    renderizarError(data.message || 'Error al cargar los datos.');
                }
            })
            .catch(err => {
                console.error("Error fetching real-time inventory:", err);
                renderizarError('Ocurrió un error al conectarse con el servidor.');
            });
    }

    function renderCargando() {
        const colCount = sucursalId === 0 ? 12 : 7;
        tablaBody.innerHTML = `
            <tr>
                <td colspan="${colCount}" style="text-align: center; color: var(--text-muted); padding: 3rem;">
                    <i class="fas fa-spinner fa-pulse" style="font-size: 2rem; margin-bottom: 0.75rem; display: block; color: var(--accent-color);"></i>
                    Buscando productos y calculando stock...
                </td>
            </tr>
        `;
    }

    function renderizarError(msg) {
        const colCount = sucursalId === 0 ? 12 : 7;
        tablaBody.innerHTML = `
            <tr>
                <td colspan="${colCount}" style="text-align: center; color: var(--danger); padding: 3rem; font-weight: 600;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 2.5rem; margin-bottom: 0.75rem; display: block;"></i>
                    ${escapeHTML(msg)}
                </td>
            </tr>
        `;
    }

    function renderizarTabla(data) {
        // 1. Dibujar Cabecera
        if (sucursalId === 0) {
            tablaHeader.innerHTML = `
                <tr>
                    <th style="width: 100px;">Código</th>
                    <th>Producto</th>
                    <th style="text-align: right; width: 95px;">Bodega</th>
                    <th style="text-align: right; width: 95px;">Sanfe (S2)</th>
                    <th style="text-align: right; width: 95px;">Terminal (S3)</th>
                    <th style="text-align: right; width: 95px;">Sector 8 (S4)</th>
                    <th style="text-align: right; width: 95px;">Centro (S5)</th>
                    <th style="text-align: right; width: 105px; color: var(--accent-color);">Stock Gral</th>
                    <th style="text-align: right; width: 105px;">Costo Base</th>
                    <th style="text-align: right; width: 130px;">Valorizado</th>
                    <th style="width: 130px;">Última Act.</th>
                    <th style="width: 250px;">Próximos Vencimientos</th>
                </tr>
            `;
        } else {
            tablaHeader.innerHTML = `
                <tr>
                    <th style="width: 100px;">Código</th>
                    <th>Producto</th>
                    <th style="text-align: right; width: 120px; color: var(--accent-color);">Stock Total</th>
                    <th style="text-align: right; width: 120px;">Costo Local</th>
                    <th style="text-align: right; width: 140px;">Valorizado Local</th>
                    <th style="width: 130px;">Última Act.</th>
                    <th style="width: 250px;">Próximos Vencimientos</th>
                </tr>
            `;
        }

        // 2. Dibujar Cuerpo
        tablaBody.innerHTML = '';

        if (!data.products || data.products.length === 0) {
            const colCount = sucursalId === 0 ? 12 : 7;
            tablaBody.innerHTML = `
                <tr>
                    <td colspan="${colCount}" style="text-align: center; color: var(--text-muted); padding: 3rem;">
                        <i class="fas fa-info-circle" style="font-size: 2rem; margin-bottom: 0.75rem; display: block; color: var(--info);"></i>
                        No se encontraron productos en el inventario.
                    </td>
                </tr>
            `;
            return;
        }

        data.products.forEach(p => {
            const tr = document.createElement('tr');
            
            const labText = p.laboratorio ? `<div style="font-size:0.7rem; color:var(--text-muted); margin-top:0.1rem;">${escapeHTML(p.laboratorio)}</div>` : '';
            const genText = ''; // Hiden from product listing to reduce clutter as requested
            
            // Badge Tipo Stock (Facturado / Sin Factura)
            const badgeClass = p.tipo_inventario === 'facturado' ? 'badge-soft-success' : 'badge-soft-danger';
            const badgeText = p.tipo_inventario === 'facturado' ? 'Facturado' : 'Sin Factura';
            const badgeHtml = `<span class="badge-premium ${badgeClass}" style="font-size: 0.65rem; padding: 0.15rem 0.45rem; border-radius: 4px; font-weight:600; display:inline-block; vertical-align:middle; margin-left: 0.5rem;">${badgeText}</span>`;
            
            const dateStr = formatDateTime(p.fecha_registro);

            if (sucursalId === 0) {
                // Fila Consolidada con vencimientos de múltiples sucursales
                let vencHtml = '<div style="color:var(--text-muted); font-size:0.75rem;">Sin vencimientos</div>';
                if (p.vencimientos && p.vencimientos.length > 0) {
                    vencHtml = '<div class="vencimientos-container">';
                    p.vencimientos.forEach(v => {
                        vencHtml += getVencimientoBadgeConsolidado(v);
                    });
                    vencHtml += '</div>';
                }

                tr.innerHTML = `
                    <td style="font-family: monospace; font-size: 0.8rem; font-weight: 500; vertical-align: middle; white-space: nowrap;">${escapeHTML(p.codigo || 'S/C')}</td>
                    <td style="vertical-align: middle;">
                        <div style="display:flex; align-items:center; flex-wrap:wrap; gap:0.25rem;">
                            <span style="font-weight: 600; color: var(--text-primary);">${escapeHTML(p.nombre)}</span>
                            ${badgeHtml}
                        </div>
                        ${labText}
                    </td>
                    <td style="text-align: right; vertical-align: middle; white-space: nowrap;" class="${p.stock_suc_1 > 0 ? 'stock-val-highlight' : 'stock-val-zero'}">${p.stock_suc_1}</td>
                    <td style="text-align: right; vertical-align: middle; white-space: nowrap;" class="${p.stock_suc_2 > 0 ? 'stock-val-highlight' : 'stock-val-zero'}">${p.stock_suc_2}</td>
                    <td style="text-align: right; vertical-align: middle; white-space: nowrap;" class="${p.stock_suc_3 > 0 ? 'stock-val-highlight' : 'stock-val-zero'}">${p.stock_suc_3}</td>
                    <td style="text-align: right; vertical-align: middle; white-space: nowrap;" class="${p.stock_suc_4 > 0 ? 'stock-val-highlight' : 'stock-val-zero'}">${p.stock_suc_4}</td>
                    <td style="text-align: right; vertical-align: middle; white-space: nowrap;" class="${p.stock_suc_5 > 0 ? 'stock-val-highlight' : 'stock-val-zero'}">${p.stock_suc_5}</td>
                    <td style="text-align: right; vertical-align: middle; font-weight: 700; color: var(--accent-color); white-space: nowrap;">${p.stock_total_general}</td>
                    <td style="text-align: right; color: var(--text-light); vertical-align: middle; white-space: nowrap;">Q ${p.costo_promedio.toFixed(4)}</td>
                    <td style="text-align: right; font-weight: 600; vertical-align: middle; white-space: nowrap;">Q ${p.valorizado_total.toFixed(2)}</td>
                    <td style="vertical-align: middle; font-size: 0.75rem; color: var(--text-light); white-space: nowrap;">${escapeHTML(dateStr)}</td>
                    <td style="vertical-align: middle;">${vencHtml}</td>
                `;
            } else {
                // Fila Específica con vencimientos
                let vencHtml = '<div style="color:var(--text-muted); font-size:0.75rem;">Sin vencimientos registrados</div>';
                if (p.vencimientos && p.vencimientos.length > 0) {
                    vencHtml = '<div class="vencimientos-container">';
                    p.vencimientos.forEach(v => {
                        vencHtml += getVencimientoBadge(v);
                    });
                    vencHtml += '</div>';
                }

                tr.innerHTML = `
                    <td style="font-family: monospace; font-size: 0.8rem; font-weight: 500; vertical-align: middle; white-space: nowrap;">${escapeHTML(p.codigo || 'S/C')}</td>
                    <td style="vertical-align: middle;">
                        <div style="display:flex; align-items:center; flex-wrap:wrap; gap:0.25rem;">
                            <span style="font-weight: 600; color: var(--text-primary);">${escapeHTML(p.nombre)}</span>
                            ${badgeHtml}
                        </div>
                        ${labText}
                    </td>
                    <td style="text-align: right; font-weight: 700; color: var(--accent-color); vertical-align: middle; white-space: nowrap;">${p.stock_total}</td>
                    <td style="text-align: right; color: var(--text-light); vertical-align: middle; white-space: nowrap;">Q ${p.costo_promedio.toFixed(4)}</td>
                    <td style="text-align: right; font-weight: 600; vertical-align: middle; white-space: nowrap;">Q ${p.valorizado_total.toFixed(2)}</td>
                    <td style="vertical-align: middle; font-size: 0.75rem; color: var(--text-light); white-space: nowrap;">${escapeHTML(dateStr)}</td>
                    <td style="vertical-align: middle;">${vencHtml}</td>
                `;
            }
            tablaBody.appendChild(tr);
        });
    }

    function getVencimientoBadge(venc) {
        const parts = venc.fecha.split('-');
        if (parts.length !== 3) return '';
        
        // Parsear fecha de vencimiento de forma local
        const dateVal = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
        const today = new Date();
        today.setHours(0,0,0,0);
        
        const diffTime = dateVal - today;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        let badgeClass = 'venc-active';
        let title = `Vence: ${parts[2]}/${parts[1]}/${parts[0]}`;
        
        if (diffDays < 0) {
            badgeClass = 'venc-expired';
            title = `¡VENCIDO! (${parts[2]}/${parts[1]}/${parts[0]})`;
        } else if (diffDays <= 180) {
            badgeClass = 'venc-warning';
            title = `Por vencer (${parts[2]}/${parts[1]}/${parts[0]})`;
        }
        
        return `<span class="venc-badge ${badgeClass}" title="${title}">
            <i class="fas fa-calendar-times"></i> ${parts[2]}/${parts[1]}/${parts[0]} (${venc.cantidad} u)
        </span>`;
    }

    function renderizarPaginacion(data) {
        // Actualizar Info de paginación
        const from = data.total === 0 ? 0 : (data.page - 1) * data.limit + 1;
        const to = Math.min(data.page * data.limit, data.total);
        paginationInfo.textContent = `Mostrando ${from} - ${to} de ${data.total} registros`;

        // Limpiar controles de paginación
        paginationControls.innerHTML = '';
        if (data.pages <= 1) return;

        // Botón Anterior
        const btnPrev = document.createElement('button');
        btnPrev.className = `btn btn-secondary ${data.page === 1 ? 'disabled' : ''}`;
        btnPrev.innerHTML = '<i class="fas fa-chevron-left"></i>';
        btnPrev.style.padding = '0.35rem 0.6rem';
        if (data.page > 1) {
            btnPrev.addEventListener('click', () => {
                currentPage--;
                loadInventory();
            });
        }
        paginationControls.appendChild(btnPrev);

        // Páginas Intermedias (Algoritmo simplificado para no mostrar 100 botones)
        let startPage = Math.max(1, data.page - 2);
        let endPage = Math.min(data.pages, data.page + 2);

        if (startPage > 1) {
            const btnFirst = document.createElement('button');
            btnFirst.className = 'btn btn-secondary';
            btnFirst.textContent = '1';
            btnFirst.style.padding = '0.35rem 0.6rem';
            btnFirst.addEventListener('click', () => {
                currentPage = 1;
                loadInventory();
            });
            paginationControls.appendChild(btnFirst);

            if (startPage > 2) {
                const dots = document.createElement('span');
                dots.textContent = '...';
                dots.style.alignSelf = 'center';
                dots.style.margin = '0 0.25rem';
                dots.style.color = 'var(--text-muted)';
                paginationControls.appendChild(dots);
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const btnPage = document.createElement('button');
            btnPage.className = `btn ${data.page === i ? 'btn-primary' : 'btn-secondary'}`;
            btnPage.textContent = i;
            btnPage.style.padding = '0.35rem 0.6rem';
            btnPage.addEventListener('click', () => {
                currentPage = i;
                loadInventory();
            });
            paginationControls.appendChild(btnPage);
        }

        if (endPage < data.pages) {
            if (endPage < data.pages - 1) {
                const dots = document.createElement('span');
                dots.textContent = '...';
                dots.style.alignSelf = 'center';
                dots.style.margin = '0 0.25rem';
                dots.style.color = 'var(--text-muted)';
                paginationControls.appendChild(dots);
            }

            const btnLast = document.createElement('button');
            btnLast.className = 'btn btn-secondary';
            btnLast.textContent = data.pages;
            btnLast.style.padding = '0.35rem 0.6rem';
            btnLast.addEventListener('click', () => {
                currentPage = data.pages;
                loadInventory();
            });
            paginationControls.appendChild(btnLast);
        }

        // Botón Siguiente
        const btnNext = document.createElement('button');
        btnNext.className = `btn btn-secondary ${data.page === data.pages ? 'disabled' : ''}`;
        btnNext.innerHTML = '<i class="fas fa-chevron-right"></i>';
        btnNext.style.padding = '0.35rem 0.6rem';
        if (data.page < data.pages) {
            btnNext.addEventListener('click', () => {
                currentPage++;
                loadInventory();
            });
        }
        paginationControls.appendChild(btnNext);
    }

    function formatConsolidatedCell(total, f, nf) {
        if (total <= 0) return '<span class="stock-val-zero">0</span>';
        return `
            <div class="font-bold text-slate-200" style="font-size:0.85rem;">${total}</div>
            <div style="font-size:0.65rem; color:var(--text-muted); line-height: 1.15; margin-top:0.05rem;">
                <span style="color:var(--success); font-weight:600;">${f} F</span> | <span style="color:var(--danger); font-weight:600;">${nf} NF</span>
            </div>
        `;
    }

    function formatGeneralCell(total, f, nf) {
        if (total <= 0) return '<span class="stock-val-zero">0</span>';
        return `
            <div class="font-bold" style="font-size:0.85rem; color:var(--accent-color);">${total}</div>
            <div style="font-size:0.65rem; color:var(--text-muted); line-height: 1.15; margin-top:0.05rem;">
                <span style="color:var(--success); font-weight:600;">${f} F</span> | <span style="color:var(--danger); font-weight:600;">${nf} NF</span>
            </div>
        `;
    }

    function actualizarMetricas(data) {
        totalItemsCount.textContent = data.total;
        
        // Stock total y desglose
        totalStockText.textContent = `${data.grand_total_stock.toLocaleString('es-GT')} u.`;
        
        const totalStockBreakdown = document.getElementById('totalStockBreakdown');
        if (totalStockBreakdown) {
            totalStockBreakdown.innerHTML = `<span style="color:var(--success); font-weight:600;">${data.grand_total_stock_f.toLocaleString('es-GT')} F</span> | <span style="color:var(--danger); font-weight:600;">${data.grand_total_stock_nf.toLocaleString('es-GT')} NF</span>`;
        }
        
        // Valorizado total y desglose
        const valTotal = data.grand_total_valorizado.toLocaleString('es-GT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        const valF = data.grand_total_valorizado_f.toLocaleString('es-GT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        const valNf = data.grand_total_valorizado_nf.toLocaleString('es-GT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        
        totalValorizadoText.textContent = `Q ${valTotal}`;
        
        const totalValorizadoBreakdown = document.getElementById('totalValorizadoBreakdown');
        if (totalValorizadoBreakdown) {
            totalValorizadoBreakdown.innerHTML = `<span style="color:var(--success); font-weight:600;">Q ${valF} F</span> | <span style="color:var(--danger); font-weight:600;">Q ${valNf} NF</span>`;
        }
    }

    function formatDateTime(sqlDateTime) {
        if (!sqlDateTime) return '-';
        try {
            const date = new Date(sqlDateTime.replace(' ', 'T'));
            if (isNaN(date.getTime())) return sqlDateTime;
            
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${day}/${month}/${year} ${hours}:${minutes}`;
        } catch(e) {
            return sqlDateTime;
        }
    }

    function escapeHTML(str) {
        if (!str) return '';
        return str.replace(/[&<>'"]/g, 
            tag => ({
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                "'": '&#39;',
                '"': '&quot;'
            }[tag] || tag)
        );
    }

    function getVencimientoBadgeConsolidado(venc) {
        const parts = venc.fecha.split('-');
        if (parts.length !== 3) return '';
        
        const dateVal = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
        const today = new Date();
        today.setHours(0,0,0,0);
        
        const diffTime = dateVal - today;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        let badgeClass = 'venc-active';
        let title = `${venc.sucursal_nombre} - Vence: ${parts[2]}/${parts[1]}/${parts[0]}`;
        
        if (diffDays < 0) {
            badgeClass = 'venc-expired';
            title = `${venc.sucursal_nombre} - ¡VENCIDO! (${parts[2]}/${parts[1]}/${parts[0]})`;
        } else if (diffDays <= 180) {
            badgeClass = 'venc-warning';
            title = `${venc.sucursal_nombre} - Por vencer (${parts[2]}/${parts[1]}/${parts[0]})`;
        }
        
        let shortBranch = venc.sucursal_nombre.split(' ')[0];
        
        return `<span class="venc-badge ${badgeClass}" title="${title}" style="margin: 2px;">
            <i class="fas fa-calendar-times"></i> <strong>${escapeHTML(shortBranch)}:</strong> ${parts[2]}/${parts[1]}/${parts[0]} (${venc.cantidad} u)
        </span>`;
    }

    window.exportarExcel = function(facturadoVal) {
        const soloExistencias = filtroExistencias.checked ? 1 : 0;
        const url = `api/inventario/productos/exportar_real_time.php?query=${encodeURIComponent(searchQuery)}&sucursal_id=${sucursalId}&solo_existencias=${soloExistencias}&facturado=${facturadoVal}`;
        window.open(url, '_blank');
    };
});
