/**
 * BICHOTTA - Progressive Web App Logic & UI
 */

// 1. Registro dinámico del Service Worker (Solo en producción)
const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    window.location.hostname === '[::1]' ||
    window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);

if ('serviceWorker' in navigator) {
    if (isLocalhost) {
        // Desregistrar SW en local para evitar caché
        navigator.serviceWorker.getRegistrations().then(registrations => {
            for (let registration of registrations) {
                registration.unregister();
                console.log('SW Unregistered for development');
            }
        });
    } else {
        window.addEventListener('load', () => {
            const swPath = window.location.pathname.includes('/admin/') ? '../service-worker.js' : 'service-worker.js';
            navigator.serviceWorker.register(swPath)
                .then(reg => console.log('SW Registered'))
                .catch(err => console.log('SW Error', err));
        });
    }
}

/**
 * UI Interactions
 */
document.addEventListener('DOMContentLoaded', () => {
    
    // -- Lógica de Popups de Marketing --
    const popup = document.getElementById('marketing-popup');
    if (popup) {
        const closeBtns = popup.querySelectorAll('.close-popup');
        closeBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                popup.style.display = 'none';
            });
        });
        popup.addEventListener('click', (e) => {
            if (e.target === popup) popup.style.display = 'none';
        });
    }

    // -- Botones de Añadir Rápido (+) --
    const quickAddBtns = document.querySelectorAll('.quick-add-btn');
    quickAddBtns.forEach(btn => {
        btn.addEventListener('click', async (e) => {
            e.preventDefault();
            e.stopPropagation();
            const productId = btn.dataset.id;
            
            try {
                const response = await fetch('api/cart.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `product_id=${productId}&quantity=1`
                });
                const data = await response.json();
                
                if (data.success) {
                    showCartToast();
                    updateCartBadges(data.cart_count);
                }
            } catch (err) {
                console.error('Error adding to cart', err);
            }
        });
    });

    // -- Navegación de Imágenes (Shein Style) --
    const nextBtns = document.querySelectorAll('.img-next');
    const prevBtns = document.querySelectorAll('.img-prev');

    nextBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            alert('Función de galería: Aquí Shein cambia a la siguiente imagen del producto.');
        });
    });

    prevBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            alert('Función de galería: Aquí Shein vuelve a la imagen anterior.');
        });
    });

    function showCartToast() {
        const toast = document.createElement('div');
        toast.className = 'product-added-toast';
        toast.innerHTML = '✨ ¡Añadido a tu bolsa!';
        document.body.appendChild(toast);
        
        const cartIcons = document.querySelectorAll('.action-icon svg, .mobile-nav-item svg');
        cartIcons.forEach(icon => {
            icon.classList.add('cart-animate');
            setTimeout(() => icon.classList.remove('cart-animate'), 600);
        });

        setTimeout(() => toast.remove(), 3000);
    }

    function updateCartBadges(count) {
        const badges = document.querySelectorAll('.cart-badge, .cart-count, .cart-badge-mobile');
        badges.forEach(b => {
            b.textContent = count;
            b.style.display = count > 0 ? 'flex' : 'none';
        });
    }

});

// -- PWA Install Logic --
let deferredPrompt;
const installBtn = document.createElement('div');
installBtn.id = 'pwa-install-banner';
installBtn.innerHTML = `
    <div class="pwa-content">
        <span>👗 ¡Instala la App de BICHOTTA!</span>
        <button id="btn-pwa-install">Instalar</button>
        <button id="btn-pwa-close">✕</button>
    </div>
`;

window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    deferredPrompt = e;
    if (!window.matchMedia('(display-mode: standalone)').matches) {
        document.body.appendChild(installBtn);
    }
});

document.addEventListener('click', (e) => {
    if (e.target.id === 'btn-pwa-install') {
        if (deferredPrompt) {
            deferredPrompt.prompt();
            deferredPrompt.userChoice.then(() => installBtn.remove());
        }
    }
    if (e.target.id === 'btn-pwa-close') {
        installBtn.remove();
    }
});
