/**
 * HrDepartmentsSection.js — بخش‌ها (ساختار درختی)
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class HrDepartmentsSection 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;">
                    <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._openModal());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/hr/departments");
            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; }
        const renderNode = (parent, level = 0) => this._rows.filter(d => d.parent_id == parent).map(d => `
            <div style="margin-right:${level * 20}px;padding:8px 12px;border:1px solid #e2e8f0;border-radius:8px;margin-bottom:6px;background:#fff;">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <div>
                        <b>🏢 ${this.escape(d.name)}</b>
                        <small style="color:#94a3b8;margin-right:6px;">${this.escape(d.code || '')}</small>
                        ${d.manager_first ? `<small style="color:#3b82f6;margin-right:8px;">👤 ${this.escape(d.manager_first)} ${this.escape(d.manager_last)}</small>` : ''}
                    </div>
                    <div style="display:flex;gap:4px;">
                        <span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${d.emp_count} کارمند</span>
                        <button class="acc-btn acc-btn--xs" data-edit="${d.id}">✏️</button>
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${d.id}">🗑️</button>
                    </div>
                </div>
            </div>
            ${renderNode(d.id, level + 1)}
        `).join("");

        this.ref("wrap").innerHTML = renderNode(0);

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

    _openModal(d = null) {
        const isEdit = !!d;
        const parentOpts = `<option value="0">سطح اول</option>` + this._rows.map(p =>
            `<option value="${p.id}" ${d?.parent_id == p.id ? 'selected' : ''}>${this.escape(p.name)}</option>`).join("");

        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>
                <div class="acc-form-group"><label>بخش والد</label>
                    <select name="parent_id">${parentOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد</label><input name="code" value="${this.escape(d?.code ?? '')}"></div>
                    <div class="acc-form-group"><label>نام *</label><input name="name" required value="${this.escape(d?.name ?? '')}"></div>
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="description" rows="2">${this.escape(d?.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(`/hr/departments/${d.id}`, body);
                else        await this.api.post("/hr/departments", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

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