/**
 * Fichier  : assets/js/pages/suppliers.js
 * Auteur   : KREMER Régis
 * Version  : 2.3.0
 * Date     : 2026-03-14
 * Description : JS — Fournisseurs : CRUD avancé, statuts, multi-contacts,
 *               conditions commerciales et marques associées
 */
const SupplierPage = {
    suppliers: [],
    brands: [],

    esc(v){
        return String(v ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));
    },

    normalizeSupplier(s = {}) {
        return {
            id: s.id,
            name: s.name || '',
            companyName: s.companyName || '',
            contact: s.contact || '',
            email: s.email || '',
            phone: s.phone || '',
            website: s.website || '',
            address: s.address || '',
            siret: s.siret || '',
            vatNumber: s.vatNumber || '',
            leadTime: Number(s.leadTime || s.leadTimeDays || 0) || 0,
            minimumOrderAmount: Number(s.minimumOrderAmount || 0) || 0,
            freeShippingThreshold: Number(s.freeShippingThreshold || 0) || 0,
            paymentTerms: s.paymentTerms || '',
            status: s.status || 'active',
            notes: s.notes || '',
            linkedBrands: Array.isArray(s.linkedBrands) ? s.linkedBrands : (()=>{ try{ return JSON.parse(s.linkedBrands || '[]'); } catch(_){ return []; } })(),
            contacts: Array.isArray(s.contacts) ? s.contacts : (()=>{ try{ return JSON.parse(s.contacts || '[]'); } catch(_){ return []; } })(),
        };
    },

    statusLabel(status){
        const map = {
            active: 'Actif',
            watch: 'À surveiller',
            inactive: 'Inactif',
            blocked: 'Bloqué'
        };
        return map[status] || 'Actif';
    },

    statusBadge(status){
        const label = this.statusLabel(status);
        const styles = {
            active: 'background:rgba(16,185,129,.15);color:#059669;border:1px solid rgba(16,185,129,.22);',
            watch: 'background:rgba(245,158,11,.15);color:#b45309;border:1px solid rgba(245,158,11,.22);',
            inactive: 'background:rgba(107,114,128,.12);color:#4b5563;border:1px solid rgba(107,114,128,.18);',
            blocked: 'background:rgba(239,68,68,.12);color:#b91c1c;border:1px solid rgba(239,68,68,.18);'
        };
        return `<span class="badge" style="${styles[status] || styles.active}">${label}</span>`;
    },

    money(v){
        const n = Number(v || 0);
        return n > 0 ? n.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' }) : '—';
    },

    async init() {
        const search = document.getElementById('suppSearch');
        const btnNew = document.getElementById('btnNewSupp');

        if (search) search.addEventListener('input', () => this.load());
        if (btnNew) btnNew.onclick = () => this.openModal();

        try {
            this.brands = await Api.brands();
        } catch(e) {
            console.error('[SupplierPage] Error loading brands:', e);
            this.brands = [];
        }

        await this.load();
    },

    async load() {
        const q = document.getElementById('suppSearch')?.value || '';
        try {
            const suppliers = await Api.suppliers(q);
            this.suppliers = (suppliers || []).map(s => this.normalizeSupplier(s));
            const countEl = document.getElementById('suppCount');
            if (countEl) countEl.textContent = this.suppliers.length + ' fournisseur(s)';
            this.renderTable(this.suppliers);
        } catch(e) {
            console.error('[SupplierPage] Error loading suppliers:', e);
            toast('Erreur chargement fournisseurs: ' + e.message, 'error');
        }
    },

    renderTable(suppliers) {
        const tbody = document.getElementById('suppBody');
        if (!tbody) return;

        if(!suppliers.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="tbl-empty">Aucun fournisseur</td></tr>';
            return;
        }

        tbody.innerHTML = suppliers.map(raw => {
            const s = this.normalizeSupplier(raw);
            const linkedBrands = this.brands.filter(b => s.linkedBrands.includes(b.id));
            const brandsDisplay = linkedBrands.length > 0
                ? linkedBrands.map(b => `<span class="badge">${this.esc(b.name)}</span>`).join(' ')
                : '—';
            const contactsCount = Array.isArray(s.contacts) ? s.contacts.length : 0;
            const supplierTitle = `<div><strong>${this.esc(s.name)}</strong></div>` +
                (s.companyName ? `<div style="color:var(--text-muted);font-size:.92em">${this.esc(s.companyName)}</div>` : '') +
                (s.siret ? `<div style="color:var(--text-muted);font-size:.88em">SIRET : ${this.esc(s.siret)}</div>` : '');
            const primaryContact = s.contact
                ? `<div><strong>${this.esc(s.contact)}</strong></div>`
                : '<span style="color:var(--text-muted)">—</span>';
            const coordinates = [
                s.email ? `<div>${this.esc(s.email)}</div>` : '',
                s.phone ? `<div>${this.esc(s.phone)}</div>` : '',
                s.website ? `<div>${this.esc(s.website)}</div>` : ''
            ].filter(Boolean).join('') || '—';
            const conditions = [
                s.leadTime ? `<div>Délai : <strong>${this.esc(s.leadTime)} j</strong></div>` : '<div>Délai : —</div>',
                `<div>Mini : <strong>${this.money(s.minimumOrderAmount)}</strong></div>`,
                `<div>Franco : <strong>${this.money(s.freeShippingThreshold)}</strong></div>`,
                s.paymentTerms ? `<div>${this.esc(s.paymentTerms)}</div>` : '<div>Conditions : —</div>'
            ].join('');
            const contactsDisplay = contactsCount > 0
                ? `<span class="badge">${contactsCount} contact${contactsCount > 1 ? 's' : ''}</span>`
                : '—';

            return `
                <tr>
                    <td>${supplierTitle}</td>
                    <td>${this.statusBadge(s.status)}</td>
                    <td>${primaryContact}</td>
                    <td>${coordinates}</td>
                    <td>${conditions}</td>
                    <td>${brandsDisplay}</td>
                    <td>${contactsDisplay}</td>
                    <td style="display:flex;gap:4px">
                        <button class="btn btn-sm btn-secondary" onclick="SupplierPage.openModal(${s.id})">${Icons.edit}</button>
                        <button class="btn btn-sm btn-danger" onclick="SupplierPage.deleteSupplier(${s.id})">${Icons.trash}</button>
                    </td>
                </tr>
            `;
        }).join('');
    },

    renderContactRow(contact = {}, index = 0) {
        const c = {
            type: contact.type || 'commercial',
            name: contact.name || '',
            role: contact.role || '',
            phone: contact.phone || '',
            email: contact.email || ''
        };
        const typeOptions = [
            ['commercial', 'Commercial'],
            ['sav', 'SAV'],
            ['logistique', 'Logistique'],
            ['facturation', 'Facturation'],
            ['support', 'Support']
        ].map(([val, label]) => `<option value="${val}" ${c.type === val ? 'selected' : ''}>${label}</option>`).join('');

        return `
            <div class="supp-contact-row" data-index="${index}" style="border:1px solid var(--border);border-radius:12px;padding:12px;background:var(--bg-card);margin-bottom:10px">
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px;align-items:end">
                    <div>
                        <label class="lbl">Type</label>
                        <select class="inp supp-contact-type">${typeOptions}</select>
                    </div>
                    <div>
                        <label class="lbl">Nom</label>
                        <input type="text" class="inp supp-contact-name" value="${this.esc(c.name)}" placeholder="Nom du contact">
                    </div>
                    <div>
                        <label class="lbl">Fonction</label>
                        <input type="text" class="inp supp-contact-role" value="${this.esc(c.role)}" placeholder="Commercial secteur, ADV...">
                    </div>
                    <div>
                        <label class="lbl">Téléphone</label>
                        <input type="text" class="inp supp-contact-phone" value="${this.esc(c.phone)}" placeholder="Téléphone">
                    </div>
                    <div>
                        <label class="lbl">Email</label>
                        <input type="email" class="inp supp-contact-email" value="${this.esc(c.email)}" placeholder="contact@fournisseur.fr">
                    </div>
                    <div>
                        <button type="button" class="btn btn-danger supp-contact-remove" style="width:100%">Supprimer</button>
                    </div>
                </div>
            </div>
        `;
    },

    bindContactActions() {
        const addBtn = document.getElementById('suppAddContact');
        const list = document.getElementById('suppContactsList');
        if (!addBtn || !list) return;

        addBtn.onclick = () => {
            list.insertAdjacentHTML('beforeend', this.renderContactRow({}, list.querySelectorAll('.supp-contact-row').length));
            this.bindContactActions();
        };

        list.querySelectorAll('.supp-contact-remove').forEach(btn => {
            btn.onclick = () => {
                btn.closest('.supp-contact-row')?.remove();
            };
        });
    },

    openModal(id) {
        const s = this.normalizeSupplier(id ? this.suppliers.find(x => x.id === id) || {} : {});
        const isEdit = !!id;
        const brandCheckboxes = this.brands.length > 0
            ? this.brands.map(b => {
                const checked = s.linkedBrands.includes(b.id) ? 'checked' : '';
                return `<label class="chk" style="display:block;margin:4px 0"><input type="checkbox" value="${b.id}" ${checked}> ${this.esc(b.name)}</label>`;
            }).join('')
            : '<p style="color:var(--text-muted)">Aucune marque disponible. <a href="?page=brands">Créer des marques</a></p>';
        const contactRows = (s.contacts || []).length
            ? (s.contacts || []).map((c, i) => this.renderContactRow(c, i)).join('')
            : '<div style="color:var(--text-muted);margin-bottom:10px" id="suppNoContacts">Aucun contact ajouté.</div>';

        Modal.show(
            isEdit ? 'Modifier fournisseur' : 'Nouveau fournisseur',
            `
                <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px">
                    <div>
                        <label class="lbl">Nom fournisseur *</label>
                        <input type="text" class="inp" id="smName" value="${this.esc(s.name)}" placeholder="Nom affiché dans l'application">
                    </div>
                    <div>
                        <label class="lbl">Raison sociale</label>
                        <input type="text" class="inp" id="smCompanyName" value="${this.esc(s.companyName)}" placeholder="Nom société / raison sociale">
                    </div>
                    <div>
                        <label class="lbl">Contact principal</label>
                        <input type="text" class="inp" id="smContact" value="${this.esc(s.contact)}" placeholder="Contact principal">
                    </div>
                    <div>
                        <label class="lbl">Statut</label>
                        <select class="inp" id="smStatus">
                            <option value="active" ${s.status === 'active' ? 'selected' : ''}>Actif</option>
                            <option value="watch" ${s.status === 'watch' ? 'selected' : ''}>À surveiller</option>
                            <option value="inactive" ${s.status === 'inactive' ? 'selected' : ''}>Inactif</option>
                            <option value="blocked" ${s.status === 'blocked' ? 'selected' : ''}>Bloqué</option>
                        </select>
                    </div>
                    <div>
                        <label class="lbl">Email</label>
                        <input type="email" class="inp" id="smEmail" value="${this.esc(s.email)}">
                    </div>
                    <div>
                        <label class="lbl">Téléphone</label>
                        <input type="text" class="inp" id="smPhone" value="${this.esc(s.phone)}">
                    </div>
                    <div>
                        <label class="lbl">Site web</label>
                        <input type="text" class="inp" id="smWebsite" value="${this.esc(s.website)}" placeholder="https://...">
                    </div>
                    <div>
                        <label class="lbl">SIRET</label>
                        <input type="text" class="inp" id="smSiret" value="${this.esc(s.siret)}">
                    </div>
                    <div>
                        <label class="lbl">TVA intracom</label>
                        <input type="text" class="inp" id="smVatNumber" value="${this.esc(s.vatNumber)}">
                    </div>
                </div>

                <label class="lbl">Adresse</label>
                <textarea class="inp" id="smAddr" rows="2" placeholder="Adresse complète">${this.esc(s.address)}</textarea>

                <label class="lbl">Marques liées</label>
                <div id="smBrands" style="max-height:200px;overflow-y:auto;border:1px solid var(--border);border-radius:12px;padding:12px;background:var(--bg-card)">${brandCheckboxes}</div>

                <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border)">
                    <h3 style="margin:0 0 12px 0;font-size:1rem">Conditions commerciales</h3>
                    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px">
                        <div>
                            <label class="lbl">Délai moyen (jours)</label>
                            <input type="number" class="inp" id="smLead" min="0" value="${this.esc(s.leadTime)}">
                        </div>
                        <div>
                            <label class="lbl">Minimum de commande (€)</label>
                            <input type="number" class="inp" id="smMinOrder" min="0" step="0.01" value="${this.esc(s.minimumOrderAmount)}">
                        </div>
                        <div>
                            <label class="lbl">Franco de port (€)</label>
                            <input type="number" class="inp" id="smFreeShip" min="0" step="0.01" value="${this.esc(s.freeShippingThreshold)}">
                        </div>
                        <div>
                            <label class="lbl">Conditions de paiement</label>
                            <input type="text" class="inp" id="smPay" value="${this.esc(s.paymentTerms)}" placeholder="Ex : 30 jours fin de mois">
                        </div>
                    </div>
                </div>

                <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border)">
                    <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px">
                        <h3 style="margin:0;font-size:1rem">Contacts fournisseur</h3>
                        <button type="button" class="btn btn-secondary" id="suppAddContact">Ajouter un contact</button>
                    </div>
                    <div id="suppContactsList">${contactRows}</div>
                </div>

                <div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border)">
                    <label class="lbl">Notes internes</label>
                    <textarea class="inp" id="smNotes" rows="4" placeholder="Notes, habitudes, incidents, qualité de service...">${this.esc(s.notes)}</textarea>
                </div>
            `,
            [
                { label: 'Annuler', cls: 'btn-secondary', onclick: () => Modal.close() },
                { label: isEdit ? 'Sauvegarder' : 'Créer', cls: 'btn-primary', onclick: () => this.saveSupplier(id) },
                ...(isEdit ? [{ label: 'Supprimer', cls: 'btn-danger', onclick: () => this.deleteSupplier(id) }] : [])
            ],
            isEdit ? 'info' : 'success'
        );

        this.bindContactActions();
        document.getElementById('smName')?.focus();
    },

    collectContacts() {
        return Array.from(document.querySelectorAll('#suppContactsList .supp-contact-row')).map(row => ({
            type: row.querySelector('.supp-contact-type')?.value || 'commercial',
            name: row.querySelector('.supp-contact-name')?.value?.trim() || '',
            role: row.querySelector('.supp-contact-role')?.value?.trim() || '',
            phone: row.querySelector('.supp-contact-phone')?.value?.trim() || '',
            email: row.querySelector('.supp-contact-email')?.value?.trim() || ''
        })).filter(c => c.name || c.phone || c.email || c.role);
    },

    async saveSupplier(id) {
        const name = document.getElementById('smName')?.value.trim() || '';
        if(!name) {
            toast('Nom obligatoire', 'error');
            return;
        }

        const linkedBrands = Array.from(document.querySelectorAll('#smBrands input[type="checkbox"]:checked')).map(cb => parseInt(cb.value, 10));
        const body = {
            name,
            companyName: document.getElementById('smCompanyName')?.value.trim() || '',
            contact: document.getElementById('smContact')?.value.trim() || '',
            email: document.getElementById('smEmail')?.value.trim() || '',
            phone: document.getElementById('smPhone')?.value.trim() || '',
            website: document.getElementById('smWebsite')?.value.trim() || '',
            address: document.getElementById('smAddr')?.value.trim() || '',
            siret: document.getElementById('smSiret')?.value.trim() || '',
            vatNumber: document.getElementById('smVatNumber')?.value.trim() || '',
            linkedBrands,
            leadTime: parseInt(document.getElementById('smLead')?.value, 10) || 0,
            minimumOrderAmount: parseFloat(document.getElementById('smMinOrder')?.value) || 0,
            freeShippingThreshold: parseFloat(document.getElementById('smFreeShip')?.value) || 0,
            paymentTerms: document.getElementById('smPay')?.value.trim() || '',
            status: document.getElementById('smStatus')?.value || 'active',
            notes: document.getElementById('smNotes')?.value.trim() || '',
            contacts: this.collectContacts()
        };

        try {
            if(id) {
                body.id = parseInt(id, 10);
                await Api.supplierEdit(body);
                toast('Fournisseur mis à jour', 'success');
            } else {
                await Api.supplierAdd(body);
                toast('Fournisseur créé', 'success');
            }
            Modal.close();
            await this.load();
        } catch(e) {
            toast(e.message, 'error');
        }
    },

    async deleteSupplier(id) {
        if(!confirm('Supprimer ce fournisseur ?')) return;
        try {
            await Api.supplierDel(id);
            toast('Fournisseur supprimé', 'success');
            Modal.close();
            await this.load();
        } catch(e) {
            toast(e.message, 'error');
        }
    }
};
