/**
 * WorkflowTemplatesSection.js — مدیریت قالب‌های workflow
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WorkflowTemplatesSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🎨 قالب‌های Workflow</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._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._toast("⚠️ ساخت قالب جدید فعلاً در دست توسعه است", "#f59e0b"));
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/wf/templates");
            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(320px,1fr));gap:14px;">
            ${this._rows.map(t => `
            <div style="border:1.5px solid ${t.color};border-radius:10px;padding:14px;background:#fff;">
                <div style="display:flex;justify-content:space-between;align-items:start;">
                    <div>
                        <div style="font-size:28px;">${t.icon}</div>
                        <div style="font-weight:700;font-size:15px;color:${t.color};margin-top:4px;">${this.escape(t.name)}</div>
                        <small style="color:#94a3b8;font-family:monospace;">${this.escape(t.code)}</small>
                        ${t.is_system == 1 ? '<span style="background:#dbeafe;color:#1e40af;padding:1px 6px;border-radius:4px;font-size:10px;margin-right:6px;">سیستمی</span>' : ''}
                    </div>
                </div>
                ${t.description ? `<div style="font-size:12px;color:#64748b;margin-top:8px;">${this.escape(t.description)}</div>` : ''}
                <div style="display:flex;gap:8px;margin-top:12px;font-size:12px;">
                    <span>📋 <b>${t.stage_count}</b> مرحله</span>
                    <span>✅ <b>${t.instance_count}</b> پروژه</span>
                </div>
                <div style="display:flex;gap:6px;margin-top:10px;">
                    <button class="acc-btn acc-btn--xs acc-btn--primary" data-view="${t.id}">👁️ نمایش جزئیات</button>
                </div>
            </div>`).join("")}
        </div>`;

        this.ref("wrap").querySelectorAll("[data-view]").forEach(b =>
            b.addEventListener("click", () => this._viewTemplate(parseInt(b.dataset.view)))
        );
    }

    async _viewTemplate(id) {
        try {
            const res = await this.api.get(`/wf/templates/${id}`);
            const tpl = res?.data;
            if (!tpl) return;

            const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
            ov.innerHTML = `
            <div class="acc-modal" style="max-width:760px;max-height:90vh;overflow-y:auto;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${tpl.icon} ${this.escape(tpl.name)}</div>
                <div style="font-size:12px;color:#64748b;margin-bottom:14px;">${this.escape(tpl.description ?? '')}</div>

                ${(tpl.stages ?? []).map((s, idx) => `
                <div style="border-right:3px solid ${s.color};padding:10px 14px;background:#f8fafc;border-radius:6px;margin-bottom:8px;">
                    <div style="font-weight:700;font-size:14px;color:${s.color};">
                        ${s.icon} ${idx+1}. ${this.escape(s.name)}
                        <small style="color:#94a3b8;margin-right:8px;">${s.estimated_days} روز | ${s.budget_pct}% بودجه</small>
                    </div>
                    ${s.tasks?.length ? `
                    <div style="margin-top:8px;">
                        <b style="font-size:12px;color:#475569;">Tasks:</b>
                        <ul style="font-size:12px;color:#64748b;margin:4px 0 0 0;padding-right:20px;">
                            ${s.tasks.map(t => `<li>${this.escape(t.title)}</li>`).join("")}
                        </ul>
                    </div>` : ''}
                    ${s.gates?.length ? `
                    <div style="margin-top:8px;">
                        <b style="font-size:12px;color:#475569;">🚦 Gates:</b>
                        <ul style="font-size:12px;color:#eab308;margin:4px 0 0 0;padding-right:20px;">
                            ${s.gates.map(g => `<li>${this.escape(g.title)}</li>`).join("")}
                        </ul>
                    </div>` : ''}
                </div>
                `).join("")}

                <div class="acc-modal__actions">
                    <button class="acc-btn acc-btn--secondary" data-action="close">بستن</button>
                </div>
            </div>`;
            document.body.appendChild(ov);
            const close = () => ov.remove();
            ov.querySelector(".acc-modal__close").addEventListener("click", close);
            ov.querySelector("[data-action=close]").addEventListener("click", close);
            ov.addEventListener("click", e => { if (e.target === ov) close(); });
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

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