/**
 * WfHistorySection.js — تاریخچه Workflow پروژه‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WfHistorySection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap" dir="rtl">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📜 تاریخچه Workflow</h2>
            </div>
            <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px;flex-wrap:wrap;">
                <label style="font-size:13px;color:#475569;display:flex;align-items:center;gap:8px;">
                    انتخاب پروژه:
                    <select class="acc-select" data-ref="projSel"></select>
                </label>
                <button class="acc-btn acc-btn--primary" data-ref="loadBtn">نمایش تاریخچه</button>
            </div>
            <div data-ref="table"></div>
        </div>`;
    }

    async afterRender() {
        await this._loadProjects();
        this.on(this.ref("loadBtn"), "click", () => this._loadHistory());
    }

    async _loadProjects() {
        try {
            const projRes = await this.api.get("pc/projects");
            const projects = projRes?.data ?? projRes ?? [];
            const instances = await Promise.all(
                projects.map(p => this.api.get(`wf/instances/project/${p.id}`).catch(() => ({ data: null })))
            );
            const withWf = projects.filter((p, i) => instances[i]?.data);
            const sel = this.ref("projSel");
            if (!withWf.length) {
                sel.innerHTML = `<option>هیچ پروژه‌ای با Workflow وجود ندارد</option>`;
                return;
            }
            sel.innerHTML = withWf.map((p, i) => {
                const inst = instances[projects.indexOf(p)]?.data;
                return `<option value="${inst.id}">${this.escape(p.name || p.title || `#${p.id}`)}</option>`;
            }).join("");
            await this._loadHistory();
        } catch {}
    }

    async _loadHistory() {
        const sel = this.ref("projSel");
        const instanceId = sel?.value;
        if (!instanceId) return;
        const table = this.ref("table");
        table.innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get(`wf/instances/${instanceId}/transitions`);
            const rows = res?.data ?? [];
            if (!rows.length) {
                table.innerHTML = `<div class="acc-empty">تاریخچه‌ای ثبت نشده</div>`;
                return;
            }
            table.innerHTML = `
            <div style="overflow-x:auto;">
                <table class="acc-table">
                    <thead><tr><th>زمان</th><th>عملیات</th><th>از مرحله</th><th>به مرحله</th><th>توسط</th><th>یادداشت</th></tr></thead>
                    <tbody>
                    ${rows.map(r => `
                    <tr>
                        <td style="white-space:nowrap;font-size:11px;">${this.escape(r.created_at || '')}</td>
                        <td><span style="background:${this._actionColor(r.action)};padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700;">${this.escape(r.action)}</span></td>
                        <td>${this.escape(r.from_stage_name || '-')}</td>
                        <td>${this.escape(r.to_stage_name || '-')}</td>
                        <td>${this.escape(r.actor_name || '-')}</td>
                        <td>${this.escape(r.notes || '')}</td>
                    </tr>`).join("")}
                    </tbody>
                </table>
            </div>`;
        } catch (e) {
            table.innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _actionColor(a) {
        return { create:'#dbeafe', start_stage:'#ede9fe', advance:'#d1fae5', complete:'#fef3c7' }[a] ?? '#f1f5f9';
    }

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