/**
 * ParcelsSection.js — لیست پرونده‌های ملک
 * جستجو + فیلتر + Pipeline Kanban
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_COLOR = {
    prospect:'#f59e0b', under_review:'#f97316', purchased:'#3b82f6',
    permitted:'#8b5cf6', under_construction:'#ef4444', completed:'#10b981', sold:'#6b7280',
};
const STATUS_LABEL = {
    prospect:'در کشف', under_review:'در بررسی', purchased:'خریداری‌شده',
    permitted:'مجوزگرفته', under_construction:'در ساخت', completed:'تکمیل‌شده', sold:'فروخته‌شده',
};
const PIPELINE = ['discovery','review','purchase','permit','construction','sale'];
const PIPELINE_LABEL = {discovery:'کشف',review:'بررسی',purchase:'خرید',permit:'مجوز',construction:'ساخت',sale:'فروش'};

export default class ParcelsSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._parcels   = [];
        this._districts = [];
        this._filter    = { status:'', district_id:'', search:'' };
        this._view      = 'list'; // 'list' | 'kanban'
    }

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

    async afterRender() {
        await this._loadDistricts();
        await this._showList();
    }

    async _loadDistricts() {
        try {
            const res = await this.api.get('/gis/districts');
            this._districts = res?.data ?? [];
        } catch { /* non-fatal */ }
    }

    async _showList() {
        const root = this.ref('root');
        const distOpts = `<option value="">همه مناطق</option>` +
            this._districts.map(d => `<option value="${d.id}">${this.escape(d.name)}</option>`).join('');

        root.innerHTML = `
            <div style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap;">
                <input type="text" class="acc-input" data-ref="searchInp" placeholder="🔍 جستجوی پلاک یا آدرس..."
                    style="min-width:200px;flex:1;" value="${this.escape(this._filter.search)}">
                <select class="event-type-filter" data-ref="distSel">
                    ${distOpts}
                </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--secondary acc-btn--sm" data-ref="kanbanBtn">📋 Kanban</button>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄</button>
                <span style="font-size:12px;color:#94a3b8;" data-ref="countLbl"></span>
            </div>
            <div data-ref="body"></div>
        `;
        this._bindRef();

        this.on(this.ref('searchInp'), 'input', () => { this._filter.search = this.ref('searchInp').value; this._loadList(); });
        this.on(this.ref('distSel'),   'change', () => { this._filter.district_id = this.ref('distSel').value; this._loadList(); });
        this.on(this.ref('statusSel'), 'change', () => { this._filter.status = this.ref('statusSel').value; this._loadList(); });
        this.on(this.ref('refreshBtn'),'click',  () => this._loadList());
        this.on(this.ref('kanbanBtn'), 'click',  () => this._view === 'list' ? this._renderKanban() : this._renderListView());

        await this._loadList();
    }

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

    async _loadList() {
        const body = this.ref('body');
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const params = {};
            if (this._filter.status)      params.status = this._filter.status;
            if (this._filter.district_id) params.district_id = this._filter.district_id;
            if (this._filter.search)      params.search = this._filter.search;
            const res = await this.api.get('/gis/parcels', params);
            this._parcels = res?.data ?? [];
            this.ref('countLbl').textContent = `${this._parcels.length} پرونده`;
            if (this._view === 'kanban') this._renderKanban();
            else this._renderListView();
        } catch {
            body.innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`;
        }
    }

    _renderListView() {
        this._view = 'list';
        const body = this.ref('body');
        if (!this._parcels.length) { body.innerHTML = `<div class="acc-empty">پرونده‌ای یافت نشد.</div>`; return; }
        body.innerHTML = '';
        this._parcels.forEach(p => {
            const card = document.createElement('div');
            card.className = 'parcel-list-card';
            card.style.borderRight = `4px solid ${STATUS_COLOR[p.status]||'#94a3b8'}`;
            card.innerHTML = `
                <div style="flex:1;min-width:0;">
                    <div style="font-weight:800;font-size:15px;color:#1e293b;margin-bottom:4px;">
                        پلاک ${this.escape(p.code||'—')}/${this.escape(p.sub_code||'—')}
                    </div>
                    <div style="font-size:12px;color:#64748b;margin-bottom:6px;">
                        ${this.escape(p.district_name||'')} ${p.neighborhood_name ? '← '+this.escape(p.neighborhood_name) : ''}
                    </div>
                    <div style="font-size:12px;color:#475569;">${this.escape(p.address||'')}</div>
                </div>
                <div style="display:flex;flex-direction:column;align-items:flex-end;gap:6px;min-width:100px;">
                    <span style="background:${STATUS_COLOR[p.status]||'#94a3b8'};color:#fff;border-radius:8px;padding:3px 10px;font-size:11px;font-weight:700;">
                        ${STATUS_LABEL[p.status]||p.status}
                    </span>
                    ${p.assigned_user_name ? `<span style="font-size:11px;color:#64748b;">👤 ${this.escape(p.assigned_user_name)}</span>` : ''}
                    ${p.locked_by_name ? `<span style="font-size:11px;color:#d97706;">🔒 ${this.escape(p.locked_by_name)}</span>` : ''}
                </div>
            `;
            body.appendChild(card);
        });
    }

    _renderKanban() {
        this._view = 'kanban';
        const body = this.ref('body');
        body.innerHTML = `
            <div class="gis-kanban">
                ${PIPELINE.map(stage => {
                    const items = this._parcels.filter(p => p.pipeline_stage === stage);
                    return `
                    <div class="gis-kanban-col">
                        <div class="gis-kanban-col__header">
                            ${PIPELINE_LABEL[stage]}
                            <span class="gis-kanban-count">${items.length}</span>
                        </div>
                        <div class="gis-kanban-col__body">
                            ${items.map(p => `
                                <div class="gis-kanban-card" style="border-top:3px solid ${STATUS_COLOR[p.status]||'#94a3b8'}">
                                    <div class="gis-kanban-card__title">پلاک ${this.escape(p.code||'—')}</div>
                                    <div class="gis-kanban-card__meta">${this.escape(p.district_name||'')} ${p.neighborhood_name?'← '+this.escape(p.neighborhood_name):''}</div>
                                    ${p.assigned_user_name ? `<div class="gis-kanban-card__user">👤 ${this.escape(p.assigned_user_name)}</div>` : ''}
                                </div>`).join('')}
                        </div>
                    </div>`;
                }).join('')}
            </div>`;
    }
}
