(function () {
    const articles = window.DARLINK_ARTICLES || [];
    const tarifsClients = window.DARLINK_TARIFS_CLIENTS || {};
    const existingLines = window.DARLINK_EXISTING_LINES || [];
    const clientSelect = document.getElementById('documentClientSelect');
    const tbody = document.querySelector('#documentLinesTable tbody');
    const addLineBtn = document.getElementById('addLineBtn');
    const search = document.getElementById('articleQuickSearch');
    const results = document.getElementById('articleResults');
    let lineIndex = 0;

    function money(value) {
        return (Number(value) || 0).toLocaleString('fr-FR', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    function number(value) {
        if (typeof value === 'number') return value;
        return Number(String(value || '0').replace(/\s/g, '').replace(',', '.')) || 0;
    }

    function roundMoney(value) {
        return Math.round((Number(value) + Number.EPSILON) * 100) / 100;
    }

    function escapeHtml(value) {
        return String(value).replace(/[&<>'"]/g, tag => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[tag]));
    }

    function currentClientId() {
        return clientSelect ? String(clientSelect.value || '') : '';
    }

    function priceForArticle(article) {
        const clientId = currentClientId();
        const articleId = String(article.id || '');
        const clientTarifs = tarifsClients[clientId] || {};
        const specificPrice = clientTarifs[articleId];

        if (specificPrice !== undefined && specificPrice !== null && Number(specificPrice) > 0) {
            return {price: Number(specificPrice), source: 'Tarif client'};
        }

        return {price: number(article.prix_vente_ht || 0), source: 'Prix article'};
    }

    function addLine(article = {}) {
        const idx = lineIndex++;
        let priceInfo = priceForArticle(article);
        if (article.prix_vente_ht !== undefined && article.prix_vente_ht !== null && Number(article.prix_vente_ht) >= 0 && article.__existingLine) {
            priceInfo = {price: number(article.prix_vente_ht), source: 'Prix document'};
        }
        const sourceClass = priceInfo.source === 'Tarif client' ? 'text-success' : 'text-muted';
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>
                <input type="hidden" name="lignes[${idx}][article_id]" value="${article.id || ''}">
                <input class="form-control form-control-sm" name="lignes[${idx}][reference]" value="${escapeHtml(article.reference || '')}">
                <input type="hidden" name="lignes[${idx}][prix_achat_ht]" value="${article.prix_achat_ht || 0}">
            </td>
            <td>
                <input class="form-control form-control-sm" name="lignes[${idx}][designation]" value="${escapeHtml(article.designation || '')}" required>
                <div class="small ${sourceClass}">${escapeHtml(priceInfo.source)}</div>
            </td>
            <td><input class="form-control form-control-sm" name="lignes[${idx}][unite]" value="${escapeHtml(article.unite || 'unité')}"></td>
            <td><input class="form-control form-control-sm text-end calc" name="lignes[${idx}][quantite]" value="${article.quantite || 1}" type="number" step="0.01" min="0"></td>
            <td><input class="form-control form-control-sm text-end calc" name="lignes[${idx}][prix_vente_ht]" value="${priceInfo.price || 0}" type="number" step="0.01" min="0"></td>
            <td><input class="form-control form-control-sm text-end calc" name="lignes[${idx}][remise]" value="${article.remise || 0}" type="number" step="0.01" min="0" max="100"></td>
            <td><input class="form-control form-control-sm text-end calc" name="lignes[${idx}][taux_tva]" value="${article.taux_tva || 20}" type="number" step="0.01" min="0"></td>
            <td class="text-end line-total">0,00</td>
            <td><button type="button" class="btn btn-sm btn-outline-danger remove-line">×</button></td>
        `;
        tbody.appendChild(tr);
        bindRow(tr);
        calculate();
    }

    function bindRow(tr) {
        tr.querySelectorAll('.calc').forEach(input => input.addEventListener('input', calculate));
        tr.querySelector('.remove-line').addEventListener('click', () => { tr.remove(); calculate(); });
    }

    function calculate() {
        let totalHt = 0;
        let totalTva = 0;
        let totalMarge = 0;
        document.querySelectorAll('#documentLinesTable tbody tr').forEach(row => {
            const qte = number(row.querySelector('[name$="[quantite]"]').value);
            const prix = number(row.querySelector('[name$="[prix_vente_ht]"]').value);
            const remise = number(row.querySelector('[name$="[remise]"]').value);
            const tva = number(row.querySelector('[name$="[taux_tva]"]').value);
            const achat = number(row.querySelector('[name$="[prix_achat_ht]"]').value);
            const ht = roundMoney(qte * prix * (1 - (remise / 100)));
            const tvaAmount = roundMoney(ht * (tva / 100));
            const ttc = roundMoney(ht + tvaAmount);
            const marge = roundMoney(ht - (qte * achat));
            totalHt = roundMoney(totalHt + ht);
            totalTva = roundMoney(totalTva + tvaAmount);
            totalMarge = roundMoney(totalMarge + marge);
            row.querySelector('.line-total').innerText = money(ht);
        });
        document.getElementById('totalHt').innerText = money(totalHt);
        document.getElementById('totalTva').innerText = money(totalTva);
        document.getElementById('totalTtc').innerText = money(roundMoney(totalHt + totalTva));
        document.getElementById('totalMarge').innerText = totalHt > 0 ? money((totalMarge / totalHt) * 100) + ' %' : '0,00 %';
    }

    function showResults(query) {
        query = String(query || '').trim().toLocaleLowerCase('fr-FR');
        if (query.length < 1) { results.style.display = 'none'; return; }
        const found = articles.filter(a => (`${a.reference || ''} ${a.designation || ''}`).toLocaleLowerCase('fr-FR').includes(query)).slice(0, 20);
        results.innerHTML = '';
        found.forEach(article => {
            const button = document.createElement('button');
            button.type = 'button';
            button.className = 'list-group-item list-group-item-action';
            const priceInfo = priceForArticle(article);
            const badge = priceInfo.source === 'Tarif client' ? ' <span class="badge bg-success ms-2">Tarif client</span>' : '';
            button.innerHTML = `<strong>${escapeHtml(article.reference)}</strong> — ${escapeHtml(article.designation)}${badge} <span class="float-end">${money(priceInfo.price)} DH</span>`;
            button.addEventListener('click', () => {
                addLine(article);
                search.value = '';
                results.style.display = 'none';
            });
            results.appendChild(button);
        });
        results.style.display = found.length ? 'block' : 'none';
    }

    if (Array.isArray(existingLines) && existingLines.length) {
        existingLines.forEach(line => addLine({...line, __existingLine: true}));
    }

    addLineBtn?.addEventListener('click', () => addLine());
    search?.addEventListener('input', () => showResults(search.value));
    document.addEventListener('click', (e) => {
        if (results && !results.contains(e.target) && e.target !== search) results.style.display = 'none';
    });
    document.getElementById('documentForm')?.addEventListener('submit', function (e) {
        if (!document.querySelector('#documentLinesTable tbody tr')) {
            e.preventDefault();
            alert('Veuillez ajouter au moins une ligne au document.');
        }
    });
})();
