/**
 * Fichier  : assets/js/pages/users.js
 * Version  : 2.3.0
 * Description : JS — Utilisateurs : CRUD, rôles, permissions magasins + permissions fines
 */
const UsrPage = {
    users: [],
    warehouses: [],

    // Toutes les permissions disponibles pour un utilisateur (role=user)
    PERM_DEFS: [
        { key: 'products.read',       label: 'Voir les produits',       group: 'Produits' },
        { key: 'stock.read',          label: 'Voir le stock',           group: 'Produits' },
        { key: 'movements.read',      label: 'Voir les mouvements',     group: 'Mouvements' },
        { key: 'movements.create',    label: 'Créer des mouvements',    group: 'Mouvements' },
        { key: 'movements.delete',    label: 'Supprimer des mouvements',group: 'Mouvements' },
        { key: 'inventory.read',      label: 'Voir les inventaires',    group: 'Inventaire' },
        { key: 'inventory.write',     label: 'Modifier les inventaires',group: 'Inventaire' },
        { key: 'kits.read',           label: 'Voir les kits',           group: 'Fonctions avancées' },
        { key: 'lots.read',           label: 'Voir les lots',           group: 'Fonctions avancées' },
        { key: 'reservations.read',   label: 'Voir les réservations',   group: 'Fonctions avancées' },
        { key: 'analytics.read',      label: 'Voir le pilotage',        group: 'Fonctions avancées' },
        { key: 'product.versions.read',label:'Historique produits',     group: 'Fonctions avancées' },
        { key: 'price.read',          label: 'Voir les prix',           group: 'Prix & Valorisation' },
        { key: 'valuation.read',      label: 'Voir la valorisation',    group: 'Prix & Valorisation' },
        { key: 'locations.manage',    label: 'Gérer les emplacements',  group: 'Administration' },
        { key: 'warehouses.manage',   label: 'Gérer les magasins',      group: 'Administration' },
        { key: 'settings.write',      label: 'Modifier les paramètres', group: 'Administration' },
        { key: 'users.manage',        label: 'Gérer les utilisateurs',  group: 'Administration' },
        { key: 'admin.access',        label: 'Accès zone admin',        group: 'Administration' },
    ],

    async init(){
        this.warehouses = await Api.warehouses();
        document.getElementById('userSearch').addEventListener('input', ()=>this.load());
        document.getElementById('btnNewUser').onclick = ()=>this.openModal();
        await this.load();
    },

    async load(){
        const q = document.getElementById('userSearch').value.toLowerCase();
        const users = await Api.users();
        this.users = users;
        const filtered = q ? users.filter(u=>
            (u.name||'').toLowerCase().includes(q)||(u.username||'').toLowerCase().includes(q)
        ) : users;
        document.getElementById('userCount').textContent = filtered.length + ' utilisateur(s)';
        this.renderTable(filtered);
    },

    renderTable(users){
        const tbody = document.getElementById('userBody');
        if(!users.length){
            tbody.innerHTML='<tr><td colspan="7" class="tbl-empty">Aucun utilisateur</td></tr>';
            return;
        }
        tbody.innerHTML = users.map(u=>{
            const d = u.createdAt ? new Date(u.createdAt).toLocaleDateString('fr-FR',{day:'2-digit',month:'short',year:'numeric'}) : '—';
            let whDisplay = '—';
            if(u.role === 'admin'){
                whDisplay = '<span class="text-muted" style="font-size:11px">Tous (Admin)</span>';
            } else {
                const allowed = u.allowedWarehouses || [];
                if(allowed.length === 0){
                    whDisplay = '<span class="text-muted" style="font-size:11px">Tous</span>';
                } else {
                    const whNames = allowed.map(wid=>{
                        const wh = this.warehouses.find(w=>w.id===wid);
                        return wh ? wh.name : '?';
                    });
                    whDisplay = (whNames.length<=2)
                        ? whNames.map(n=>`<span class="badge badge-muted">${n}</span>`).join(' ')
                        : `<span class="badge badge-muted">${whNames[0]}</span> <span class="badge badge-muted">+${whNames.length-1}</span>`;
                }
            }
            return `<tr>
                <td><strong>${u.name||'—'}</strong></td>
                <td class="col-mono">${u.username||'—'}</td>
                <td><span class="badge ${u.role==='admin'?'badge-blue':'badge-green'}">${u.role==='admin'?'Admin':'Utilisateur'}</span></td>
                <td>${whDisplay}</td>
                <td><span class="badge ${u.active!==false?'badge-green':'badge-red'}">${u.active!==false?'Actif':'Inactif'}</span></td>
                <td>${d}</td>
                <td style="display:flex;gap:4px">
                    <button class="btn btn-sm btn-secondary" onclick="UsrPage.openModal('${u.id}')">Éditer</button>
                    <button class="btn btn-sm btn-danger" onclick="UsrPage.delUser('${u.id}')">Suppr.</button>
                </td>
            </tr>`;
        }).join('');
    },

    async openModal(id){
        const u = id ? (this.users||[]).find(x=>String(x.id)===String(id))||{} : {};
        const isEdit = !!id;
        const isAdmin = (u.role||'user') === 'admin';
        const allowedWarehouses = u.allowedWarehouses || [];

        // Charger les permissions existantes si édition
        let rolePerms = {};
        let userOverrides = {};
        if(isEdit && !isAdmin){
            try {
                const pr = await Api.userPerms(id);
                rolePerms     = pr.rolePerms     || {};
                userOverrides = pr.userOverrides  || {};
            } catch(e){ /* silencieux */ }
        }

        // Warehouse checkboxes
        const whCheckboxes = this.warehouses.map(wh=>{
            const checked = allowedWarehouses.includes(wh.id) ? 'checked' : '';
            return `<label style="display:flex;align-items:center;gap:8px;padding:6px 0;cursor:pointer">
                <input type="checkbox" class="wh-access-cb" value="${wh.id}" ${checked} style="width:16px;height:16px;flex-shrink:0">
                <span style="font-size:13px">${wh.name}</span>
            </label>`;
        }).join('');

        // Permission rows par groupe (seulement pour les users non-admin en édition)
        const permGroupsHtml = isEdit && !isAdmin ? this._buildPermGroups(rolePerms, userOverrides) : '';

        Modal.show(isEdit?'Modifier utilisateur':'Nouvel utilisateur', `
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                <div>
                    <label class="lbl">Nom complet *</label>
                    <input type="text" class="inp" id="umName" value="${u.name||''}">
                </div>
                <div>
                    <label class="lbl">Username *</label>
                    <input type="text" class="inp" id="umUser" value="${u.username||''}" ${isEdit?'disabled':''}>
                </div>
            </div>

            <div style="margin-top:12px">
                <label class="lbl">Mot de passe ${isEdit?'(laisser vide = inchangé)':'*'}</label>
                <input type="password" class="inp" id="umPass" placeholder="Min 8 caractères…">
            </div>

            <div style="margin-top:16px">
                <label class="lbl">Rôle</label>
                <div style="display:flex;gap:8px;margin-top:6px">
                    <button type="button" class="btn btn-sm ${!isAdmin?'btn-primary':'btn-secondary'}" id="umRoleUser" onclick="UsrPage._toggleRole('user')">👤 Utilisateur</button>
                    <button type="button" class="btn btn-sm ${isAdmin?'btn-primary':'btn-secondary'}" id="umRoleAdmin" onclick="UsrPage._toggleRole('admin')">🛡 Admin</button>
                </div>
            </div>

            <div id="umUserSections" style="${isAdmin?'display:none':''}">
                <div style="margin-top:16px">
                    <label class="lbl">Accès aux magasins</label>
                    <p style="font-size:11px;color:var(--text-muted);margin-bottom:8px">
                        Si aucun magasin sélectionné, l'utilisateur aura accès à tous.
                    </p>
                    <div style="max-height:120px;overflow-y:auto;border:1px solid var(--border);border-radius:8px;padding:6px 12px;background:var(--bg-input)">
                        ${whCheckboxes || '<p style="color:var(--text-muted);font-size:12px">Aucun magasin disponible</p>'}
                    </div>
                </div>

                ${permGroupsHtml ? `
                <div style="margin-top:16px">
                    <label class="lbl">Permissions fines</label>
                    <p style="font-size:11px;color:var(--text-muted);margin-bottom:10px">
                        Cochez pour activer. Les cases grisées correspondent aux valeurs par défaut du rôle.
                    </p>
                    <div id="umPermsContainer" style="border:1px solid var(--border);border-radius:8px;background:var(--bg-input);overflow:hidden">
                        ${permGroupsHtml}
                    </div>
                </div>
                ` : ''}
            </div>

            ${isEdit?`
            <div style="margin-top:16px">
                <label class="lbl">Statut</label>
                <div style="display:flex;gap:8px;margin-top:6px">
                    <button type="button" class="btn btn-sm ${u.active!==false?'btn-primary':'btn-secondary'}" id="umActif" onclick="UsrPage._toggleStatus(true)">✓ Actif</button>
                    <button type="button" class="btn btn-sm ${u.active===false?'btn-primary':'btn-secondary'}" id="umInactif" onclick="UsrPage._toggleStatus(false)">✗ Inactif</button>
                </div>
            </div>
            `:''}
        `, [
            {label:'Annuler', cls:'btn-secondary', onclick:()=>Modal.close()},
            {label:isEdit?'Sauvegarder':'Créer', cls:'btn-primary', onclick:()=>UsrPage.saveUser(id)},
            ...(isEdit?[{label:'Supprimer', cls:'btn-danger', onclick:()=>UsrPage.delUser(id)}]:[])
        ], isEdit?'info':'success');
    },

    _buildPermGroups(rolePerms, userOverrides){
        // Regrouper les permissions par groupe
        const groups = {};
        this.PERM_DEFS.forEach(p=>{
            if(!groups[p.group]) groups[p.group] = [];
            groups[p.group].push(p);
        });
        let html = '';
        let first = true;
        for(const [grpName, perms] of Object.entries(groups)){
            if(!first) html += '<div style="border-top:1px solid var(--border)"></div>';
            first = false;
            html += `<div style="padding:10px 14px">
                <div style="font-size:10px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;color:var(--text-muted);margin-bottom:8px">${grpName}</div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:4px">`;
            perms.forEach(p=>{
                // valeur effective : override prioritaire, sinon role
                const effective = userOverrides.hasOwnProperty(p.key) ? userOverrides[p.key] : (rolePerms[p.key] ?? false);
                const hasOverride = userOverrides.hasOwnProperty(p.key);
                const checked = effective ? 'checked' : '';
                const dimStyle = !hasOverride ? 'opacity:0.6' : '';
                html += `<label style="display:flex;align-items:center;gap:6px;padding:4px 0;cursor:pointer;${dimStyle}">
                    <input type="checkbox" class="perm-cb" data-perm="${p.key}" ${checked} style="width:14px;height:14px;flex-shrink:0">
                    <span style="font-size:12px;color:var(--text-primary)">${p.label}</span>
                </label>`;
            });
            html += `</div></div>`;
        }
        return html;
    },

    _toggleRole(role){
        const btnUser   = document.getElementById('umRoleUser');
        const btnAdmin  = document.getElementById('umRoleAdmin');
        const sections  = document.getElementById('umUserSections');
        if(role === 'admin'){
            btnAdmin.classList.add('btn-primary');    btnAdmin.classList.remove('btn-secondary');
            btnUser.classList.remove('btn-primary');  btnUser.classList.add('btn-secondary');
            sections.style.display = 'none';
        } else {
            btnUser.classList.add('btn-primary');     btnUser.classList.remove('btn-secondary');
            btnAdmin.classList.remove('btn-primary'); btnAdmin.classList.add('btn-secondary');
            sections.style.display = '';
        }
    },

    _toggleStatus(active){
        const btnActif  = document.getElementById('umActif');
        const btnInactif= document.getElementById('umInactif');
        if(active){
            btnActif.classList.add('btn-primary');   btnActif.classList.remove('btn-secondary');
            btnInactif.classList.remove('btn-primary'); btnInactif.classList.add('btn-secondary');
        } else {
            btnInactif.classList.add('btn-primary'); btnInactif.classList.remove('btn-secondary');
            btnActif.classList.remove('btn-primary');    btnActif.classList.add('btn-secondary');
        }
    },

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

        const role = document.getElementById('umRoleAdmin').classList.contains('btn-primary') ? 'admin' : 'user';
        const pass = document.getElementById('umPass').value;

        if(!id && !pass){ toast('Mot de passe obligatoire pour un nouvel utilisateur','error'); return; }

        const whCbs = document.querySelectorAll('.wh-access-cb:checked');
        const allowedWarehouses = Array.from(whCbs).map(cb=>parseInt(cb.value));

        const body = { name, role, allowedWarehouses };
        if(!id) body.username = document.getElementById('umUser').value.trim();
        if(pass) body.password = pass;
        if(id){
            body.id = parseInt(id);
            const actBtn = document.getElementById('umActif');
            if(actBtn) body.active = actBtn.classList.contains('btn-primary');
        }

        try {
            let savedUser;
            if(id) savedUser = await Api.userEdit(body);
            else   savedUser = await Api.userAdd(body);

            // Sauvegarder permissions fines si présentes
            if(role !== 'admin'){
                const permCbs = document.querySelectorAll('.perm-cb');
                if(permCbs.length > 0){
                    const permissions = {};
                    permCbs.forEach(cb=>{ permissions[cb.dataset.perm] = cb.checked; });
                    const userId = id || (savedUser?.id);
                    if(userId) await Api.userPermsEdit({ userId: String(userId), permissions });
                }
            }

            toast(id?'Utilisateur mis à jour':'Utilisateur créé', 'success');
            Modal.close();
            this.load();
        } catch(e){
            toast(e.message || 'Erreur', 'error');
        }
    },

    async delUser(id){
        if(!confirm('Supprimer cet utilisateur ?')) return;
        try {
            await Api.userDel(id);
            toast('Utilisateur supprimé','success');
            Modal.close();
            this.load();
        } catch(e){
            toast(e.message||'Erreur','error');
        }
    }
};
