/**
 * EqtesadMelkView.js — پورتال کامل همکاری بنگاه «اقتصاد ملک»
 */
import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import acl from "../../core/AclService.js";
import {
    MELK_ROLE_LABELS as ROLE_LABELS,
    renderMelkCaseCollaboration,
    bindMelkCaseTabs,
    filterMelkNotesByMember,
} from "../../views/melk/melk-case-detail.js";

const STATUS_CFG = {
    open:        { label: 'باز',      color: '#3b82f6' },
    in_progress: { label: 'در جریان', color: '#f59e0b' },
    review:      { label: 'بررسی',    color: '#8b5cf6' },
    closed:      { label: 'بسته',     color: '#94a3b8' },
};

export default class EqtesadMelkView extends BaseView {
    static title = "🏛️ اقتصاد ملک";
    useContextBadge = false;

    constructor(props = {}) {
        super(props);
        this.api = props.api;
        this._tab = 'dashboard';
        this._overview = null;
        this._data = [];
        this._cases = [];
        this._org = [];
        this._level = 'district';
        this._path = [];
        this._search = '';
        this._participantRoles = [];
        this._canManage = false;
        this._blockCtx = null;
    }

    async template() {
        return `<div class="em-wrap red-wrap" dir="rtl">
            <div class="red-hero em-hero">
                <div class="red-hero-title">
                    <span class="red-hero-icon">🏛️</span>
                    <div>
                        <div class="red-hero-name">اقتصاد ملک</div>
                        <div class="red-hero-sub">شبکه همکاری بنگاه — منطقه → محله → بلوک → ملک → پرونده</div>
                    </div>
                </div>
                <div class="red-kpis">
                    <div class="red-kpi"><div class="red-kpi-val" data-ref="kDistricts">—</div><div class="red-kpi-lbl">منطقه</div></div>
                    <div class="red-kpi"><div class="red-kpi-val" data-ref="kCases">—</div><div class="red-kpi-lbl">پرونده باز</div></div>
                    <div class="red-kpi"><div class="red-kpi-val em-role-chip" data-ref="kRole">—</div><div class="red-kpi-lbl">نقش شما</div></div>
                </div>
            </div>

            <div class="em-main-tabs" data-ref="mainTabs">
                <button class="em-main-tab em-main-tab--active" data-tab="dashboard">🗺️ داشبورد</button>
                <button class="em-main-tab" data-tab="cases">📋 پرونده‌ها</button>
                <button class="em-main-tab em-main-tab--org" data-tab="org" style="display:none">👥 سازمان</button>
            </div>

            <div data-ref="panelDashboard">
                <div class="em-toolbar red-toolbar">
                    <input class="red-inp" placeholder="🔍 جستجو..." data-ref="searchInput">
                    <div class="red-crumbs" data-ref="crumbs"></div>
                    <button class="red-btn" data-ref="backBtn" style="display:none">← بازگشت</button>
                    <button class="red-btn red-btn--primary" data-ref="refreshBtn">↻</button>
                    <button class="red-btn" data-ref="newCaseBtn" style="display:none">➕ پرونده</button>
                    <button class="red-btn" data-ref="mapBtn">🗺️ نقشه</button>
                </div>
                <div class="em-grid red-grid" data-ref="grid"></div>
            </div>

            <div data-ref="panelCases" style="display:none">
                <div class="em-toolbar red-toolbar">
                    <select class="red-sel" data-ref="caseStatusFilter">
                        <option value="">همه وضعیت‌ها</option>
                        <option value="open">باز</option>
                        <option value="in_progress">در جریان</option>
                        <option value="review">بررسی</option>
                        <option value="closed">بسته</option>
                    </select>
                    <button class="red-btn red-btn--primary" data-ref="reloadCasesBtn">↻ بروزرسانی</button>
                </div>
                <div class="em-cases-full" data-ref="casesFull"></div>
            </div>

            <div data-ref="panelOrg" style="display:none">
                <div class="em-org-form" data-ref="orgForm"></div>
                <div class="em-org-list" data-ref="orgList"></div>
            </div>

            <div class="red-detail-overlay" data-ref="detailOverlay" style="display:none">
                <div class="red-detail em-detail">
                    <button class="red-detail-close" data-ref="detailClose">✕</button>
                    <div data-ref="detailBody"></div>
                </div>
            </div>
        </div>`;
    }

    async afterRender() {
        this._canManage = acl.can('melk.manage');
        if (this._canManage) {
            const orgTab = this.ref('mainTabs')?.querySelector('[data-tab="org"]');
            if (orgTab) orgTab.style.display = '';
        }
        try {
            const pr = await this.api.get('melk/participant-roles');
            this._participantRoles = pr?.data ?? [];
        } catch { this._participantRoles = []; }

        await this._loadOverview();
        this._bindEvents();
        this._checkGisHandoff();
        this.eventBus?.on('melk:open-case', this._onOpenCaseEvent, this);
    }

    destroy() {
        this.eventBus?.off('melk:open-case', this._onOpenCaseEvent);
        super.destroy?.();
    }

    _onOpenCaseEvent = ({ caseId }) => {
        if (caseId) this._openCase(caseId);
    };

    async _checkGisHandoff() {
        try {
            const raw = sessionStorage.getItem('acc_melk_create_parcel');
            if (!raw) return;
            sessionStorage.removeItem('acc_melk_create_parcel');
            const p = JSON.parse(raw);
            if (p?.parcel_id) await this._createCaseFromParcel(p);
        } catch { /* ignore */ }
    }

    async _loadOverview() {
        try {
            const res = await this.api.get('melk/overview');
            this._overview = res?.data ?? res;
            this._data = this._overview?.districts ?? [];
            this._level = 'district';
            this._path = [];
            this._blockCtx = null;
            this._updateKpis();
            if (this._tab === 'dashboard') {
                this._renderGrid();
                this._renderCrumbs();
            }
        } catch (e) {
            this.ref('grid').innerHTML = `<div class="em-empty">خطا: ${this.esc(e.message)}</div>`;
        }
    }

    async _switchMainTab(tab) {
        this._tab = tab;
        this.ref('mainTabs')?.querySelectorAll('.em-main-tab').forEach(b =>
            b.classList.toggle('em-main-tab--active', b.dataset.tab === tab));
        this.ref('panelDashboard').style.display = tab === 'dashboard' ? '' : 'none';
        this.ref('panelCases').style.display = tab === 'cases' ? '' : 'none';
        this.ref('panelOrg').style.display = tab === 'org' ? '' : 'none';
        if (tab === 'cases') await this._loadCases();
        if (tab === 'org') await this._loadOrg();
    }

    async _loadCases(filters = {}) {
        const st = this.ref('caseStatusFilter')?.value;
        if (st) filters.status = st;
        const qs = new URLSearchParams(filters).toString();
        try {
            const res = await this.api.get(`melk/cases${qs ? '?' + qs : ''}`);
            this._cases = res?.data?.data ?? res?.data ?? [];
        } catch { this._cases = []; }
        this._renderCasesList(this.ref('casesFull'));
    }

    async _loadOrg() {
        try {
            const res = await this.api.get('melk/org-assignments');
            this._org = res?.data?.data ?? res?.data ?? [];
        } catch { this._org = []; }
        this._renderOrg();
    }

    async _drill(item) {
        if (this._level === 'district') {
            this._path.push({ level: 'district', id: item.id, label: item.name });
            this._level = 'neighborhood';
            const res = await this.api.get(`melk/hierarchy?level=neighborhood&district=${item.id}`);
            this._data = res?.data?.data ?? res?.data ?? [];
        } else if (this._level === 'neighborhood') {
            this._path.push({ level: 'neighborhood', id: item.id, label: item.name });
            this._level = 'block';
            const res = await this.api.get(`melk/hierarchy?level=block&neighborhood=${item.id}`);
            this._data = res?.data?.data ?? res?.data ?? [];
        } else if (this._level === 'block') {
            this._path.push({ level: 'block', id: item.block_code, label: item.block_code, block: item });
            this._level = 'parcel';
            this._blockCtx = item;
            const res = await this.api.get(`gis/parcels?block=${encodeURIComponent(item.block_code)}`);
            this._data = res?.data?.data ?? res?.data ?? [];
        } else return;

        this._renderGrid();
        this._renderCrumbs();
        this.ref('backBtn').style.display = '';
        this._toggleNewCaseBtn();
    }

    _toggleNewCaseBtn() {
        const btn = this.ref('newCaseBtn');
        if (!btn) return;
        const show = acl.can('melk.cases.create') && (this._level === 'block' || this._level === 'parcel');
        btn.style.display = show ? '' : 'none';
    }

    _updateKpis() {
        const o = this._overview || {};
        if (this.ref('kDistricts')) this.ref('kDistricts').textContent = o.district_count ?? '—';
        if (this.ref('kCases')) this.ref('kCases').textContent = o.open_cases ?? '—';
        if (this.ref('kRole')) this.ref('kRole').textContent = o.user_role || 'کاربر';
    }

    _renderCrumbs() {
        const el = this.ref('crumbs');
        if (!el) return;
        const city = this._overview?.city || 'شهر';
        const parts = [{ label: `🏛️ ${city}` }, ...this._path.map(p => ({ label: p.label }))];
        el.innerHTML = parts.map((p, i) =>
            `<span class="red-crumb${i === parts.length - 1 ? ' red-crumb--active' : ''}" data-idx="${i}">${this.esc(p.label)}</span>`
        ).join('<span class="red-crumb-sep">›</span>');
        el.querySelectorAll('.red-crumb').forEach(c => {
            c.addEventListener('click', () => this._crumbNav(parseInt(c.dataset.idx, 10)));
        });
    }

    async _crumbNav(idx) {
        if (idx <= 0) {
            await this._loadOverview();
            this.ref('backBtn').style.display = 'none';
            this._toggleNewCaseBtn();
            return;
        }
        const target = this._path[idx - 1];
        this._path = this._path.slice(0, idx);
        if (target.level === 'district') {
            this._level = 'neighborhood';
            const res = await this.api.get(`melk/hierarchy?level=neighborhood&district=${target.id}`);
            this._data = res?.data?.data ?? res?.data ?? [];
        } else if (target.level === 'neighborhood') {
            this._level = 'block';
            const res = await this.api.get(`melk/hierarchy?level=block&neighborhood=${target.id}`);
            this._data = res?.data?.data ?? res?.data ?? [];
            this._blockCtx = null;
        } else if (target.level === 'block') {
            this._level = 'parcel';
            this._blockCtx = target.block;
            const res = await this.api.get(`gis/parcels?block=${encodeURIComponent(target.id)}`);
            this._data = res?.data?.data ?? res?.data ?? [];
        }
        this._renderGrid();
        this._renderCrumbs();
        this._toggleNewCaseBtn();
    }

    _renderGrid() {
        const grid = this.ref('grid');
        if (!grid) return;
        const q = this._search.toLowerCase();
        const items = (this._data || []).filter(r => {
            const name = (r.name || r.block_code || r.code || '').toLowerCase();
            return !q || name.includes(q);
        });

        if (!items.length) {
            grid.innerHTML = `<div class="em-empty">موردی یافت نشد.</div>`;
            return;
        }

        if (this._level === 'district') {
            grid.innerHTML = items.map(d => `
                <div class="red-card em-card" data-id="${d.id}">
                    <div class="em-card-badge" style="background:${d.color || '#6366f1'}">${this.esc(d.code || d.id)}</div>
                    <div class="red-card-title">${this.esc(d.name)}</div>
                    <div class="red-card-meta"><span>🏘️ ${d.neighborhood_count || 0}</span><span>📍 ${d.parcel_count || 0}</span></div>
                    ${d.lead_name ? `<div class="em-lead">👤 ${this.esc(d.lead_name)}</div>` : `<div class="em-lead em-lead--empty">سرگروه تعیین نشده</div>`}
                </div>`).join('');
        } else if (this._level === 'neighborhood') {
            grid.innerHTML = items.map(n => `
                <div class="red-card em-card" data-id="${n.id}">
                    <div class="red-card-title">${this.esc(n.name)}</div>
                    <div class="red-card-meta"><span>🧱 ${n.block_count || 0}</span><span>📍 ${n.parcel_count || 0}</span></div>
                    ${n.manager_name ? `<div class="em-lead">👤 ${this.esc(n.manager_name)}</div>` : ''}
                </div>`).join('');
        } else if (this._level === 'block') {
            grid.innerHTML = items.map(b => `
                <div class="red-card em-card" data-block="${this.esc(b.block_code)}">
                    <div class="red-card-title">🧱 ${this.esc(b.block_code)}</div>
                    <div class="red-card-meta"><span>📍 ${b.parcel_count || 0}</span><span>🏢 ${b.bld_count || 0}</span></div>
                    ${b.open_cases > 0 ? `<div class="em-case-badge">${b.open_cases} پرونده</div>` : ''}
                </div>`).join('');
        } else {
            grid.innerHTML = items.map(p => `
                <div class="red-card em-card em-card--parcel" data-parcel="${p.id}">
                    <div class="red-card-title">${this.esc(p.code || 'ملک #' + p.id)}</div>
                    <div class="red-card-meta"><span>${this.esc(p.status || '')}</span>${p.area_sqm ? `<span>${p.area_sqm} m²</span>` : ''}</div>
                    <div class="em-card-actions">
                        ${acl.can('melk.cases.create') ? `<button class="em-mini-btn" data-action="case" data-id="${p.id}">➕ پرونده</button>` : ''}
                        <button class="em-mini-btn" data-action="map" data-id="${p.id}" data-code="${this.esc(p.code || '')}">🗺️</button>
                    </div>
                </div>`).join('');
        }

        grid.querySelectorAll('.red-card').forEach(card => {
            card.addEventListener('click', (e) => {
                if (e.target.closest('[data-action]')) return;
                const id = card.dataset.id;
                const block = card.dataset.block;
                if (this._level === 'parcel') return;
                const item = items.find(x =>
                    String(x.id) === id || x.block_code === block);
                if (item) this._drill(item);
            });
        });
        grid.querySelectorAll('[data-action="case"]').forEach(btn => {
            btn.addEventListener('click', async (e) => {
                e.stopPropagation();
                const p = items.find(x => String(x.id) === btn.dataset.id);
                if (p) await this._createCaseFromParcel(p);
            });
        });
        grid.querySelectorAll('[data-action="map"]').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const code = btn.dataset.code;
                if (this._blockCtx?.block_code) {
                    sessionStorage.setItem('acc_gis_focus_block', JSON.stringify({ block: this._blockCtx.block_code }));
                }
                this.eventBus?.emit('tab:open', { key: 'gis', params: { focusBlock: this._blockCtx?.block_code, code } });
            });
        });
    }

    _renderCasesList(el) {
        if (!el) return;
        if (!this._cases.length) {
            el.innerHTML = `<div class="em-empty">پرونده‌ای ثبت نشده.</div>`;
            return;
        }
        el.innerHTML = this._cases.map(c => this._caseRowHtml(c)).join('');
        el.querySelectorAll('.em-case-row').forEach(row => {
            row.addEventListener('click', () => this._openCase(parseInt(row.dataset.case, 10)));
        });
    }

    _caseRowHtml(c) {
        const st = STATUS_CFG[c.status] || STATUS_CFG.open;
        return `<div class="em-case-row" data-case="${c.id}">
            <div class="em-case-key">${this.esc(c.case_key)}</div>
            <div class="em-case-title">${this.esc(c.title)}</div>
            <div class="em-case-loc">${this.esc(c.district_name || '')} ${c.neighborhood_name ? '› ' + this.esc(c.neighborhood_name) : ''} ${c.block_code ? '› ' + this.esc(c.block_code) : ''}</div>
            <span class="em-status" style="background:${st.color}">${st.label}</span>
        </div>`;
    }

    async _createCaseFromParcel(p) {
        if (!acl.can('melk.cases.create')) return alert('مجوز ایجاد پرونده ندارید');
        const title = prompt('عنوان پرونده:', `پرونده ${p.code || p.id}`);
        if (title === null) return;
        try {
            const res = await this.api.post('melk/cases', {
                parcel_id: p.id || p.parcel_id,
                title: title || `پرونده ${p.code || p.id}`,
                district_id: p.district_id,
                neighborhood_id: p.neighborhood_id,
                block_code: p.block_code,
            });
            const id = res?.id ?? res?.data?.id;
            if (id) {
                await this._openCase(id);
                await this._loadOverview();
            }
        } catch (e) { alert(e.message || e); }
    }

    async _createCaseFromContext() {
        const d = this._path.find(x => x.level === 'district');
        const n = this._path.find(x => x.level === 'neighborhood');
        const b = this._path.find(x => x.level === 'block');
        const title = prompt('عنوان پرونده:', b ? `پرونده بلوک ${b.label}` : 'پرونده جدید');
        if (title === null) return;
        try {
            const res = await this.api.post('melk/cases', {
                title,
                district_id: d?.id,
                neighborhood_id: n?.id,
                block_code: b?.id || this._blockCtx?.block_code,
            });
            const id = res?.id ?? res?.data?.id;
            if (id) await this._openCase(id);
        } catch (e) { alert(e.message || e); }
    }

    async _openCase(id) {
        try {
            const res = await this.api.get(`melk/cases/${id}`);
            const c = res?.data?.data ?? res?.data;
            const st = STATUS_CFG[c.status] || STATUS_CFG.open;
            const canEdit = acl.can('melk.cases.edit') || acl.can('melk.manage');
            const body = this.ref('detailBody');
            const roleOpts = (this._participantRoles.length ? this._participantRoles : Object.entries(ROLE_LABELS).map(([key, label]) => ({ key, label })))
                .map(r => `<option value="${r.key}">${this.esc(r.label)}</option>`).join('');

            const collabHtml = renderMelkCaseCollaboration(c, {
                esc: (t) => this.esc(t),
                canEditFull: canEdit,
                roleOpts,
            });

            body.innerHTML = `
                <h2>${this.esc(c.title)}</h2>
                <div class="em-detail-meta">
                    <span class="em-status" style="background:${st.color}">${st.label}</span>
                    <span>${this.esc(c.case_key)}</span>
                    ${c.parcel_code ? `<span>کد: ${this.esc(c.parcel_code)}</span>` : ''}
                </div>
                <p class="em-detail-loc">📍 ${this.esc(c.district_name || '')} ${c.neighborhood_name ? '› ' + this.esc(c.neighborhood_name) : ''} ${c.block_code ? '› ' + this.esc(c.block_code) : ''}</p>
                ${canEdit ? `<div class="em-detail-edit">
                    <label>وضعیت</label>
                    <select data-ref="caseStatusSel">${Object.entries(STATUS_CFG).map(([k,v]) =>
                        `<option value="${k}" ${c.status===k?'selected':''}>${v.label}</option>`).join('')}</select>
                    <label>خلاصه</label>
                    <textarea data-ref="caseSummary" rows="2">${this.esc(c.summary || '')}</textarea>
                    <button class="red-btn red-btn--primary" data-ref="saveCaseBtn">ذخیره</button>
                </div>` : (c.summary ? `<p>${this.esc(c.summary)}</p>` : '')}
                <div class="em-case-section em-case-section--collab">
                    <h4>👥 همکاری و نظرات اعضا</h4>
                    ${collabHtml}
                </div>`;

            bindMelkCaseTabs(body.querySelector('.em-case-collab'));
            body.querySelectorAll('.em-member-card').forEach(card => {
                card.addEventListener('click', (e) => {
                    if (e.target.closest('[data-rm-part]')) return;
                    filterMelkNotesByMember(body.querySelector('.em-case-collab'), +card.dataset.memberUid);
                });
            });

            this.ref('detailOverlay').style.display = 'flex';
            body.querySelector('[data-ref="noteSubmit"]')?.addEventListener('click', () => this._submitNote(id));
            body.querySelector('[data-ref="saveCaseBtn"]')?.addEventListener('click', () => this._saveCase(id, body));
            body.querySelectorAll('[data-rm-part]').forEach(btn => {
                btn.addEventListener('click', async () => {
                    await this.api.delete(`melk/cases/${id}/participants/${btn.dataset.rmPart}`);
                    await this._openCase(id);
                });
            });
            const qInp = body.querySelector('[data-ref="partUserQ"]');
            const qRes = body.querySelector('[data-ref="partUserResults"]');
            let qTimer;
            qInp?.addEventListener('input', () => {
                clearTimeout(qTimer);
                qTimer = setTimeout(async () => {
                    const q = qInp.value.trim();
                    if (q.length < 1) { qRes.innerHTML = ''; return; }
                    const ur = await this.api.get(`melk/users?q=${encodeURIComponent(q)}`);
                    const users = ur?.data ?? [];
                    qRes.innerHTML = users.map(u =>
                        `<button type="button" class="em-user-pick" data-uid="${u.id}">${this.esc(u.display_name)} (${this.esc(u.user_login)})</button>`
                    ).join('');
                    qRes.querySelectorAll('.em-user-pick').forEach(pb => {
                        pb.addEventListener('click', async () => {
                            await this.api.post(`melk/cases/${id}/participants`, {
                                user_id: +pb.dataset.uid,
                                role_type: body.querySelector('[data-ref="partRoleSel"]')?.value || 'other',
                            });
                            await this._openCase(id);
                        });
                    });
                }, 300);
            });
        } catch (e) { alert(e.message || e); }
    }

    async _saveCase(id, body) {
        try {
            await this.api.put(`melk/cases/${id}`, {
                status: body.querySelector('[data-ref="caseStatusSel"]')?.value,
                summary: body.querySelector('[data-ref="caseSummary"]')?.value,
            });
            await this._openCase(id);
            await this._loadOverview();
        } catch (e) { alert(e.message || e); }
    }

    async _submitNote(caseId) {
        const inp = this.ref('detailBody')?.querySelector('[data-ref="noteInput"]');
        const text = inp?.value?.trim();
        if (!text) return;
        try {
            await this.api.post(`melk/cases/${caseId}/notes`, { body: text });
            await this._openCase(caseId);
        } catch (e) { alert(e.message || e); }
    }

    async _renderOrg() {
        const form = this.ref('orgForm');
        const list = this.ref('orgList');
        if (!form || !list) return;

        let districts = [];
        let neighborhoods = [];
        try {
            const dr = await this.api.get('gis/districts');
            districts = dr?.data?.data ?? dr?.data ?? [];
            const nr = await this.api.get('gis/neighborhoods');
            neighborhoods = nr?.data?.data ?? nr?.data ?? [];
        } catch { /* */ }

        form.innerHTML = `
            <h3>تعیین سرگروه / مدیر محله</h3>
            <div class="em-org-row">
                <select data-ref="orgUnitType">
                    <option value="district">منطقه (سرگروه)</option>
                    <option value="neighborhood">محله (مدیر)</option>
                </select>
                <select data-ref="orgUnitId">
                    ${districts.map(d => `<option value="${d.id}" data-type="district">${this.esc(d.name)}</option>`).join('')}
                </select>
                <input data-ref="orgUserQ" class="red-inp" placeholder="جستجوی کاربر...">
                <input type="hidden" data-ref="orgUserId" value="">
                <div data-ref="orgUserPick"></div>
                <button class="red-btn red-btn--primary" data-ref="orgSaveBtn">ذخیره</button>
            </div>`;

        const unitType = form.querySelector('[data-ref="orgUnitType"]');
        const unitId = form.querySelector('[data-ref="orgUnitId"]');
        const refreshUnits = () => {
            const t = unitType.value;
            unitId.innerHTML = (t === 'district' ? districts : neighborhoods)
                .map(u => `<option value="${u.id}">${this.esc(u.name)}</option>`).join('');
        };
        unitType.addEventListener('change', refreshUnits);

        let oTimer;
        const qInp = form.querySelector('[data-ref="orgUserQ"]');
        const pick = form.querySelector('[data-ref="orgUserPick"]');
        const hid = form.querySelector('[data-ref="orgUserId"]');
        qInp.addEventListener('input', () => {
            clearTimeout(oTimer);
            oTimer = setTimeout(async () => {
                const q = qInp.value.trim();
                if (!q) { pick.innerHTML = ''; return; }
                const ur = await this.api.get(`melk/users?q=${encodeURIComponent(q)}`);
                pick.innerHTML = (ur?.data ?? []).map(u =>
                    `<button type="button" class="em-user-pick" data-uid="${u.id}">${this.esc(u.display_name)}</button>`
                ).join('');
                pick.querySelectorAll('.em-user-pick').forEach(b => {
                    b.addEventListener('click', () => {
                        hid.value = b.dataset.uid;
                        qInp.value = b.textContent;
                        pick.innerHTML = '';
                    });
                });
            }, 300);
        });

        form.querySelector('[data-ref="orgSaveBtn"]').addEventListener('click', async () => {
            const uid = +hid.value;
            if (!uid) return alert('کاربر را انتخاب کنید');
            try {
                await this.api.post('melk/org-assignments', {
                    unit_type: unitType.value,
                    unit_id: +unitId.value,
                    user_id: uid,
                    role_slug: unitType.value === 'district' ? 'district_lead' : 'neighborhood_manager',
                });
                await this._loadOrg();
                await this._loadOverview();
            } catch (e) { alert(e.message || e); }
        });

        list.innerHTML = `<h3>انتصاب‌های فعلی</h3>` + (this._org.length ? `
            <table class="em-org-table"><thead><tr><th>نوع</th><th>واحد</th><th>مسئول</th><th></th></tr></thead>
            <tbody>${this._org.map(o => `<tr>
                <td>${o.unit_type === 'district' ? 'منطقه' : 'محله'}</td>
                <td>${this.esc(o.district_name || o.neighborhood_name || o.unit_id)}</td>
                <td>${this.esc(o.user_name || o.user_id)}</td>
                <td><button class="em-link-btn" data-del-org="${o.id}">حذف</button></td>
            </tr>`).join('')}</tbody></table>` : `<p class="em-empty">انتصابی ثبت نشده.</p>`);

        list.querySelectorAll('[data-del-org]').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('حذف شود؟')) return;
                await this.api.delete(`melk/org-assignments/${btn.dataset.delOrg}`);
                await this._loadOrg();
                await this._loadOverview();
            });
        });
    }

    _bindEvents() {
        this.ref('mainTabs')?.querySelectorAll('.em-main-tab').forEach(b => {
            b.addEventListener('click', () => this._switchMainTab(b.dataset.tab));
        });
        this.ref('searchInput')?.addEventListener('input', e => {
            this._search = e.target.value;
            this._renderGrid();
        });
        this.ref('refreshBtn')?.addEventListener('click', () => this._loadOverview());
        this.ref('reloadCasesBtn')?.addEventListener('click', () => this._loadCases());
        this.ref('caseStatusFilter')?.addEventListener('change', () => this._loadCases());
        this.ref('newCaseBtn')?.addEventListener('click', () => this._createCaseFromContext());
        this.ref('backBtn')?.addEventListener('click', async () => {
            if (!this._path.length) return;
            await this._crumbNav(this._path.length);
        });
        this.ref('detailClose')?.addEventListener('click', () => {
            this.ref('detailOverlay').style.display = 'none';
        });
        this.ref('mapBtn')?.addEventListener('click', () => {
            this.eventBus?.emit('tab:open', { key: 'gis' });
        });
    }

    esc(t) {
        return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }
}

viewRegistry.register('eqtesad_melk', EqtesadMelkView);
