/**
 * RealEstateDashboardView.js — داشبورد حرفه‌ای تحلیل املاک
 */
import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";

const LS_KEY = 'acc_re_v3';

const STATUS_CFG = [
    { key: 'prospect',  label: 'بالقوه',    color: '#94a3b8' },
    { key: 'active',    label: 'فعال',       color: '#22c55e' },
    { key: 'completed', label: 'تکمیل',      color: '#6366f1' },
    { key: 'suspended', label: 'متوقف',      color: '#f59e0b' },
    { key: 'cancelled', label: 'لغو',        color: '#ef4444' },
];

const TYPE_CFG = [
    { key: 'cnt_building',  label: 'ساختمان',  icon: 'dashicons-building',   color: '#6366f1', bg: '#eef2ff' },
    { key: 'cnt_apartment', label: 'آپارتمان', icon: 'dashicons-admin-home',  color: '#0ea5e9', bg: '#e0f2fe' },
    { key: 'cnt_shop',      label: 'مغازه',    icon: 'dashicons-cart',        color: '#f59e0b', bg: '#fef3c7' },
    { key: 'cnt_land_only', label: 'زمین',     icon: 'dashicons-admin-site',  color: '#10b981', bg: '#d1fae5' },
];

export default class RealEstateDashboardView extends BaseView {
    static title = "🏘️ داشبورد املاک";
    useContextBadge = false;

    constructor(props = {}) {
        super(props);
        this.api        = props.api;
        this._data      = [];
        this._summary   = {};
        this._landUses  = [];
        this._sortCol   = 'total_blocks';
        this._sortDir   = 'desc';
        this._search    = '';
        this._filters   = this._loadFilters();
        this._showFilter = false;
        // ── drill-down: منطقه → محله → بلوک ──
        this._level     = 'district';     // district | neighborhood | block
        this._path      = [];             // [{level, key_id, label}] والدینِ انتخاب‌شده
        this._started   = false;          // داشبورد تا «اعمال» خالی می‌ماند
        this._layers    = [];             // لیست LayerIDها برای فیلتر
    }

    async template() {
        return `<div class="red-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 class="red-kpi red-kpi--area">
                        <div class="red-kpi-val" data-ref="kArea">—</div>
                        <div class="red-kpi-lbl">متوسط م²</div>
                    </div>
                </div>
            </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">
                    <select class="red-sel" data-ref="sortSel">
                        <option value="total_parcels">تعداد کل</option>
                        <option value="cnt_building">ساختمان</option>
                        <option value="cnt_apartment">آپارتمان</option>
                        <option value="cnt_shop">مغازه</option>
                        <option value="cnt_land_only">زمین</option>
                        <option value="avg_area">متوسط مساحت</option>
                    </select>
                    <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-fp-hint">عدد = حداقل تعداد لازم (۰ = بدون فیلتر)</div>
                        <div class="red-def-row">
                            <div class="red-def-box">
                                <div class="red-def-lbl" style="color:#6366f1">🏗️ ساختمان</div>
                                <input type="number" class="red-num-input" data-ref="defBuilding"
                                       value="${this._filters.def_building??0}" min="0">
                            </div>
                            <div class="red-def-box">
                                <div class="red-def-lbl" style="color:#0ea5e9">🏢 آپارتمان</div>
                                <input type="number" class="red-num-input" data-ref="defUnits"
                                       value="${this._filters.def_units??0}" min="0">
                            </div>
                            <div class="red-def-box">
                                <div class="red-def-lbl" style="color:#f59e0b">🏪 مغازه</div>
                                <input type="number" class="red-num-input" data-ref="defShops"
                                       value="${this._filters.def_shops??0}" min="0">
                            </div>
                        </div>
                        <div class="red-def-preview" data-ref="defPreview">همه ملک‌ها</div>
                    </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>
                        <select class="red-fp-sel" data-ref="landUseSel">
                            <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() {
        this._updateDefPreview();
        await this._loadLandUses();
        await this._loadLayers();
        this._bindEvents();
        // empty-first: تا کاربر «اعمال» را نزند، چیزی لود نمی‌شود
    }

    /* لیست لایه‌ها برای فیلتر */
    async _loadLayers() {
        try {
            const res = await this.api.get('gis/layers-list');
            const sel = this.ref('layerSel');
            this._layers = res?.data ?? [];
            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 _loadLandUses() {
        try {
            const res = await this.api.get('gis/dashboard/land-uses');
            const sel = this.ref('landUseSel');
            if (!sel) return;
            (res?.data ?? []).forEach(u => {
                const o = document.createElement('option');
                o.value = u.value;
                o.textContent = `${u.value} (${u.count})`;
                if (this._filters.land_use === u.value) o.selected = true;
                sel.appendChild(o);
            });
        } catch {}
    }

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

    _buildParams() {
        const f = this._filters;
        const p = { level: this._level };

        /* context drill از مسیر */
        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;

        /* فیلترها — def فقط وقتی حداقل یکی >0 باشد (۰/۰/۰ = همه ملک‌ها) */
        const db = +f.def_building || 0, du = +f.def_units || 0, ds = +f.def_shops || 0;
        if (f._def_applied && (db > 0 || du > 0 || ds > 0)) {
            p.def_building = db;
            p.def_units    = du;
            p.def_shops    = ds;
        }
        if (f.statuses?.length) p.statuses = f.statuses.join(',');
        if (f.land_use)         p.land_use = f.land_use;
        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-down ── */
    _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 { /* block */
            this._openBlockOnMap(row);
            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' : 'block';
        }
        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, active) => active
            ? `<span style="font-weight:800;color:#1e293b;">${this.esc(txt)}</span>`
            : `<a data-crumb="${idx}" style="color:#3b82f6;cursor:pointer;text-decoration:none;">${this.esc(txt)}</a>`;

        const parts = [ link('🗺️ مناطق', -1, this._level === 'district') ];
        this._path.forEach((c, i) => {
            const isLast = (i === this._path.length - 1) && this._level === 'block'
                ? false
                : (i === this._path.length - 1);
            parts.push(sep, link(c.label, i, false));
        });
        // برچسب سطح فعلی
        const levelLbl = this._level === 'district' ? '' : this._level === 'neighborhood' ? ' — محلات' : ' — بلوک‌ها';
        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)))
        );
    }

    /* ── اتصال به نقشه: باز کردن تب «نقشه هوشمند» روی این بلوک ── */
    _openBlockOnMap(row) {
        const f = this._filters;
        const payload = {
            block: row.key_id,
            filters: {
                land_use: f.land_use || '',
                area_min: f.area_min || null,
                area_max: f.area_max || null,
                statuses: f.statuses || [],
                def_building: (+f.def_building > 0) ? +f.def_building : -1,
                def_units:    (+f.def_units    > 0) ? +f.def_units    : -1,
                def_shops:    (+f.def_shops    > 0) ? +f.def_shops    : -1,
                layer_id: f.layer_id || '',
            },
        };
        try { sessionStorage.setItem('acc_gis_focus_block', JSON.stringify(payload)); } catch {}
        this.eventBus?.emit('tab:open', { key: 'gis', params: { focusBlock: row.key_id } });
    }

    /* ────────────────────── KPIs (جمع سطح جاری) ── */
    _updateKPIs() {
        const rows = this._data || [];
        const sum  = k => rows.reduce((a, r) => a + (+r[k] || 0), 0);
        const n    = v => (+v || 0).toLocaleString('fa-IR');
        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')));
        // در سطح منطقه/محله شمارش بر حسب بلوک است؛ متوسط مساحت معنا ندارد
        this._setRef('kArea',  this._level === 'block' ? n(rows.length) : n(sum('total_blocks')));
    }

    /* ────────────────────── cards ── */
    _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)
        );

        const sortCol = 'total_parcels';
        rows.sort((a, b) => {
            const av = parseFloat(a[sortCol] ?? 0);
            const bv = parseFloat(b[sortCol] ?? 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 isBlock = this._level === 'block';

        /* عدد بزرگ کارت: همیشه تعداد ملک (پارسل) */
        const headNum  = +r.total_parcels || 0;
        const headUnit = 'ملک';

        const bldg = +r.cnt_building  || 0;
        const apt  = +r.cnt_apartment || 0;
        const shop = +r.cnt_shop      || 0;
        const 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 foot = isBlock
            ? `<span class="red-accent-tag" style="background:#3b82f620;color:#3b82f6">🗺️ نمایش روی نقشه</span>`
            : `<span class="red-accent-tag" style="background:${accentColor}20;color:${accentColor}">${accentLabel}</span>
               <span class="red-avg">${n(+r.total_blocks||0)} بلوک · کلیک برای ${this._level === 'district' ? 'محلات' : 'بلوک‌ها'}</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">${headUnit}</span>
                </div>
            </div>

            <div class="red-stats">
                <div class="red-stat" style="--sc:${TYPE_CFG[0].color};--sb:${TYPE_CFG[0].bg}">
                    <span class="red-stat-n">${n(bldg)}</span><span class="red-stat-l">ساختمان</span>
                </div>
                <div class="red-stat" style="--sc:${TYPE_CFG[1].color};--sb:${TYPE_CFG[1].bg}">
                    <span class="red-stat-n">${n(apt)}</span><span class="red-stat-l">آپارتمان</span>
                </div>
                <div class="red-stat" style="--sc:${TYPE_CFG[2].color};--sb:${TYPE_CFG[2].bg}">
                    <span class="red-stat-n">${n(shop)}</span><span class="red-stat-l">مغازه</span>
                </div>
                <div class="red-stat" style="--sc:${TYPE_CFG[3].color};--sb:${TYPE_CFG[3].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>`;
    }

    /* ────────────────────── detail modal ── */
    _showDetail(r) {
        const overlay = this.ref('detailOverlay');
        const modal   = this.ref('detailModal');
        if (!overlay || !modal) return;

        const n = v => (+v||0).toLocaleString('fa-IR');
        const total = +r.total_parcels || 1;

        const statusRows = STATUS_CFG.map(s => {
            const cnt = +(r[`status_${s.key}`]??0);
            if (!cnt) return '';
            const pct = Math.round(cnt / total * 100);
            return `<div class="red-dm-row">
                <span style="display:flex;align-items:center;gap:6px">
                    <span style="width:10px;height:10px;border-radius:50%;background:${s.color};display:inline-block"></span>
                    ${s.label}
                </span>
                <span><b>${n(cnt)}</b> <small>(${pct}٪)</small></span>
            </div>`;
        }).join('');

        modal.innerHTML = `
        <div class="red-dm-hdr">
            <div>
                <h3 class="red-dm-title">${this.esc(r.neighborhood_name||'—')}</h3>
                <span class="red-dm-sub">${this.esc(r.district_name||'')}</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">
                    <div class="red-dm-bsv">${n(r.total_parcels)}</div>
                    <div class="red-dm-bsl">کل ملک</div>
                </div>
                <div class="red-dm-bs" style="border-color:#6366f1;background:#eef2ff">
                    <div class="red-dm-bsv" style="color:#6366f1">${n(r.cnt_building)}</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.cnt_apartment)}</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.cnt_shop)}</div>
                    <div class="red-dm-bsl">🏪 مغازه</div>
                </div>
                <div class="red-dm-bs" style="border-color:#10b981;background:#d1fae5">
                    <div class="red-dm-bsv" style="color:#10b981">${n(r.cnt_land_only)}</div>
                    <div class="red-dm-bsl">🌿 زمین</div>
                </div>
            </div>

            <div class="red-dm-section">مساحت</div>
            <div class="red-dm-row">
                <span>متوسط زمین</span>
                <b>${r.avg_area ? Math.round(+r.avg_area).toLocaleString('fa-IR') : '—'} م²</b>
            </div>
            <div class="red-dm-row">
                <span>مساحت کل</span>
                <b>${r.total_area ? Math.round(+r.total_area/10000).toLocaleString('fa-IR') : '—'} هکتار</b>
            </div>

            <div class="red-dm-section">توزیع وضعیت</div>
            ${statusRows}
            <div class="red-sbar" style="height:10px;border-radius:5px;margin-top:10px">
                ${STATUS_CFG.map(s => {
                    const cnt = +(r[`status_${s.key}`]??0);
                    const w   = Math.round(cnt/total*100);
                    return w ? `<div style="width:${w}%;background:${s.color};height:100%" title="${s.label}"></div>` : '';
                }).join('')}
            </div>
        </div>`;

        overlay.style.display = 'flex';
        modal.querySelector('[data-ref="detailClose"]')?.addEventListener('click', () => {
            overlay.style.display = 'none';
        });
    }

    /* ────────────────────── filter preview ── */
    _updateDefPreview() {
        const b = parseInt(this.ref('defBuilding')?.value)||0;
        const u = parseInt(this.ref('defUnits')?.value)||0;
        const s = parseInt(this.ref('defShops')?.value)||0;
        const el = this.ref('defPreview');
        if (!el) return;
        if (b===0 && u===0 && s===0) {
            el.textContent = '🌿 همه ملک‌ها';
            el.style.color = '#10b981';
        } else {
            const parts = [];
            if (b) parts.push(`${b}+ ساختمان`);
            if (u) parts.push(`${u}+ آپارتمان`);
            if (s) parts.push(`${s}+ مغازه`);
            el.textContent = '🔍 ' + parts.join(' | ');
            el.style.color = '#6366f1';
        }
    }

    /* ────────────────────── events ── */
    _bindEvents() {
        this.ref('searchInput')?.addEventListener('input', e => {
            this._search = e.target.value;
            this._renderCards();
        });
        this.ref('sortSel')?.addEventListener('change', e => {
            this._sortCol = e.target.value;
            this._renderCards();
        });
        this.ref('sortDirBtn')?.addEventListener('click', () => {
            this._sortDir = this._sortDir === 'desc' ? 'asc' : 'desc';
            this.ref('sortDirBtn').textContent = this._sortDir === 'desc' ? '↓' : '↑';
            this._renderCards();
        });
        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());
        ['defBuilding','defUnits','defShops'].forEach(r =>
            this.ref(r)?.addEventListener('input', () => this._updateDefPreview())
        );
        this.ref('detailOverlay')?.addEventListener('click', e => {
            if (e.target === this.ref('detailOverlay'))
                this.ref('detailOverlay').style.display = 'none';
        });
    }

    _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 = {
            def_building: parseInt(this.ref('defBuilding')?.value)||0,
            def_units:    parseInt(this.ref('defUnits')?.value)||0,
            def_shops:    parseInt(this.ref('defShops')?.value)||0,
            _def_applied: true,
            statuses,
            land_use: this.ref('landUseSel')?.value||'',
            area_min: parseFloat(this.ref('areaMin')?.value)||null,
            area_max: parseFloat(this.ref('areaMax')?.value)||null,
        };
        this._filters.layer_id = this.ref('layerSel')?.value || '';
        const dot = this.ref('filterDot');
        if (dot) dot.style.display = this._hasActiveFilter() ? 'inline-block' : 'none';
        this._saveFilters();
        this._toggleFilter(false);

        /* شروع/ریستِ drill-down از سطح منطقه */
        this._started = true;
        this._path    = [];
        this._level   = 'district';
        this._load();
    }

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

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

    _loadFilters()  { try { return JSON.parse(localStorage.getItem(LS_KEY))||{}; } catch { return {}; } }
    _saveFilters()  { try { localStorage.setItem(LS_KEY, JSON.stringify(this._filters)); } 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('realestate', RealEstateDashboardView);
