/**
 * UserUseDashboardView.js — داشبورد کاربری (تحلیل بر حسب نوع کاربری/current_use)
 *
 * جریان کار:
 *   ۱) کاربر یک «کاربری» (current_use) انتخاب می‌کند → داشبورد شروع می‌شود
 *   ۲) سپس drill-down: منطقه → محله → بلوک → پارسل
 *
 * از همان endpointهای موجود استفاده می‌کند:
 *   - gis/dashboard/land-uses   → لیست کاربری‌ها
 *   - gis/drilldown (land_use=)  → منطقه/محله/بلوک (فیلترشده روی کاربری)
 *   - gis/parcels  (current_use=)→ سطح پارسل (لیست تفصیلی)
 */
import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";

const LS_KEY = 'acc_usedash_v1';

const STATUS_CFG = [
    { key: 'prospect',     label: 'بالقوه',  color: '#94a3b8' },
    { key: 'under_review', label: 'بررسی',   color: '#f59e0b' },
    { key: 'purchased',    label: 'خریداری', color: '#22c55e' },
    { key: 'active',       label: 'فعال',    color: '#10b981' },
    { key: 'completed',    label: 'تکمیل',   color: '#6366f1' },
];

const TYPE_CFG = {
    bldg: { color: '#6366f1', bg: '#eef2ff' },
    apt:  { color: '#0ea5e9', bg: '#e0f2fe' },
    shop: { color: '#f59e0b', bg: '#fef3c7' },
    land: { color: '#10b981', bg: '#d1fae5' },
};

export default class UserUseDashboardView extends BaseView {
    static title = "🧭 داشبورد کاربری";
    useContextBadge = false;

    constructor(props = {}) {
        super(props);
        this.api      = props.api;
        this._data    = [];
        this._uses    = [];                // [{value,count}]
        this._use     = '';               // کاربری انتخاب‌شده (گیت شروع)
        this._search  = '';
        this._sortDir = 'desc';
        this._filters = this._loadFilters();
        // drill: district → neighborhood → block → parcel
        this._level   = 'district';
        this._path    = [];               // [{level,key_id,label}]
        this._started = false;
        this._layers  = [];
        this._useTotal = null;            // مجموع دقیقِ کاربری از روی دادهٔ بارگذاری‌شده
    }

    async template() {
        return `<div class="red-wrap ud-wrap" dir="rtl">

            <!-- هدر + KPI -->
            <div class="red-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="kTotal">—</div>
                        <div class="red-kpi-lbl">کل ملک</div>
                    </div>
                    <div class="red-kpi red-kpi--bldg">
                        <div class="red-kpi-val" data-ref="kBldg">—</div>
                        <div class="red-kpi-lbl">ساختمان</div>
                    </div>
                    <div class="red-kpi red-kpi--apt">
                        <div class="red-kpi-val" data-ref="kApt">—</div>
                        <div class="red-kpi-lbl">آپارتمان</div>
                    </div>
                    <div class="red-kpi red-kpi--shop">
                        <div class="red-kpi-val" data-ref="kShop">—</div>
                        <div class="red-kpi-lbl">مغازه</div>
                    </div>
                    <div class="red-kpi red-kpi--land">
                        <div class="red-kpi-val" data-ref="kLand">—</div>
                        <div class="red-kpi-lbl">زمین</div>
                    </div>
                </div>
            </div>

            <!-- نوار انتخاب کاربری (گیت شروع) -->
            <div class="ud-usebar">
                <span class="ud-usebar-lbl">🏷️ کاربری:</span>
                <select class="red-sel ud-use-sel" data-ref="useSel">
                    <option value="">— یک کاربری انتخاب کنید —</option>
                </select>
                <button class="red-btn red-btn--primary" data-ref="goBtn">↻ نمایش</button>
                <span class="ud-use-chip" data-ref="useChip" style="display:none"></span>
            </div>

            <!-- نوار کنترل -->
            <div class="red-toolbar">
                <div class="red-search-wrap">
                    <span class="red-search-icon">🔍</span>
                    <input class="red-search" data-ref="searchInput" placeholder="جستجو...">
                </div>
                <div class="red-toolbar-right">
                    <button class="red-btn red-btn--icon" data-ref="sortDirBtn" title="تغییر جهت">↓</button>
                    <button class="red-btn red-btn--filter" data-ref="filterBtn">
                        ⚙️ فیلتر
                        <span class="red-filter-dot" data-ref="filterDot" style="display:none"></span>
                    </button>
                    <span class="red-count" data-ref="rowCount"></span>
                </div>
            </div>

            <!-- breadcrumb -->
            <div class="red-crumbs" data-ref="crumbs" style="display:none;align-items:center;gap:6px;flex-wrap:wrap;padding:6px 12px;font-size:13px;"></div>

            <div class="red-body">

                <!-- پنل فیلتر -->
                <aside class="red-filter-panel" data-ref="filterPanel">
                    <div class="red-fp-header">
                        <span>⚙️ فیلترها</span>
                        <button class="red-fp-close" data-ref="filterClose">✕</button>
                    </div>

                    <div class="red-fp-section">
                        <div class="red-fp-title">وضعیت</div>
                        <div class="red-checks" data-ref="statusChecks">
                            ${STATUS_CFG.map(s => `
                            <label class="red-check-item">
                                <input type="checkbox" value="${s.key}"
                                    ${(this._filters.statuses||[]).includes(s.key)?'checked':''}>
                                <span class="red-check-dot" style="background:${s.color}"></span>
                                ${s.label}
                            </label>`).join('')}
                        </div>
                    </div>

                    <div class="red-fp-section">
                        <div class="red-fp-title">لایه (LayerID)</div>
                        <select class="red-fp-sel" data-ref="layerSel">
                            <option value="">همه لایه‌ها</option>
                        </select>
                    </div>

                    <div class="red-fp-section">
                        <div class="red-fp-title">بازه مساحت زمین (م²)</div>
                        <div class="red-range-row">
                            <input type="number" class="red-fp-inp" data-ref="areaMin"
                                   value="${this._filters.area_min??''}" placeholder="از">
                            <span class="red-range-sep">—</span>
                            <input type="number" class="red-fp-inp" data-ref="areaMax"
                                   value="${this._filters.area_max??''}" placeholder="تا">
                        </div>
                    </div>

                    <div class="red-fp-footer">
                        <button class="red-btn red-btn--primary" data-ref="applyBtn">↻ اعمال</button>
                        <button class="red-btn red-btn--ghost"   data-ref="resetBtn">پاک کردن</button>
                    </div>
                </aside>

                <!-- بدنه -->
                <main class="red-main" data-ref="cardsWrap">
                    <div class="red-empty" style="text-align:center;padding:60px 20px;color:#64748b;">
                        <div style="font-size:40px;margin-bottom:12px;">🏷️</div>
                        <div style="font-size:15px;font-weight:700;margin-bottom:6px;">برای شروع، یک کاربری انتخاب کنید</div>
                        <div style="font-size:13px;">از نوار بالا یک نوع کاربری برگزینید و «نمایش» را بزنید.</div>
                    </div>
                </main>
            </div>

            <!-- overlay جزئیات پارسل -->
            <div class="red-detail-overlay" data-ref="detailOverlay" style="display:none">
                <div class="red-detail-modal" data-ref="detailModal"></div>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._loadUses();
        await this._loadLayers();
        this._bindEvents();
    }

    /* ───────── منابع کمکی ───────── */
    async _loadUses() {
        try {
            const res = await this.api.get('gis/dashboard/land-uses');
            this._uses = res?.data ?? [];
            const sel = this.ref('useSel');
            if (!sel) return;
            this._uses.forEach(u => {
                const o = document.createElement('option');
                o.value = u.value;
                o.textContent = `${u.value} (${(+u.count||0).toLocaleString('fa-IR')})`;
                if (this._use === u.value) o.selected = true;
                sel.appendChild(o);
            });
        } catch {}
    }

    async _loadLayers() {
        try {
            const res = await this.api.get('gis/layers-list');
            this._layers = res?.data ?? [];
            const sel = this.ref('layerSel');
            if (!sel) return;
            this._layers.forEach(l => {
                const o = document.createElement('option');
                o.value = l.layer_id;
                o.textContent = `${l.layer_id} (${(+l.parcel_count||0).toLocaleString('fa-IR')})`;
                if (this._filters.layer_id === l.layer_id) o.selected = true;
                sel.appendChild(o);
            });
        } catch {}
    }

    /* ───────── data ───────── */
    async _load() {
        if (!this._started || !this._use) { this._renderEmpty(); return; }
        const wrap = this.ref('cardsWrap');
        if (wrap) wrap.innerHTML = '<div class="red-loading">⏳ در حال بارگذاری...</div>';
        try {
            if (this._level === 'parcel') {
                const res = await this.api.get('gis/parcels', this._parcelParams());
                this._data = res?.data ?? [];
            } else {
                const res = await this.api.get('gis/drilldown', this._drillParams());
                this._data  = res?.data  ?? [];
                this._level = res?.level ?? this._level;
            }
            this._renderCrumbs();
            this._updateKPIs();
            this._render();
        } catch (e) {
            if (wrap) wrap.innerHTML = `<div class="red-error">❌ ${this.esc(e.message)}</div>`;
        }
    }

    _drillParams() {
        const f = this._filters;
        const p = { level: this._level, land_use: this._use };
        const dist = this._path.find(x => x.level === 'district');
        const hood = this._path.find(x => x.level === 'neighborhood');
        if (dist) p.district     = dist.key_id;
        if (hood) p.neighborhood = hood.key_id;
        if (f.statuses?.length) p.statuses = f.statuses.join(',');
        if (f.area_min)         p.area_min = f.area_min;
        if (f.area_max)         p.area_max = f.area_max;
        if (f.layer_id)         p.layer_id = f.layer_id;
        return p;
    }

    _parcelParams() {
        const f = this._filters;
        const block = this._path.find(x => x.level === 'block');
        const p = { current_use: this._use, per_page: 2000 };
        if (block) p.block = block.key_id;
        if (f.statuses?.length === 1) p.status = f.statuses[0]; // get_parcels تک‌وضعیتی است
        if (f.area_min) p.area_min = f.area_min;
        if (f.area_max) p.area_max = f.area_max;
        if (f.layer_id) p.layer_id = f.layer_id;
        return p;
    }

    _renderEmpty() {
        const wrap = this.ref('cardsWrap');
        if (wrap) wrap.innerHTML = `
            <div class="red-empty" style="text-align:center;padding:60px 20px;color:#64748b;">
                <div style="font-size:40px;margin-bottom:12px;">🏷️</div>
                <div style="font-size:15px;font-weight:700;margin-bottom:6px;">برای شروع، یک کاربری انتخاب کنید</div>
                <div style="font-size:13px;">از نوار بالا یک نوع کاربری برگزینید و «نمایش» را بزنید.</div>
            </div>`;
        const cr = this.ref('crumbs');
        if (cr) cr.style.display = 'none';
    }

    /* ───────── ناوبری drill ───────── */
    _drillInto(row) {
        if (this._level === 'district') {
            this._path  = [{ level:'district', key_id: row.key_id, label: row.label || ('منطقه ' + row.key_id) }];
            this._level = 'neighborhood';
        } else if (this._level === 'neighborhood') {
            this._path.push({ level:'neighborhood', key_id: row.key_id, label: row.label || '—' });
            this._level = 'block';
        } else if (this._level === 'block') {
            this._path.push({ level:'block', key_id: row.key_id, label: row.label || '—' });
            this._level = 'parcel';
        } else {
            return; // پارسل: ردیف‌ها خودشان جزئیات/نقشه دارند
        }
        this._load();
    }

    _goToCrumb(idx) {
        if (idx < 0) { this._path = []; this._level = 'district'; }
        else {
            this._path = this._path.slice(0, idx + 1);
            const last = this._path[this._path.length - 1];
            this._level = last.level === 'district' ? 'neighborhood'
                        : last.level === 'neighborhood' ? 'block' : 'parcel';
        }
        this._load();
    }

    _renderCrumbs() {
        const cr = this.ref('crumbs');
        if (!cr) return;
        cr.style.display = 'flex';
        const sep = '<span style="color:#cbd5e1;">‹</span>';
        const link = (txt, idx) =>
            `<a data-crumb="${idx}" style="color:#3b82f6;cursor:pointer;text-decoration:none;">${this.esc(txt)}</a>`;

        const parts = [
            `<span class="ud-crumb-use">🏷️ ${this.esc(this._use)}</span>`, sep,
            link('🗺️ مناطق', -1),
        ];
        this._path.forEach((c, i) => parts.push(sep, link(c.label, i)));
        const levelLbl = this._level === 'district' ? 'مناطق'
                       : this._level === 'neighborhood' ? 'محلات'
                       : this._level === 'block' ? 'بلوک‌ها' : 'پارسل‌ها';
        cr.innerHTML = parts.join(' ') +
            `<span style="margin-right:6px;color:#94a3b8;font-size:12px;">— ${levelLbl}</span>`;
        cr.querySelectorAll('[data-crumb]').forEach(a =>
            a.addEventListener('click', () => this._goToCrumb(parseInt(a.dataset.crumb)))
        );
    }

    /* ───────── KPIs ───────── */
    _updateKPIs() {
        const rows = this._data || [];
        const n = v => (+v || 0).toLocaleString('fa-IR');
        if (this._level === 'parcel') {
            const cnt = (pred) => rows.filter(pred).length;
            this._setRef('kTotal', n(rows.length));
            this._setRef('kBldg',  n(cnt(r => +r.bld_count  > 0)));
            this._setRef('kApt',   n(cnt(r => +r.apt_count  > 0)));
            this._setRef('kShop',  n(cnt(r => +r.shop_count > 0)));
            this._setRef('kLand',  n(cnt(r => !(+r.bld_count) && !(+r.apt_count) && !(+r.shop_count))));
        } else {
            const sum = k => rows.reduce((a, r) => a + (+r[k] || 0), 0);
            this._setRef('kTotal', n(sum('total_parcels')));
            this._setRef('kBldg',  n(sum('cnt_building')));
            this._setRef('kApt',   n(sum('cnt_apartment')));
            this._setRef('kShop',  n(sum('cnt_shop')));
            this._setRef('kLand',  n(sum('cnt_land_only')));
            // در سطحِ ریشه (منطقه) مجموعِ دقیق = کلِ کاربری → روی چیپ بنشان
            if (this._level === 'district') {
                this._useTotal = sum('total_parcels');
                this._updateUseChip();
            }
        }
    }

    /* ───────── رندر بدنه ───────── */
    _render() {
        if (this._level === 'parcel') this._renderParcels();
        else this._renderCards();
    }

    _renderCards() {
        const wrap = this.ref('cardsWrap');
        if (!wrap) return;
        const q = this._search.toLowerCase();
        let rows = this._data.filter(r => !q || String(r.label ?? '').toLowerCase().includes(q));
        rows.sort((a, b) => {
            const av = parseFloat(a.total_parcels ?? 0), bv = parseFloat(b.total_parcels ?? 0);
            return this._sortDir === 'desc' ? bv - av : av - bv;
        });

        const unitLbl = this._level === 'district' ? 'منطقه'
                      : this._level === 'neighborhood' ? 'محله' : 'بلوک';
        const rc = this.ref('rowCount');
        if (rc) rc.textContent = `${rows.length.toLocaleString('fa-IR')} ${unitLbl}`;

        if (!rows.length) { wrap.innerHTML = '<div class="red-empty">📭 داده‌ای با این شرایط یافت نشد</div>'; return; }

        wrap.innerHTML = `<div class="red-grid">${rows.map((r, i) => this._cardHtml(r, i)).join('')}</div>`;
        wrap.querySelectorAll('.red-card').forEach(card => {
            card.addEventListener('click', () => {
                const row = rows[parseInt(card.dataset.idx)];
                if (row) this._drillInto(row);
            });
        });
    }

    _cardHtml(r, idx) {
        const n = v => (+v || 0).toLocaleString('fa-IR');
        const headNum = +r.total_parcels || 0;
        const bldg = +r.cnt_building||0, apt = +r.cnt_apartment||0, shop = +r.cnt_shop||0, land = +r.cnt_land_only||0;

        let accentColor = '#10b981', accentLabel = 'زمین غالب';
        if (bldg >= apt && bldg >= shop && bldg >= land) { accentColor = '#6366f1'; accentLabel = 'ساختمان غالب'; }
        else if (apt >= shop && apt >= land)             { accentColor = '#0ea5e9'; accentLabel = 'آپارتمان غالب'; }
        else if (shop >= land)                            { accentColor = '#f59e0b'; accentLabel = 'مغازه غالب'; }

        const denom = +r.total_parcels || 1;
        const bPct  = Math.round(bldg / denom * 100);

        let title, badge;
        if (this._level === 'district') {
            title = r.label || `منطقه ${r.key_id}`; badge = `منطقه ${r.key_id}`;
        } else if (this._level === 'neighborhood') {
            const dist = this._path.find(x => x.level === 'district');
            title = r.label || '—'; badge = dist ? dist.label : 'محله';
        } else {
            title = `بلوک ${r.label}`; badge = '🏘️ بلوک';
        }

        const nextLbl = this._level === 'district' ? 'محلات'
                      : this._level === 'neighborhood' ? 'بلوک‌ها' : 'پارسل‌ها';
        const sub = this._level === 'block'
            ? `کلیک برای ${nextLbl}`
            : `${n(+r.total_blocks||0)} بلوک · کلیک برای ${nextLbl}`;
        const foot = `<span class="red-accent-tag" style="background:${accentColor}20;color:${accentColor}">${accentLabel}</span>
            <span class="red-avg">${sub}</span>`;

        return `
        <div class="red-card" data-idx="${idx}" style="border-top:3px solid ${accentColor};cursor:pointer">
            <div class="red-card-head">
                <div class="red-card-name">
                    <span class="red-card-title">${this.esc(title)}</span>
                    <span class="red-card-dist">${this.esc(badge)}</span>
                </div>
                <div class="red-card-total">
                    <span class="red-total-n">${n(headNum)}</span>
                    <span class="red-total-u">ملک</span>
                </div>
            </div>
            <div class="red-stats">
                <div class="red-stat" style="--sc:${TYPE_CFG.bldg.color};--sb:${TYPE_CFG.bldg.bg}">
                    <span class="red-stat-n">${n(bldg)}</span><span class="red-stat-l">ساختمان</span></div>
                <div class="red-stat" style="--sc:${TYPE_CFG.apt.color};--sb:${TYPE_CFG.apt.bg}">
                    <span class="red-stat-n">${n(apt)}</span><span class="red-stat-l">آپارتمان</span></div>
                <div class="red-stat" style="--sc:${TYPE_CFG.shop.color};--sb:${TYPE_CFG.shop.bg}">
                    <span class="red-stat-n">${n(shop)}</span><span class="red-stat-l">مغازه</span></div>
                <div class="red-stat" style="--sc:${TYPE_CFG.land.color};--sb:${TYPE_CFG.land.bg}">
                    <span class="red-stat-n">${n(land)}</span><span class="red-stat-l">زمین</span></div>
            </div>
            <div class="red-bbar-wrap">
                <div class="red-bbar"><div class="red-bbar-fill" style="width:${bPct}%;background:${accentColor}"></div></div>
                <span class="red-bbar-pct" style="color:${accentColor}">${bPct}٪</span>
            </div>
            <div class="red-card-foot">${foot}</div>
        </div>`;
    }

    /* ───────── سطح پارسل (جدول) ───────── */
    _renderParcels() {
        const wrap = this.ref('cardsWrap');
        if (!wrap) return;
        const q = this._search.toLowerCase();
        let rows = this._data.filter(r => !q ||
            String(r.code ?? '').toLowerCase().includes(q) ||
            String(r.address ?? '').toLowerCase().includes(q));

        const rc = this.ref('rowCount');
        if (rc) rc.textContent = `${rows.length.toLocaleString('fa-IR')} پارسل`;

        if (!rows.length) { wrap.innerHTML = '<div class="red-empty">📭 پارسلی با این شرایط یافت نشد</div>'; return; }

        const n  = v => (+v || 0).toLocaleString('fa-IR');
        const st = k => STATUS_CFG.find(s => s.key === k);

        const body = rows.map((r, i) => {
            const s = st(r.status);
            const badge = s
                ? `<span class="ud-st" style="background:${s.color}20;color:${s.color}">${s.label}</span>`
                : `<span class="ud-st" style="background:#e2e8f0;color:#64748b">${this.esc(r.status||'—')}</span>`;
            return `<tr data-idx="${i}">
                <td class="ud-c-code">${this.esc(r.code || '—')}</td>
                <td>${this.esc(r.block_code || '—')}</td>
                <td class="ud-c-addr" title="${this.esc(r.address||'')}">${this.esc(r.address || '—')}</td>
                <td class="ud-c-num">${r.area_sqm ? n(Math.round(+r.area_sqm)) : '—'}</td>
                <td class="ud-c-num">${n(r.bld_count)}</td>
                <td class="ud-c-num">${n(r.apt_count)}</td>
                <td class="ud-c-num">${n(r.shop_count)}</td>
                <td>${this.esc(r.assigned_user_name || '—')}</td>
                <td>${badge}</td>
            </tr>`;
        }).join('');

        wrap.innerHTML = `
        <div class="ud-table-wrap">
            <table class="ud-table">
                <thead><tr>
                    <th>کد</th><th>بلوک</th><th>آدرس</th><th>مساحت م²</th>
                    <th>ساخت.</th><th>آپ.</th><th>مغازه</th><th>کاربر</th><th>وضعیت</th>
                </tr></thead>
                <tbody>${body}</tbody>
            </table>
        </div>`;

        wrap.querySelectorAll('tbody tr').forEach(tr => {
            tr.addEventListener('click', () => {
                const row = rows[parseInt(tr.dataset.idx)];
                if (row) this._showParcel(row);
            });
        });
    }

    _showParcel(r) {
        const overlay = this.ref('detailOverlay');
        const modal   = this.ref('detailModal');
        if (!overlay || !modal) return;
        const n = v => (+v || 0).toLocaleString('fa-IR');
        const row = (lbl, val) => `<div class="red-dm-row"><span>${lbl}</span><b>${val}</b></div>`;

        modal.innerHTML = `
        <div class="red-dm-hdr">
            <div>
                <h3 class="red-dm-title">${this.esc(r.code || 'پارسل')}</h3>
                <span class="red-dm-sub">🏷️ ${this.esc(r.current_use || this._use)} · بلوک ${this.esc(r.block_code||'—')}</span>
            </div>
            <button class="red-dm-close" data-ref="detailClose">✕</button>
        </div>
        <div class="red-dm-body">
            <div class="red-dm-bigstats">
                <div class="red-dm-bs" style="border-color:#6366f1;background:#eef2ff">
                    <div class="red-dm-bsv" style="color:#6366f1">${n(r.bld_count)}</div>
                    <div class="red-dm-bsl">🏗️ ساختمان</div></div>
                <div class="red-dm-bs" style="border-color:#0ea5e9;background:#e0f2fe">
                    <div class="red-dm-bsv" style="color:#0ea5e9">${n(r.apt_count)}</div>
                    <div class="red-dm-bsl">🏢 آپارتمان</div></div>
                <div class="red-dm-bs" style="border-color:#f59e0b;background:#fef3c7">
                    <div class="red-dm-bsv" style="color:#f59e0b">${n(r.shop_count)}</div>
                    <div class="red-dm-bsl">🏪 مغازه</div></div>
            </div>
            <div class="red-dm-section">مشخصات</div>
            ${row('آدرس', this.esc(r.address || '—'))}
            ${row('مساحت زمین', r.area_sqm ? n(Math.round(+r.area_sqm)) + ' م²' : '—')}
            ${row('کاربری فعلی', this.esc(r.current_use || '—'))}
            ${row('وضعیت', this.esc(r.status || '—'))}
            ${row('مرحله', this.esc(r.pipeline_stage || '—'))}
            ${row('کاربر مسئول', this.esc(r.assigned_user_name || '—'))}
            ${row('منطقه / محله', this.esc((r.district_name||'—') + ' / ' + (r.neighborhood_name||'—')))}
            <div class="red-dm-section">موقعیت</div>
            ${row('مختصات', (r.lat && r.lng) ? `${(+r.lat).toFixed(5)}, ${(+r.lng).toFixed(5)}` : '—')}
            ${(r.block_code) ? `<button class="red-btn red-btn--primary" data-ref="mapBtn" style="width:100%;margin-top:14px">🗺️ نمایش بلوک روی نقشه</button>` : ''}
        </div>`;

        overlay.style.display = 'flex';
        modal.querySelector('[data-ref="detailClose"]')?.addEventListener('click', () => overlay.style.display = 'none');
        modal.querySelector('[data-ref="mapBtn"]')?.addEventListener('click', () => {
            try { sessionStorage.setItem('acc_gis_focus_block', JSON.stringify({ block: r.block_code, filters: { land_use: this._use } })); } catch {}
            this.eventBus?.emit('tab:open', { key: 'gis', params: { focusBlock: r.block_code } });
            overlay.style.display = 'none';
        });
    }

    /* ───────── events ───────── */
    _bindEvents() {
        this.ref('useSel')?.addEventListener('change', e => {
            this._use = e.target.value;
            this._useTotal = null;        // تا بارگذاری بعدی، عددِ دقیق نامعلوم است
            this._updateUseChip();
        });
        this.ref('goBtn')?.addEventListener('click', () => this._start());
        this.ref('searchInput')?.addEventListener('input', e => {
            this._search = e.target.value;
            this._render();
        });
        this.ref('sortDirBtn')?.addEventListener('click', () => {
            this._sortDir = this._sortDir === 'desc' ? 'asc' : 'desc';
            this.ref('sortDirBtn').textContent = this._sortDir === 'desc' ? '↓' : '↑';
            this._render();
        });
        this.ref('filterBtn')?.addEventListener('click', () => this._toggleFilter(true));
        this.ref('filterClose')?.addEventListener('click', () => this._toggleFilter(false));
        this.ref('applyBtn')?.addEventListener('click', () => this._applyFilters());
        this.ref('resetBtn')?.addEventListener('click', () => this._resetFilters());
        this.ref('detailOverlay')?.addEventListener('click', e => {
            if (e.target === this.ref('detailOverlay')) this.ref('detailOverlay').style.display = 'none';
        });
    }

    _updateUseChip() {
        const chip = this.ref('useChip');
        if (!chip) return;
        if (this._use) {
            // مجموعِ دقیق (از دادهٔ بارگذاری‌شده) را ترجیح بده؛ وگرنه عددِ تقریبیِ لیست
            const u = this._uses.find(x => x.value === this._use);
            const cnt = (this._useTotal != null) ? this._useTotal : (u ? +u.count||0 : null);
            chip.textContent = `🏷️ ${this._use}${cnt != null ? ` · ${cnt.toLocaleString('fa-IR')} ملک` : ''}`;
            chip.style.display = 'inline-flex';
        } else {
            chip.style.display = 'none';
        }
    }

    _start() {
        if (!this._use) {
            const sel = this.ref('useSel');
            if (sel) { sel.style.borderColor = '#ef4444'; setTimeout(() => sel.style.borderColor = '', 1200); }
            return;
        }
        this._started = true;
        this._path  = [];
        this._level = 'district';
        this._saveFilters();
        this._load();
    }

    _toggleFilter(open) {
        const p = this.ref('filterPanel');
        if (p) p.classList.toggle('red-filter-panel--open', open);
    }

    _applyFilters() {
        const statuses = [...(this.ref('statusChecks')?.querySelectorAll('input:checked')??[])].map(i=>i.value);
        this._filters = {
            statuses,
            layer_id: this.ref('layerSel')?.value || '',
            area_min: parseFloat(this.ref('areaMin')?.value)||null,
            area_max: parseFloat(this.ref('areaMax')?.value)||null,
        };
        const dot = this.ref('filterDot');
        if (dot) dot.style.display = this._hasActiveFilter() ? 'inline-block' : 'none';
        this._saveFilters();
        this._toggleFilter(false);
        if (this._started && this._use) {
            this._path  = [];
            this._level = 'district';
            this._load();
        }
    }

    _resetFilters() {
        this._filters = { statuses:[], layer_id:'', area_min:null, area_max:null };
        this._saveFilters();
        this.render(this.container);
    }

    _hasActiveFilter() {
        const f = this._filters;
        return f.statuses?.length || f.layer_id || f.area_min || f.area_max;
    }

    _loadFilters() { try { return JSON.parse(localStorage.getItem(LS_KEY))||{}; } catch { return {}; } }
    _saveFilters() { try { localStorage.setItem(LS_KEY, JSON.stringify({ ...this._filters, _use:this._use })); } catch {} }
    _setRef(k,v)   { const e=this.ref(k); if(e) e.textContent=v; }
    esc(s)         { return String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
    destroy()      { super.destroy?.(); }
}

viewRegistry.register('usedash', UserUseDashboardView);
