/*************************************
 *  POS – NETTOYAGE URL & HREF
 *************************************/
if (window.location.hash) {
    history.replaceState(null, '', window.location.pathname + window.location.search);
}

document.addEventListener('click', function (e) {
    const link = e.target.closest('a[href="#"]');
    if (link) {
        e.preventDefault();
        e.stopPropagation();
    }
});

/*************************************
 *  VARIABLES GLOBALES
 *************************************/
let cart = [];

/*************************************
 *  AJOUT AU PANIER
 *************************************/
function addToCart(produit) {
    const exist = cart.find(p => p.id === produit.id);
    if (exist) {
        exist.qte++;
    } else {
        cart.push({
            id: produit.id,
            nom: produit.nom,
            prix_vente: Number(produit.prix_vente) || 0,
            qte: 1
        });
    }
    renderCart();
}

/*************************************
 *  AFFICHAGE PANIER
 *************************************/
function renderCart() {
    const container = document.getElementById('cartItems');
    container.innerHTML = '';

    if (cart.length === 0) {
        container.innerHTML = `<p class="text-muted text-center">Panier vide</p>`;
        document.getElementById('totalPanier').innerText = 0;
        document.getElementById('monnaie').innerText = 0;
        return;
    }

    cart.forEach((p, index) => {
        container.insertAdjacentHTML('beforeend', `
            <div class="d-flex justify-content-between align-items-center mb-2">
                <div>
                    <strong>${p.nom}</strong><br>
                    <small>${p.prix_vente.toLocaleString()} FCFA</small>
                </div>
                <div class="d-flex align-items-center gap-1">
                    <button class="btn btn-sm btn-outline-secondary" data-action="minus" data-index="${index}">−</button>
                    <span>${p.qte}</span>
                    <button class="btn btn-sm btn-outline-secondary" data-action="plus" data-index="${index}">+</button>
                    <button class="btn btn-sm btn-outline-danger" data-action="remove" data-index="${index}">×</button>
                </div>
            </div>
        `);
    });

    recalculerTotal();
}

/*************************************
 *  GESTION BOUTONS PANIER
 *************************************/
document.addEventListener('click', function (e) {
    const btn = e.target.closest('button[data-action]');
    if (!btn) return;

    const index = parseInt(btn.dataset.index, 10);
    if (isNaN(index) || !cart[index]) return;

    switch (btn.dataset.action) {
        case 'minus': cart[index].qte--; if (cart[index].qte <= 0) cart.splice(index, 1); break;
        case 'plus': cart[index].qte++; break;
        case 'remove': cart.splice(index, 1); break;
    }

    renderCart();
});

/*************************************
 *  CALCUL TOTAL / MONNAIE
 *************************************/
function recalculerTotal() {
    let totalHT = 0;
    cart.forEach(p => totalHT += p.prix_vente * p.qte);

    const remise = parseFloat(document.getElementById('remise')?.value) || 0;
    const montantVerse = parseFloat(document.getElementById('montantVerse')?.value) || 0;

    const totalTTC = Math.max(totalHT - remise, 0);
    const monnaie = Math.max(montantVerse - totalTTC, 0);

    document.getElementById('totalPanier').innerText = totalTTC.toLocaleString();
    document.getElementById('monnaie').innerText = monnaie.toLocaleString();

    return { totalHT, remise, totalTTC, montantVerse };
}

/*************************************
 *  RECALCUL AUTO SUR SAISIE
 *************************************/
['remise','montantVerse'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('input', recalculerTotal);
});

/*************************************
 *  LOADER IMPRESSION
 *************************************/
function showLoader(message="Impression en cours...") {
    if (document.getElementById('posLoader')) return;
    const loader = document.createElement('div');
    loader.id = 'posLoader';
    loader.style.cssText = `
        position:fixed; inset:0;
        background:rgba(0,0,0,.5);
        color:#fff; font-size:1.5rem;
        display:flex; justify-content:center; align-items:center;
        z-index:9999;
    `;
    loader.innerText = message;
    document.body.appendChild(loader);
}

function hideLoader() {
    const loader = document.getElementById('posLoader');
    if (loader) loader.remove();
}

