/**
 * AclPermissionsSection.js — لیست همه مجوزها (read-only)
 */
import SectionBase from "../../accounting/SectionBase.js";

const MODULE_LABELS = {
    gis:'🗺️ GIS', inv:'🏭 انبار', sales:'🧾 فروش', purchase:'🛒 خرید',
    cpm:'📊 پروژه', acc:'📦 حسابداری', payroll:'👨‍💼 حقوق', treasury:'💰 خزانه',
    crm:'🎯 CRM', system:'⚙️ سیستم',
};

export default class AclPermissionsSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🔑 مجوزها</h2>
                <div style="display:flex;gap:8px;">
                    <input type="text" data-ref="search" placeholder="جستجو..." class="acc-input" style="width:220px;">
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div style="background:#eff6ff;padding:10px 14px;border-radius:8px;margin-bottom:12px;font-size:12px;color:#1e40af;">
                💡 مجوزها به‌صورت خودکار از ماژول‌ها ساخته می‌شوند. الگو: <code>ماژول.منبع.عمل</code>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("search"),     "input", () => this._filter());
    }

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

    _filter() {
        const q = (this.ref("search")?.value ?? "").toLowerCase();
        if (!q) { this._render(this._grouped); return; }
        const filtered = {};
        for (const [mod, perms] of Object.entries(this._grouped)) {
            const matches = perms.filter(p =>
                p.permission_key.toLowerCase().includes(q) ||
                (p.label ?? "").toLowerCase().includes(q)
            );
            if (matches.length) filtered[mod] = matches;
        }
        this._render(filtered);
    }

    _render(grouped) {
        const entries = Object.entries(grouped);
        if (!entries.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">مجوزی یافت نشد</div>`;
            return;
        }
        this.ref("wrap").innerHTML = entries.map(([mod, perms]) => `
        <div style="margin-bottom:16px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;">
            <div style="background:#f1f5f9;padding:10px 14px;font-weight:700;font-size:13px;">
                ${this.escape(MODULE_LABELS[mod] ?? mod)}
                <small style="color:#94a3b8;font-weight:400;">(${perms.length} مجوز)</small>
            </div>
            <table class="acc-table" style="margin:0;">
                <thead><tr><th>کلید</th><th>توضیح</th><th>عمل</th></tr></thead>
                <tbody>
                ${perms.map(p => `<tr>
                    <td style="font-family:monospace;font-size:12px;color:#1d4ed8;">${this.escape(p.permission_key)}</td>
                    <td>${this.escape(p.label ?? '—')}</td>
                    <td><small style="background:#f1f5f9;padding:2px 6px;border-radius:4px;">${this.escape(p.action)}</small></td>
                </tr>`).join("")}
                </tbody>
            </table>
        </div>
        `).join("");
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
