// 🧠 ESTADO GLOBAL
let carrito = [];

function resolverRutaFoto(foto){
    const fallback = 'assets/img/default.jpg';
    if(!foto) return fallback;

    const valor = String(foto).trim();
    if(!valor) return fallback;

    if(/^https?:\/\//i.test(valor) || valor.startsWith('assets/img/')){
        return valor;
    }

    if(/\.(webp|jpe?g|png|gif|avif)$/i.test(valor)){
        return `assets/img/${valor}`;
    }

    return `assets/img/${valor}.webp`;
}

// 📦 CARGAR CARRITO
function cargarCarrito(){
    const data = localStorage.getItem('carrito');
    carrito = data ? JSON.parse(data) : [];
}

// 💾 GUARDAR
function guardarCarrito(){
    localStorage.setItem('carrito', JSON.stringify(carrito));
}

// 🔢 BADGE
function actualizarBadge(){
    const badge = document.getElementById('badgePedido');
    if(!badge) return;

    const total = carrito.reduce((acc, p) => acc + p.cantidad, 0);

    badge.innerText = total;
    badge.style.display = total > 0 ? 'block' : 'none';
}

// 🔞 MODAL EDAD
function aceptarEdad(){
    localStorage.setItem('edadOK', 'true');

    const modal = document.getElementById('ageModal');
    if(modal){
        modal.style.display = 'none';
    }
}

// AUTO OCULTAR SI YA ACEPTÓ
document.addEventListener("DOMContentLoaded", () => {
    const modal = document.getElementById('ageModal');

    if(localStorage.getItem('edadOK') === 'true'){
        if(modal) modal.style.display = 'none';
    } else {
        if(modal) modal.style.display = 'flex';
    }
});

// 🧾 VER PEDIDO
function verPedido(){
    const cont = document.getElementById('listaPedido');
    if(!cont) return;

    cont.innerHTML = '';

    if(carrito.length === 0){
        cont.innerHTML = `<p>Hola, no has elegido productos aún.</p>`;
    }

    carrito.forEach(p => {
        cont.innerHTML += `
        <div class="d-flex mb-2 align-items-center">
            <img src="${resolverRutaFoto(p.foto)}" width="50" onerror="this.onerror=null; this.src='assets/img/default.jpg';">
            <span class="ms-2">${p.titulo} x${p.cantidad}</span>
        </div>
        `;
    });

    document.getElementById('pedidoModal')?.classList.remove('hidden');
}

// ❌ CERRAR PEDIDO
function cerrarPedido(){
    document.getElementById('pedidoModal')?.classList.add('hidden');
}

// 🔗 NAVEGACIÓN
function ir(url){
    window.location.href = url;
}

// 🎯 ACTIVE MENU
function activarMenu(){
    const page = document.body.getAttribute('data-page');

    document.querySelectorAll('.card-menu').forEach(card => {
        if(page && card.innerText.toLowerCase().includes(page)){
            card.classList.add('active-menu');
        }
    });
}

function actualizarEstadoHeader(){
    const headerTop = document.querySelector('.header-top');
    if(!headerTop) return;

    if(window.scrollY > 0){
        document.body.classList.add('header-collapsed');
    } else {
        document.body.classList.remove('header-collapsed');
    }
}

function iniciarHeaderScroll(){
    const headerTop = document.querySelector('.header-top');
    if(!headerTop) return;

    actualizarEstadoHeader();
    window.addEventListener('scroll', actualizarEstadoHeader, { passive: true });
}

function normalizarTexto(valor){
    return String(valor || '')
        .trim()
        .toLowerCase()
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '');
}

function resaltarHorarioHoy(){
    const filasHorario = document.querySelectorAll('.schedule-row[data-day]');
    if(filasHorario.length === 0) return;

    const dias = ['domingo', 'lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado'];
    const hoy = dias[new Date().getDay()];

    filasHorario.forEach(fila => {
        const diaFila = normalizarTexto(fila.getAttribute('data-day'));
        if(diaFila === hoy){
            fila.classList.add('hoy');
        } else {
            fila.classList.remove('hoy');
        }
    });
}

// 🚀 INIT GLOBAL
document.addEventListener("DOMContentLoaded", () => {
    cargarCarrito();
    actualizarBadge();
    activarMenu();
    iniciarHeaderScroll();
    resaltarHorarioHoy();
});
