/**
 * PermitListSection.js — لیست پروانه‌ها + پانل جزئیات
 */
import SectionBase from "../../accounting/SectionBase.js";

const TYPE_LABEL  = { build:'پروانه ساخت', renovation:'بازسازی', demolish:'تخریب', use_change:'تغییر کاربری', completion:'پایان کار' };
const TYPE_COLOR  = { build:'#3b82f6', renovation:'#8b5cf6', demolish:'#ef4444', use_change:'#f59e0b', completion:'#10b981' };
const TYPE_ICON   = { build:'🏗️', renovation:'🔨', demolish:'💥', use_change:'🔄', completion:'✅' };
const STATUS_LABEL= { draft:'پیش‌نویس', submitted:'ارسال‌شده', under_review:'در بررسی', approved:'تأیید شده', active:'فعال', completed:'پایان کار', rejected:'رد شده', expired:'منقضی' };
const STATUS_COLOR= { draft:'#94a3b8', submitted:'#3b82f6', under_review:'#f59e0b', approved:'#8b5cf6', active:'#10b981', completed:'#059669', rejected:'#ef4444', expired:'#dc2626' };
const FEE_CAT_LABEL = { permit_fee:'عوارض پروانه', levy:'عوارض نوسازی', fine:'جریمه', inspection:'هزینه بازدید', notary:'دفترخانه', other:'سایر' };

const STEPS = [
    { key:'document_prep',   label:'مدارک',    icon:'📄' },
    { key:'submit',          label:'ارائه',     icon:'📮' },
    { key:'municipality',    label:'بررسی',     icon:'🏛️' },
    { key:'fee_calc',        label:'محاسبه',   icon:'🧮' },
    { key:'fee_payment',     label:'پرداخت',   icon:'💳' },
    { key:'permit_issued',   label:'پروانه',    icon:'📋' },
    { key:'foundation',      label:'فونداسیون', icon:'🔍' },
    { key:'structure',       label:'اسکلت',     icon:'🏗️' },
    { key:'final_inspect',   label:'نهایی',    icon:'✅' },
    { key:'completion_cert', label:'پایان‌کار', icon:'🏆' },
    { key:'title_deed',      label:'سند',       icon:'📜' },
];

export default class PermitListSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._permits   = [];
        this._selected  = null;
        this._panelOpen = false;
        this._filter    = { status:'', type:'' };
        this._projects  = [];
        this._parcels   = [];
        this._activeTab = 'details';
    }

    async template() { return `<div data-ref="root"></div>`; }

    async afterRender() {
        try {
            const [pr, pj] = await Promise.all([
                this.api.get('/gis/districts').catch(()=>null),
                this.api.get('/pc/projects',{per_page:200}).catch(()=>null),
            ]);
            this._parcels  = pr?.data??[];
            this._projects = pj?.data??[];
        } catch {}
        await this._render();
    }

    async _render() {
        const root = this.ref('root');
        root.innerHTML = `
        <div class="permit-wrap" data-ref="wrap">
            <!-- لیست -->
            <div class="permit-list-pane" data-ref="listPane">
                <div class="permit-toolbar">
                    <select class="event-type-filter" data-ref="typeSel">
                        <option value="">همه انواع</option>
                        ${Object.entries(TYPE_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
                    </select>
                    <select class="event-type-filter" data-ref="statusSel">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
                    </select>
                    <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">➕ پروانه جدید</button>
                </div>
                <div data-ref="listBody" class="permit-list"></div>
            </div>
            <!-- پانل جزئیات -->
            <div class="permit-detail-pane" data-ref="detailPane">
                <div class="permit-detail-inner" data-ref="detailInner"></div>
            </div>
        </div>`;
        root.querySelectorAll('[data-ref]').forEach(el=>{ this.refs[el.dataset.ref]=el; });
        this.on(this.ref('typeSel'),  'change',()=>{ this._filter.type=this.ref('typeSel').value;     this._load(); });
        this.on(this.ref('statusSel'),'change',()=>{ this._filter.status=this.ref('statusSel').value; this._load(); });
        this.on(this.ref('addBtn'),   'click', ()=>this._openPermitModal());
        await this._load();
    }

    async _load() {
        const body = this.ref('listBody');
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        const params = {};
        if (this._filter.type)   params.type   = this._filter.type;
        if (this._filter.status) params.status  = this._filter.status;
        try {
            const res = await this.api.get('/permits', params);
            this._permits = res?.data??[];
            this._renderList();
        } catch {
            body.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderList() {
        const body = this.ref('listBody');
        if (!this._permits.length) {
            body.innerHTML = `<div class="acc-empty">پروانه‌ای ثبت نشده.</div>`;
            return;
        }
        body.innerHTML = '';
        this._permits.forEach(pm => {
            const sColor = STATUS_COLOR[pm.status]||'#94a3b8';
            const tColor = TYPE_COLOR[pm.type]||'#94a3b8';
            const daysLeft= parseInt(pm.days_to_expiry);
            const expAlert= pm.expiry_date && daysLeft < 30 && daysLeft >= 0;
            const expired = pm.expiry_date && daysLeft < 0;

            const card = document.createElement('div');
            card.className = `permit-card${this._selected?.id==pm.id?' permit-card--active':''}`;
            card.innerHTML = `
            <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:8px;">
                <span class="permit-type-badge" style="background:${tColor};">
                    ${TYPE_ICON[pm.type]||''} ${TYPE_LABEL[pm.type]||pm.type}
                </span>
                <span class="permit-status-badge" style="background:${sColor};">
                    ${STATUS_LABEL[pm.status]||pm.status}
                </span>
            </div>
            <div class="permit-card-title">
                ${pm.permit_number ? `📋 ${this.escape(pm.permit_number)}` : '(شماره پروانه ثبت نشده)'}
            </div>
            ${pm.project_name ? `<div class="permit-card-meta">🏗️ ${this.escape(pm.project_name)}</div>` : ''}
            ${pm.parcel_code  ? `<div class="permit-card-meta">📍 پلاک ${this.escape(pm.parcel_code)}</div>` : ''}
            ${pm.allowed_floors ? `<div class="permit-card-meta">🏢 ${pm.allowed_floors} طبقه | ${pm.allowed_area_sqm||'—'} م²</div>` : ''}
            <!-- پیشرفت -->
            <div class="permit-progress-wrap">
                <div class="treasury-bar-track" style="height:4px;">
                    <div class="treasury-bar-fill" style="width:${Math.round((pm.done_steps/11)*100)}%;background:${sColor};"></div>
                </div>
                <span style="font-size:10px;color:#94a3b8;">${pm.done_steps||0}/11 مرحله</span>
            </div>
            ${expAlert ? `<div style="font-size:11px;color:#f59e0b;margin-top:4px;">⚠️ ${daysLeft} روز تا انقضا</div>` : ''}
            ${expired  ? `<div style="font-size:11px;color:#ef4444;margin-top:4px;">❌ پروانه منقضی شده</div>` : ''}
            ${pm.pending_fees>0 ? `<div style="font-size:11px;color:#ef4444;">💳 ${pm.pending_fees} عوارض معوق</div>` : ''}`;
            card.addEventListener('click', ()=>this._openDetail(pm));
            body.appendChild(card);
        });
    }

    /* ── پانل جزئیات ─────────────────────────────────────────── */
    async _openDetail(pmSummary) {
        this._selected = pmSummary;
        this._renderList();
        const pane  = this.ref('detailPane');
        const inner = this.ref('detailInner');
        if (!this._panelOpen) {
            pane.classList.add('permit-detail-pane--open');
            this._panelOpen = true;
        }
        inner.innerHTML = `<div class="acc-loading" style="padding:40px;text-align:center;"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get(`/permits/${pmSummary.id}`);
            const pm  = res?.data;
            if (!pm) return;
            this._selected = pm;
            this._renderDetail(pm);
        } catch {
            inner.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderDetail(pm) {
        const inner  = this.ref('detailInner');
        const fmt    = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const tColor = TYPE_COLOR[pm.type]||'#94a3b8';
        const sColor = STATUS_COLOR[pm.status]||'#94a3b8';
        const fs     = pm.fee_summary||{};

        inner.innerHTML = `
        <!-- هدر -->
        <div class="permit-detail-header">
            <div style="flex:1;">
                <div style="font-size:16px;font-weight:800;color:#1e293b;margin-bottom:6px;">
                    ${TYPE_ICON[pm.type]||''} ${TYPE_LABEL[pm.type]||pm.type}
                    ${pm.permit_number?`<span style="font-size:12px;color:#64748b;margin-right:8px;">№ ${this.escape(pm.permit_number)}</span>`:''}
                </div>
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <span style="background:${sColor};color:#fff;padding:3px 10px;border-radius:8px;font-size:11px;font-weight:700;">${STATUS_LABEL[pm.status]||pm.status}</span>
                    ${pm.project_name?`<span style="font-size:11px;color:#64748b;">🏗️ ${this.escape(pm.project_name)}</span>`:''}
                    ${pm.days_to_expiry!==null&&pm.days_to_expiry<30?`<span style="font-size:11px;color:#f59e0b;">⚠️ ${pm.days_to_expiry} روز تا انقضا</span>`:''}
                </div>
            </div>
            <button class="gis-panel-close" data-ref="closeBtn">✕</button>
        </div>

        <!-- نوار پیشرفت مراحل -->
        <div class="permit-stepper" data-ref="stepperEl">
            ${this._renderStepper(pm.steps)}
        </div>
        <div style="text-align:center;font-size:11px;color:#94a3b8;margin-bottom:12px;">
            ${pm.done_steps} از ${pm.total_steps} مرحله تکمیل‌شده — ${pm.progress_pct}٪
        </div>

        <!-- خلاصه عوارض -->
        ${fs.total>0?`
        <div style="background:#f8fafc;border-radius:8px;padding:10px 14px;margin-bottom:12px;font-size:12px;">
            <div style="display:flex;justify-content:space-between;">
                <span>کل عوارض: <b>${fmt(fs.total)} ریال</b></span>
                <span>پرداخت‌شده: <b style="color:#10b981;">${fmt(fs.paid)} ریال</b></span>
                <span>مانده: <b style="color:#ef4444;">${fmt(fs.remaining)} ریال</b></span>
            </div>
            <div class="treasury-bar-track" style="margin-top:6px;">
                <div class="treasury-bar-fill" style="width:${fs.total>0?Math.round(fs.paid/fs.total*100):0}%;background:#10b981;"></div>
            </div>
        </div>`:''}

        <!-- تب‌ها -->
        <div class="gis-panel-tabs" data-ref="detailTabs">
            <button class="gis-panel-tab ${this._activeTab==='details'?'gis-panel-tab--active':''}" data-tab="details">📋 جزئیات</button>
            <button class="gis-panel-tab ${this._activeTab==='steps'?'gis-panel-tab--active':''}" data-tab="steps">🔢 مراحل (${pm.done_steps}/${pm.total_steps})</button>
            <button class="gis-panel-tab ${this._activeTab==='fees'?'gis-panel-tab--active':''}" data-tab="fees">💳 عوارض (${(pm.fees||[]).length})</button>
        </div>
        <div class="permit-tab-body" data-ref="detailTabBody">
            ${this._renderTabContent(this._activeTab, pm)}
        </div>

        <!-- اکشن‌ها -->
        <div class="gis-panel-actions">
            <button class="gis-btn gis-btn--primary" data-ref="editBtn">✏️ ویرایش</button>
            <button class="gis-btn gis-btn--danger"  data-ref="delBtn">🗑️ حذف</button>
        </div>`;

        inner.querySelectorAll('[data-ref]').forEach(el=>{ this.refs[el.dataset.ref]=el; });

        // بستن
        this.on(this.ref('closeBtn'),'click',()=>{
            this.ref('detailPane').classList.remove('permit-detail-pane--open');
            this._panelOpen=false; this._selected=null; this._renderList();
        });

        // تب‌ها
        inner.querySelectorAll('.gis-panel-tab').forEach(btn=>{
            btn.addEventListener('click',()=>{
                inner.querySelectorAll('.gis-panel-tab').forEach(b=>b.classList.remove('gis-panel-tab--active'));
                btn.classList.add('gis-panel-tab--active');
                this._activeTab = btn.dataset.tab;
                this.ref('detailTabBody').innerHTML = this._renderTabContent(btn.dataset.tab,pm);
                this._bindTabActions(btn.dataset.tab,pm);
            });
        });

        this.on(this.ref('editBtn'),'click',()=>this._openPermitModal(pm));
        this.on(this.ref('delBtn'),'click',async()=>{
            if (!confirm('حذف این پروانه؟')) return;
            await this.api.delete(`/permits/${pm.id}`);
            this._toast('🗑️ حذف شد');
            this.ref('detailPane').classList.remove('permit-detail-pane--open');
            this._panelOpen=false; this._selected=null;
            this._load();
        });

        this._bindTabActions(this._activeTab, pm);
    }

    _renderStepper(steps=[]) {
        return `<div class="permit-stepper-track">` +
            steps.map((s,i) => {
                const isDone   = s.status==='done';
                const isFailed = s.status==='failed';
                const color    = isDone?'#10b981':isFailed?'#ef4444':'#e2e8f0';
                const textColor= isDone||isFailed?'#fff':'#94a3b8';
                return `
                <div class="permit-step-item" data-step="${s.key}" title="${s.label}${s.done_date?' — '+s.done_date:''}">
                    <div class="permit-step-circle" style="background:${color};color:${textColor};">
                        ${isDone?'✓':isFailed?'✗':s.icon}
                    </div>
                    <div class="permit-step-label" style="color:${isDone?'#10b981':isFailed?'#ef4444':'#94a3b8'};">${s.label}</div>
                    ${i<steps.length-1?'<div class="permit-step-line" style="background:'+(isDone?'#10b981':'#e2e8f0')+'"></div>':''}
                </div>`;
            }).join('') + '</div>';
    }

    _renderTabContent(tab, pm) {
        switch(tab) {
            case 'details': return this._renderTabDetails(pm);
            case 'steps':   return this._renderTabSteps(pm.steps||[]);
            case 'fees':    return this._renderTabFees(pm.fees||[]);
            default:        return '';
        }
    }

    _renderTabDetails(pm) {
        const row = (l,v)=>v?`<div class="gis-info-row"><span class="gis-info-label">${l}</span><span class="gis-info-value">${v}</span></div>`:'';
        return `<div class="gis-tab-content">
            <div class="gis-info-divider">مشخصات</div>
            ${row('شماره پروانه',   pm.permit_number ? this.escape(pm.permit_number) : null)}
            ${row('شماره درخواست',  pm.application_ref ? this.escape(pm.application_ref) : null)}
            ${row('شهرداری',        pm.municipality ? this.escape(pm.municipality) : null)}
            ${row('مهندس ناظر',     pm.engineer_name ? this.escape(pm.engineer_name) : null)}
            <div class="gis-info-divider">تاریخ‌ها</div>
            ${row('درخواست',        pm.application_date)}
            ${row('تأیید',          pm.approval_date)}
            ${row('انقضا',          pm.expiry_date)}
            ${row('پایان کار',      pm.completion_date)}
            <div class="gis-info-divider">مشخصات ساختمانی مجاز</div>
            ${row('طبقات مجاز',     pm.allowed_floors)}
            ${row('زیربنای مجاز',   pm.allowed_area_sqm ? pm.allowed_area_sqm+' م²' : null)}
            ${row('کاربری مجاز',    pm.allowed_use ? this.escape(pm.allowed_use) : null)}
            ${row('تراکم',          pm.density_pct ? pm.density_pct+'%' : null)}
            ${pm.notes?`<div class="gis-info-divider">یادداشت</div><div style="font-size:12px;color:#475569;">${this.escape(pm.notes)}</div>`:''}
        </div>`;
    }

    _renderTabSteps(steps) {
        const statusLabel = { pending:'در انتظار', done:'انجام شد', failed:'ناموفق', skipped:'رد شد' };
        const statusColor = { pending:'#94a3b8', done:'#10b981', failed:'#ef4444', skipped:'#f59e0b' };
        return `<div class="gis-tab-content">
            <div class="gis-section-title">مراحل فرآیند</div>
            ${steps.map(s=>`
            <div class="permit-step-row" style="border-right:3px solid ${statusColor[s.status]||'#e2e8f0'};">
                <div style="display:flex;justify-content:space-between;align-items:start;">
                    <div>
                        <div style="font-weight:700;font-size:13px;">${s.icon} ${s.label}</div>
                        ${s.done_date?`<div style="font-size:11px;color:#64748b;">📅 ${s.done_date}</div>`:''}
                        ${s.reference?`<div style="font-size:11px;color:#64748b;">📎 ${this.escape(s.reference)}</div>`:''}
                        ${s.notes?`<div style="font-size:11px;color:#94a3b8;">${this.escape(s.notes)}</div>`:''}
                    </div>
                    <div style="display:flex;flex-direction:column;align-items:flex-end;gap:4px;">
                        <span style="font-size:10px;color:${statusColor[s.status]};font-weight:700;">${statusLabel[s.status]||s.status}</span>
                        ${s.status!=='done'?`<button class="gis-btn gis-btn--xs" style="background:#dcfce7;color:#166534;border:1px solid #86efac;" data-mark-step="${s.key}">✅ انجام شد</button>`:''}
                        ${s.status==='done'?`<button class="gis-btn gis-btn--xs" data-undo-step="${s.key}">↩️ لغو</button>`:''}
                    </div>
                </div>
            </div>`).join('')}
        </div>`;
    }

    _renderTabFees(fees) {
        const fmt   = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const sColor= { pending:'#f59e0b', paid:'#10b981', overdue:'#ef4444', cancelled:'#94a3b8' };
        const sLabel= { pending:'در انتظار', paid:'پرداخت شد', overdue:'سررسید گذشت', cancelled:'لغو' };

        return `<div class="gis-tab-content">
            <div class="gis-section-title">عوارض و هزینه‌ها
                <button class="gis-btn gis-btn--xs" data-action="add-fee">+ افزودن</button>
            </div>
            ${fees.length ? fees.map(f=>`
            <div class="permit-fee-row" style="border-right:3px solid ${sColor[f.status]||'#94a3b8'};">
                <div style="flex:1;">
                    <div style="font-weight:700;font-size:13px;">${this.escape(f.description)}</div>
                    <div style="font-size:11px;color:#64748b;">
                        ${FEE_CAT_LABEL[f.category]||f.category}
                        ${f.due_date?' | 📅 سررسید: '+f.due_date:''}
                        ${f.receipt_number?' | رسید: '+f.receipt_number:''}
                    </div>
                </div>
                <div style="text-align:left;">
                    <div style="font-weight:700;font-size:14px;">${fmt(f.amount)} ریال</div>
                    <div style="font-size:10px;color:${sColor[f.status]};font-weight:700;">${sLabel[f.status]||f.status}</div>
                    ${f.status!=='paid'&&f.status!=='cancelled'?`
                    <button class="gis-btn gis-btn--xs" style="background:#dcfce7;color:#166534;margin-top:4px;"
                        data-pay-fee="${f.id}">💳 پرداخت</button>`:''
                    }
                    <button class="gis-btn gis-btn--xs gis-btn--danger" data-del-fee="${f.id}" style="margin-top:4px;">🗑️</button>
                </div>
            </div>`).join('')
            : '<div class="gis-empty-tab">عوارضی ثبت نشده.</div>'}
        </div>`;
    }

    _bindTabActions(tab, pm) {
        const body = this.ref('detailTabBody');
        if (!body) return;

        if (tab==='steps') {
            body.querySelectorAll('[data-mark-step]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    try {
                        await this.api.post(`/permits/${pm.id}/steps`,{step_key:btn.dataset.markStep,status:'done',done_date:new Date().toISOString().split('T')[0]});
                        this._toast('✅ مرحله تکمیل شد','#10b981');
                        this._openDetail({id:pm.id});
                    } catch(e){alert('خطا');}
                });
            });
            body.querySelectorAll('[data-undo-step]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    try {
                        await this.api.post(`/permits/${pm.id}/steps`,{step_key:btn.dataset.undoStep,status:'pending'});
                        this._toast('↩️ مرحله لغو شد','#f59e0b');
                        this._openDetail({id:pm.id});
                    } catch(e){alert('خطا');}
                });
            });
        }

        if (tab==='fees') {
            body.querySelector('[data-action="add-fee"]')?.addEventListener('click',()=>this._openFeeModal(pm.id));
            body.querySelectorAll('[data-pay-fee]').forEach(btn=>{
                btn.addEventListener('click',()=>this._openPayFeeModal(pm.id,btn.dataset.payFee,pm.fees||[]));
            });
            body.querySelectorAll('[data-del-fee]').forEach(btn=>{
                btn.addEventListener('click',async()=>{
                    if (!confirm('حذف این عارضه؟')) return;
                    try {
                        await this.api.delete(`/permits/${pm.id}/fees/${btn.dataset.delFee}`);
                        this._toast('🗑️ حذف شد'); this._openDetail({id:pm.id});
                    } catch(e){alert('خطا');}
                });
            });
        }
    }

    /* ── مودال پروانه ──────────────────────────────────────── */
    _openPermitModal(pm=null) {
        const isEdit = !!pm;
        const p = pm||{};
        const projOpts = `<option value="">—</option>` +
            this._projects.map(pr=>`<option value="${pr.id}" ${p.project_id==pr.id?'selected':''}>${this.escape(pr.name)}</option>`).join('');
        const selT = k=>p.type===k?'selected':'';
        const selS = k=>p.status===k?'selected':'';

        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:560px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">📋 ${isEdit?'ویرایش':'پروانه جدید'}</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نوع پروانه</label>
                        <select name="type">
                            <option value="build"       ${selT('build')}>🏗️ پروانه ساخت</option>
                            <option value="renovation"  ${selT('renovation')}>🔨 بازسازی</option>
                            <option value="demolish"    ${selT('demolish')}>💥 تخریب</option>
                            <option value="use_change"  ${selT('use_change')}>🔄 تغییر کاربری</option>
                            <option value="completion"  ${selT('completion')}>✅ پایان کار</option>
                        </select>
                    </div>
                    <div class="acc-form-group"><label>وضعیت</label>
                        <select name="status">
                            <option value="draft"        ${selS('draft')}>پیش‌نویس</option>
                            <option value="submitted"    ${selS('submitted')}>ارسال‌شده</option>
                            <option value="under_review" ${selS('under_review')}>در بررسی</option>
                            <option value="approved"     ${selS('approved')}>تأیید شده</option>
                            <option value="active"       ${selS('active')}>فعال</option>
                            <option value="completed"    ${selS('completed')}>پایان کار</option>
                            <option value="rejected"     ${selS('rejected')}>رد شده</option>
                            <option value="expired"      ${selS('expired')}>منقضی</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>شماره پروانه</label>
                        <input name="permit_number" value="${this.escape(p.permit_number||'')}">
                    </div>
                    <div class="acc-form-group"><label>شماره درخواست</label>
                        <input name="application_ref" value="${this.escape(p.application_ref||'')}">
                    </div>
                </div>
                <div class="acc-form-group"><label>پروژه</label>
                    <select name="project_id">${projOpts}</select>
                </div>
                <div class="gis-info-divider">تاریخ‌ها</div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ درخواست</label>
                        <input name="application_date" type="date" value="${p.application_date||''}">
                    </div>
                    <div class="acc-form-group"><label>تاریخ تأیید</label>
                        <input name="approval_date" type="date" value="${p.approval_date||''}">
                    </div>
                </div>
                <div class="acc-form-group"><label>تاریخ انقضا</label>
                    <input name="expiry_date" type="date" value="${p.expiry_date||''}">
                </div>
                <div class="gis-info-divider">مشخصات ساختمانی مجاز</div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>طبقات مجاز</label>
                        <input name="allowed_floors" type="number" min="0" value="${p.allowed_floors||''}">
                    </div>
                    <div class="acc-form-group"><label>زیربنای مجاز (م²)</label>
                        <input name="allowed_area_sqm" type="number" step="0.1" value="${p.allowed_area_sqm||''}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کاربری مجاز</label>
                        <input name="allowed_use" value="${this.escape(p.allowed_use||'')}">
                    </div>
                    <div class="acc-form-group"><label>تراکم %</label>
                        <input name="density_pct" type="number" step="5" value="${p.density_pct||''}">
                    </div>
                </div>
                <div class="acc-form-group"><label>شهرداری / منطقه</label>
                    <input name="municipality" value="${this.escape(p.municipality||'')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>مهندس ناظر</label>
                        <input name="engineer_name" value="${this.escape(p.engineer_name||'')}">
                    </div>
                    <div class="acc-form-group"><label>کد نظام مهندسی</label>
                        <input name="engineer_code" value="${this.escape(p.engineer_code||'')}">
                    </div>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(p.notes||'')}</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">${isEdit?'ذخیره':'ثبت پروانه'}</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',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            ['application_date','approval_date','expiry_date','allowed_floors','allowed_area_sqm','density_pct','project_id'].forEach(k=>{if(!body[k])delete body[k];});
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                if (isEdit) await this.api.put(`/permits/${pm.id}`,body);
                else        await this.api.post('/permits',body);
                close(); this._toast(isEdit?'✅ ویرایش شد':'✅ پروانه ثبت شد');
                await this._load();
                if (isEdit) this._openDetail({id:pm.id});
            } catch(e){alert('خطا: '+(e?.message||'')); btn.disabled=false;}
        });
    }

    /* ── مودال عارضه ───────────────────────────────────────── */
    _openFeeModal(permitId) {
        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:400px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">💳 افزودن عارضه</div>
            <form>
                <div class="acc-form-group"><label>دسته‌بندی</label>
                    <select name="category">
                        ${Object.entries(FEE_CAT_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
                    </select>
                </div>
                <div class="acc-form-group"><label>شرح *</label>
                    <input name="description" required placeholder="مثلاً: عوارض صدور پروانه">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>مبلغ (ریال) *</label>
                        <input name="amount" type="number" min="0" required>
                    </div>
                    <div class="acc-form-group"><label>سررسید</label>
                        <input name="due_date" type="date">
                    </div>
                </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',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            if (!body.due_date) delete body.due_date;
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                await this.api.post(`/permits/${permitId}/fees`,body);
                close(); this._toast('✅ عارضه افزوده شد');
                this._openDetail({id:permitId});
            } catch(e){alert('خطا'); btn.disabled=false;}
        });
    }

    /* ── مودال پرداخت عارضه ─────────────────────────────────── */
    _openPayFeeModal(permitId, feeId, fees) {
        const fee = fees.find(f=>String(f.id)===String(feeId));
        if (!fee) return;
        const fmt = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));

        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:360px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">💳 ثبت پرداخت</div>
            <div style="background:#f0fdf4;border-radius:8px;padding:10px;font-size:13px;margin-bottom:14px;">
                ${this.escape(fee.description)}: <b>${fmt(fee.amount)} ریال</b>
            </div>
            <form>
                <div class="acc-form-group"><label>تاریخ پرداخت</label>
                    <input name="paid_date" type="date" value="${new Date().toISOString().split('T')[0]}">
                </div>
                <div class="acc-form-group"><label>شماره رسید</label>
                    <input name="receipt_number" placeholder="اختیاری">
                </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--success">✅ ثبت پرداخت</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',ev=>{if(ev.target===ov)close();});
        ov.querySelector('form').addEventListener('submit',async ev=>{
            ev.preventDefault();
            const body=Object.fromEntries(new FormData(ev.target).entries());
            const btn=ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                await this.api.post(`/permits/${permitId}/fees/${feeId}/pay`,body);
                close(); this._toast('✅ پرداخت ثبت شد','#10b981');
                this._openDetail({id:permitId});
            } catch(e){alert('خطا'); btn.disabled=false;}
        });
    }

    _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;direction:rtl;`;
        t.textContent=msg; document.body.appendChild(t);
        setTimeout(()=>t.remove(),3000);
    }
    _fmt(v){return new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));}
}

//const FEE_CAT_LABEL = { permit_fee:'عوارض پروانه', levy:'عوارض نوسازی', fine:'جریمه', inspection:'هزینه بازدید', notary:'دفترخانه', other:'سایر' };
