/**
 * AclRolesSection.js — نقش‌ها + ویرایش مجوزها
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class AclRolesSection extends SectionBase {

    constructor(p) { super(p); this._perms = []; this._permsGrouped = {}; }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🎭 نقش‌ها</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--primary" data-ref="addBtn">➕ نقش جدید</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._loadPerms();
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
    }

    async _loadPerms() {
        try {
            const r = await this.api.get("/acl/permissions");
            this._perms        = r?.data    ?? [];
            this._permsGrouped = r?.grouped ?? {};
        } catch {}
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res  = await this.api.get("/acl/roles");
            this._rows = res?.data ?? [];
            this._render();
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render() {
        if (!this._rows.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">نقشی یافت نشد</div>`;
            return;
        }
        this.ref("wrap").innerHTML = `
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;padding:4px;">
            ${this._rows.map(r => `
            <div style="border:1px solid #e2e8f0;border-radius:10px;padding:14px;background:#fff;">
                <div style="display:flex;justify-content:space-between;align-items:start;">
                    <div>
                        <div style="font-weight:700;font-size:14px;">🎭 ${this.escape(r.name)}</div>
                        <small style="color:#94a3b8;font-family:monospace;">${this.escape(r.slug)}</small>
                        ${r.is_system == 1 ? '<span style="background:#dbeafe;color:#1e40af;padding:1px 6px;border-radius:4px;font-size:10px;margin-right:6px;">سیستمی</span>' : ''}
                    </div>
                </div>
                ${r.description ? `<div style="font-size:12px;color:#475569;margin-top:6px;">${this.escape(r.description)}</div>` : ""}
                <div style="display:flex;gap:8px;margin-top:10px;font-size:12px;">
                    <span><b>${r.perm_count}</b> مجوز</span>
                    <span><b>${r.user_count}</b> کاربر</span>
                </div>
                <div style="display:flex;gap:6px;margin-top:10px;">
                    <button class="acc-btn acc-btn--xs acc-btn--primary" data-perms="${r.id}">🔑 ویرایش مجوزها</button>
                    ${r.is_system != 1 ? `
                    <button class="acc-btn acc-btn--xs" data-edit="${r.id}">✏️</button>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${r.id}">🗑️</button>
                    ` : ''}
                </div>
            </div>`).join("")}
        </div>`;

        this.ref("wrap").querySelectorAll("[data-perms]").forEach(btn =>
            btn.addEventListener("click", () => this._openPermsModal(parseInt(btn.dataset.perms),
                this._rows.find(r => r.id == btn.dataset.perms)))
        );
        this.ref("wrap").querySelectorAll("[data-edit]").forEach(btn =>
            btn.addEventListener("click", () =>
                this._openModal(this._rows.find(r => r.id == btn.dataset.edit)))
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(btn =>
            btn.addEventListener("click", async () => {
                if (!confirm("حذف این نقش؟")) return;
                try { await this.api.delete(`/acl/roles/${btn.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _openModal(role = null) {
        const isEdit = !!role;
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${isEdit ? '✏️ ویرایش' : '➕ نقش جدید'}</div>
            <form>
                ${!isEdit ? `<div class="acc-form-group"><label>شناسه یکتا (slug) *</label>
                    <input name="slug" required placeholder="مثلاً sales_manager">
                </div>` : ''}
                <div class="acc-form-group"><label>نام نمایشی *</label>
                    <input name="name" required value="${this.escape(role?.name ?? '')}">
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="description" rows="2">${this.escape(role?.description ?? '')}</textarea>
                </div>
                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">ذخیره</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            try {
                if (isEdit) await this.api.put(`/acl/roles/${role.id}`, body);
                else        await this.api.post("/acl/roles", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    async _openPermsModal(roleId, role) {
        // مجوزهای فعلی نقش
        let current = [];
        try {
            const res = await this.api.get(`/acl/roles/${roleId}/permissions`);
            current = res?.data ?? [];
        } catch {}

        const groups = Object.entries(this._permsGrouped);
        const moduleLabels = {
            gis:'GIS', inv:'انبار', sales:'فروش', purchase:'خرید', cpm:'پروژه',
            acc:'حسابداری', payroll:'حقوق', treasury:'خزانه', crm:'CRM', system:'سیستم',
        };

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:700px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🔑 مجوزهای نقش «${this.escape(role?.name ?? '')}»</div>

            <div style="display:flex;gap:6px;margin-bottom:12px;">
                <button class="acc-btn acc-btn--xs" id="acl-select-all">انتخاب همه</button>
                <button class="acc-btn acc-btn--xs" id="acl-deselect-all">حذف همه</button>
            </div>

            <form id="acl-perms-form">
                ${groups.map(([mod, perms]) => `
                <div style="margin-bottom:16px;padding:10px;background:#f8fafc;border-radius:8px;">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                        <b style="font-size:13px;color:#1e40af;">📦 ${this.escape(moduleLabels[mod] ?? mod)}</b>
                        <button type="button" class="acc-btn acc-btn--xs" data-group="${mod}">✅ همه</button>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:4px;">
                        ${perms.map(p => `
                        <label style="display:flex;gap:6px;align-items:center;font-size:12px;padding:4px;cursor:pointer;">
                            <input type="checkbox" name="permissions" value="${this.escape(p.permission_key)}"
                                   ${current.includes(p.permission_key) ? 'checked' : ''}>
                            ${this.escape(p.label)} <small style="color:#94a3b8;font-family:monospace;">${this.escape(p.permission_key)}</small>
                        </label>`).join("")}
                    </div>
                </div>
                `).join("")}

                <div class="acc-modal__actions" style="position:sticky;bottom:0;background:#fff;padding:10px 0;">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">💾 ذخیره مجوزها</button>
                </div>
            </form>
        </div>`;

        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });

        // انتخاب همه / حذف همه
        ov.querySelector("#acl-select-all").addEventListener("click", () =>
            ov.querySelectorAll('input[type=checkbox]').forEach(c => c.checked = true));
        ov.querySelector("#acl-deselect-all").addEventListener("click", () =>
            ov.querySelectorAll('input[type=checkbox]').forEach(c => c.checked = false));

        // انتخاب کل یک گروه
        ov.querySelectorAll("[data-group]").forEach(btn =>
            btn.addEventListener("click", () => {
                const mod = btn.dataset.group;
                const inputs = btn.closest("[style*='background:#f8fafc']").querySelectorAll("input[type=checkbox]");
                const allChecked = [...inputs].every(i => i.checked);
                inputs.forEach(i => i.checked = !allChecked);
            }));

        ov.querySelector("#acl-perms-form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const perms = [...ev.target.querySelectorAll('input[name=permissions]:checked')].map(i => i.value);
            try {
                await this.api.put(`/acl/roles/${roleId}/permissions`, { permissions: perms });
                close(); this._toast(`✅ ${perms.length} مجوز ذخیره شد`);
                this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    _toast(msg, bg = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${bg};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;`;
        t.textContent = msg; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
