/**
 * melk-investor-panel.js — پورتفوی سرمایه‌گذار · معیار خرید · هشدار آگهی · کارشناسی
 */

const WEALTH_LABELS = {
    premium: 'پریمیوم',
    ultra: 'اولترا',
    institutional: 'نهادی',
};

function fmtPrice(n) {
    if (n == null || n === '' || Number(n) <= 0) return '—';
    return Number(n).toLocaleString('fa-IR') + ' ریال';
}

function fmtArea(n) {
    if (n == null || n === '') return '—';
    return Number(n).toLocaleString('fa-IR') + ' م²';
}

export function renderInvestorPanel(esc) {
    return `<div class="em-ext-panel em-investor-panel" data-ref="investorPanel">
        <div class="em-ext-intro em-ext-intro--investor">
            <div class="em-ext-intro__text">
                <h2>💎 پورتفوی سرمایه‌گذاری</h2>
                <p>تعریف شرایط خرید و مشارکت · هشدار آگهی بر اساس منطقه و بودجه · درخواست کارشناسی</p>
            </div>
            <div class="em-ext-kpis" data-ref="invKpis"></div>
        </div>

        <div class="em-investor-tabs" data-ref="invSubTabs">
            <button type="button" class="em-investor-tab em-investor-tab--active" data-inv-tab="alerts">🔔 هشدارها</button>
            <button type="button" class="em-investor-tab" data-inv-tab="criteria">📋 معیارها</button>
            <button type="button" class="em-investor-tab" data-inv-tab="experts">👨‍⚕️ کارشناسان</button>
            <button type="button" class="em-investor-tab" data-inv-tab="requests">📨 درخواست‌ها</button>
            <button type="button" class="em-investor-tab" data-inv-tab="profile">👤 پروفایل</button>
        </div>

        <div data-ref="invPaneAlerts" class="em-investor-pane">
            <div class="em-ext-toolbar">
                <label class="em-check-label"><input type="checkbox" data-ref="invUnseenOnly"> فقط خوانده‌نشده</label>
                <button type="button" class="red-btn" data-ref="reloadAlertsBtn">↻</button>
            </div>
            <div class="em-ext-list" data-ref="alertsList"></div>
        </div>

        <div data-ref="invPaneCriteria" class="em-investor-pane" style="display:none">
            <div class="em-ext-toolbar">
                <button type="button" class="red-btn red-btn--primary" data-ref="newCriteriaBtn">➕ معیار جدید</button>
                <button type="button" class="red-btn" data-ref="reloadCriteriaBtn">↻</button>
            </div>
            <div class="em-investor-form" data-ref="criteriaForm" style="display:none"></div>
            <div class="em-ext-list" data-ref="criteriaList"></div>
        </div>

        <div data-ref="invPaneExperts" class="em-investor-pane" style="display:none">
            <p class="em-form-bank-hint">کارشناسان شهرداری، ثبت، حقوقی و مالی برای اطمینان از صحت سرمایه‌گذاری</p>
            <div class="em-investor-expert-grid" data-ref="expertsGrid"></div>
        </div>

        <div data-ref="invPaneRequests" class="em-investor-pane" style="display:none">
            <div class="em-ext-toolbar">
                <button type="button" class="red-btn red-btn--primary" data-ref="newExpertReqBtn">➕ درخواست کارشناسی</button>
                <button type="button" class="red-btn" data-ref="reloadReqBtn">↻</button>
            </div>
            <div class="em-investor-form" data-ref="expertReqForm" style="display:none"></div>
            <div class="em-ext-list" data-ref="requestsList"></div>
        </div>

        <div data-ref="invPaneProfile" class="em-investor-pane" style="display:none">
            <div class="em-investor-form" data-ref="profileForm"></div>
        </div>
    </div>`;
}

export async function bindInvestorPanel(root, { request, esc, toast }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    let meta = { deal_types: {}, expert_types: {}, geo: { districts: [], neighborhoods: [] } };
    let criteria = [];
    let matches = [];
    let experts = [];
    let requests = [];
    let editingCriteriaId = null;

    try {
        const res = await request('GET', 'melk/investor/meta');
        meta = res?.data ?? meta;
    } catch { /* */ }

    function switchInvTab(tab) {
        root.querySelectorAll('.em-investor-tab').forEach(b =>
            b.classList.toggle('em-investor-tab--active', b.dataset.invTab === tab));
        ['alerts', 'criteria', 'experts', 'requests', 'profile'].forEach(k => {
            const el = $(`invPane${k.charAt(0).toUpperCase()}${k.slice(1)}`);
            if (el) el.style.display = k === tab ? '' : 'none';
        });
    }

    root.querySelectorAll('[data-inv-tab]').forEach(btn => {
        btn.addEventListener('click', () => switchInvTab(btn.dataset.invTab));
    });

    function renderKpis() {
        const unseen = matches.filter(m => !m.seen_at).length;
        $('invKpis').innerHTML = `
            <span class="em-kpi-chip">🔔 ${unseen} هشدار جدید</span>
            <span class="em-kpi-chip">📋 ${criteria.length} معیار</span>
            <span class="em-kpi-chip">📨 ${requests.filter(r => r.status === 'pending').length} در انتظار</span>`;
        const tabBtn = root.closest('.em-wrap')?.querySelector('[data-tab="investor"]');
        if (tabBtn && unseen > 0) {
            tabBtn.textContent = `💎 سرمایه‌گذار (${unseen})`;
        }
    }

    function dealLabel(k) {
        return meta.deal_types?.[k] || k;
    }

    function districtName(id) {
        const d = (meta.geo?.districts || []).find(x => Number(x.id) === Number(id));
        return d ? d.name : `منطقه ${id}`;
    }

    function neighName(id) {
        const n = (meta.geo?.neighborhoods || []).find(x => Number(x.id) === Number(id));
        return n ? n.name : `محله ${id}`;
    }

    async function loadMatches() {
        const unseenOnly = $('invUnseenOnly')?.checked;
        const q = unseenOnly ? '?unseen=1' : '';
        try {
            const res = await request('GET', `melk/investor/matches${q}`);
            matches = res?.data ?? [];
        } catch (e) {
            matches = [];
            toast(e.message || 'خطا در بارگذاری هشدارها', true);
        }
        renderAlerts();
        renderKpis();
    }

    function renderAlerts() {
        const el = $('alertsList');
        if (!matches.length) {
            el.innerHTML = '<div class="em-empty">هنوز آگهی منطبق با معیارهای شما ثبت نشده — معیار جدید تعریف کنید.</div>';
            return;
        }
        el.innerHTML = matches.map(m => {
            const isNew = !m.seen_at;
            return `<article class="em-ext-card${isNew ? ' em-ext-card--new' : ''}" data-match-id="${m.id}">
                <div class="em-ext-card__head">
                    <strong>${esc(m.listing_title)}</strong>
                    ${isNew ? '<span class="em-badge em-badge--new">جدید</span>' : ''}
                    <span class="em-badge">امتیاز ${m.match_score}%</span>
                </div>
                <div class="em-ext-card__meta">
                    <span>${esc(dealLabel(m.deal_type))}</span>
                    <span>${fmtArea(m.area_sqm)}</span>
                    <span>${fmtPrice(m.price)}</span>
                    <span>${esc(districtName(m.district_id))} · ${esc(neighName(m.neighborhood_id))}</span>
                </div>
                <p class="em-ext-card__sub">معیار: ${esc(m.criteria_title || '—')}</p>
                <div class="em-ext-actions">
                    ${isNew ? `<button type="button" class="red-btn red-btn--sm" data-mark-seen="${m.id}">✓ خواندم</button>` : ''}
                    <button type="button" class="red-btn red-btn--primary red-btn--sm" data-expert-for="${m.listing_id}" data-match="${m.id}">👨‍⚕️ کارشناسی</button>
                </div>
            </article>`;
        }).join('');

        el.querySelectorAll('[data-mark-seen]').forEach(btn => {
            btn.addEventListener('click', async () => {
                try {
                    await request('POST', `melk/investor/matches/${btn.dataset.markSeen}/seen`);
                    await loadMatches();
                } catch (e) { toast(e.message, true); }
            });
        });
        el.querySelectorAll('[data-expert-for]').forEach(btn => {
            btn.addEventListener('click', () => openExpertForm(parseInt(btn.dataset.expertFor, 10), parseInt(btn.dataset.match, 10)));
        });
    }

    async function loadCriteria() {
        try {
            const res = await request('GET', 'melk/investor/criteria');
            criteria = res?.data ?? [];
        } catch { criteria = []; }
        renderCriteriaList();
        renderKpis();
    }

    function criteriaFormHtml(c = null) {
        const d = c || {};
        const dealOpts = Object.entries(meta.deal_types || {}).map(([k, v]) =>
            `<label class="em-check-label"><input type="checkbox" name="deal_types" value="${esc(k)}" ${(d.deal_types || []).includes(k) ? 'checked' : ''}> ${esc(v)}</label>`
        ).join('');
        const distOpts = (meta.geo?.districts || []).map(x =>
            `<label class="em-check-label"><input type="checkbox" name="district_ids" value="${x.id}" ${(d.district_ids || []).map(Number).includes(Number(x.id)) ? 'checked' : ''}> ${esc(x.name)}</label>`
        ).join('');
        const neighOpts = (meta.geo?.neighborhoods || []).map(x =>
            `<label class="em-check-label"><input type="checkbox" name="neighborhood_ids" value="${x.id}" ${(d.neighborhood_ids || []).map(Number).includes(Number(x.id)) ? 'checked' : ''}> ${esc(x.name)} (${esc(districtName(x.district_id))})</label>`
        ).join('');
        return `<h3>${c ? 'ویرایش معیار' : 'معیار سرمایه‌گذاری جدید'}</h3>
            <div class="em-form-row"><label>عنوان</label><input class="red-inp" name="title" value="${esc(d.title || '')}" placeholder="مثلاً زمین منطقه ۱ — محله ۷"></div>
            <div class="em-form-row"><label>نوع معامله</label><div class="em-check-group">${dealOpts}</div></div>
            <div class="em-form-row"><label>مناطق</label><div class="em-check-group">${distOpts || '<span class="em-empty">—</span>'}</div></div>
            <div class="em-form-row"><label>محله‌ها</label><div class="em-check-group em-check-group--scroll">${neighOpts || '<span class="em-empty">—</span>'}</div></div>
            <div class="em-form-row em-form-row--2">
                <div><label>حداقل متراژ (m²)</label><input class="red-inp" name="min_area_sqm" type="number" value="${esc(d.min_area_sqm ?? '')}"></div>
                <div><label>حداکثر بودجه (ریال)</label><input class="red-inp" name="budget_max" type="number" value="${esc(d.budget_max ?? '')}"></div>
            </div>
            <div class="em-form-row"><label>یادداشت</label><textarea class="red-inp" name="notes" rows="2">${esc(d.notes || '')}</textarea></div>
            <label class="em-check-label"><input type="checkbox" name="alert_active" ${d.alert_active !== false ? 'checked' : ''}> هشدار فعال — در صورت آگهی مناسب اطلاع دهید</label>
            <div class="em-ext-actions">
                <button type="button" class="red-btn red-btn--primary" data-ref="saveCriteriaBtn">💾 ذخیره</button>
                <button type="button" class="red-btn" data-ref="cancelCriteriaBtn">انصراف</button>
            </div>`;
    }

    function renderCriteriaList() {
        const el = $('criteriaList');
        if (!criteria.length) {
            el.innerHTML = '<div class="em-empty">هنوز معیاری تعریف نشده. مثال: منطقه ۱، محلات ۷ و ۱۰، حداقل ۱۰۰۰ متر.</div>';
            return;
        }
        el.innerHTML = criteria.map(c => `<article class="em-ext-card">
            <div class="em-ext-card__head">
                <strong>${esc(c.title)}</strong>
                <span class="em-badge">${c.alert_active ? '🔔 فعال' : '⏸ غیرفعال'}</span>
            </div>
            <div class="em-ext-card__meta">
                <span>${(c.deal_types || []).map(dealLabel).join(' · ') || 'همه'}</span>
                <span>حداقل ${fmtArea(c.min_area_sqm)}</span>
                <span>بودجه تا ${fmtPrice(c.budget_max)}</span>
            </div>
            <p class="em-ext-card__sub">${esc(c.notes || '')}</p>
            <div class="em-ext-actions">
                <button type="button" class="red-btn red-btn--sm" data-edit-crit="${c.id}">✏️ ویرایش</button>
                <button type="button" class="red-btn red-btn--sm" data-del-crit="${c.id}">🗑 حذف</button>
            </div>
        </article>`).join('');

        el.querySelectorAll('[data-edit-crit]').forEach(btn => {
            btn.addEventListener('click', () => {
                const c = criteria.find(x => String(x.id) === btn.dataset.editCrit);
                editingCriteriaId = c?.id || null;
                const form = $('criteriaForm');
                form.style.display = '';
                form.innerHTML = criteriaFormHtml(c);
                bindCriteriaForm();
            });
        });
        el.querySelectorAll('[data-del-crit]').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('حذف این معیار؟')) return;
                try {
                    await request('DELETE', `melk/investor/criteria/${btn.dataset.delCrit}`);
                    await loadCriteria();
                    await loadMatches();
                    toast('معیار حذف شد');
                } catch (e) { toast(e.message, true); }
            });
        });
    }

    function collectChecks(form, name) {
        return [...form.querySelectorAll(`input[name="${name}"]:checked`)].map(i => i.value);
    }

    function bindCriteriaForm() {
        $('saveCriteriaBtn')?.addEventListener('click', async () => {
            const form = $('criteriaForm');
            const body = {
                title: form.querySelector('[name=title]')?.value?.trim(),
                deal_types: collectChecks(form, 'deal_types'),
                district_ids: collectChecks(form, 'district_ids').map(Number),
                neighborhood_ids: collectChecks(form, 'neighborhood_ids').map(Number),
                min_area_sqm: form.querySelector('[name=min_area_sqm]')?.value || null,
                budget_max: form.querySelector('[name=budget_max]')?.value || null,
                notes: form.querySelector('[name=notes]')?.value || '',
                alert_active: form.querySelector('[name=alert_active]')?.checked ? 1 : 0,
            };
            try {
                if (editingCriteriaId) {
                    await request('PUT', `melk/investor/criteria/${editingCriteriaId}`, body);
                } else {
                    await request('POST', 'melk/investor/criteria', body);
                }
                form.style.display = 'none';
                editingCriteriaId = null;
                await loadCriteria();
                await loadMatches();
                toast('معیار ذخیره شد');
            } catch (e) { toast(e.message, true); }
        }, { once: true });
        $('cancelCriteriaBtn')?.addEventListener('click', () => {
            $('criteriaForm').style.display = 'none';
            editingCriteriaId = null;
        }, { once: true });
    }

    async function loadExperts() {
        try {
            const res = await request('GET', 'melk/investor/experts');
            experts = res?.data ?? [];
        } catch { experts = []; }
        const el = $('expertsGrid');
        if (!experts.length) {
            el.innerHTML = '<div class="em-empty">کارشناسی در سیستم یافت نشد.</div>';
            return;
        }
        el.innerHTML = experts.map(e => `<div class="em-investor-expert-card">
            <span class="em-investor-expert-icon">${esc(e.icon)}</span>
            <strong>${esc(e.name)}</strong>
            <small>${esc(e.expert_label)}</small>
            <code>${esc(e.login)}</code>
        </div>`).join('');
    }

    async function loadRequests() {
        try {
            const res = await request('GET', 'melk/investor/expert-requests');
            requests = res?.data ?? [];
        } catch { requests = []; }
        renderRequests();
        renderKpis();
    }

    function renderRequests() {
        const el = $('requestsList');
        if (!requests.length) {
            el.innerHTML = '<div class="em-empty">درخواست کارشناسی ثبت نشده.</div>';
            return;
        }
        el.innerHTML = requests.map(r => {
            const types = (r.expert_types || []).map(t => meta.expert_types?.[t]?.label || t).join(' · ');
            const statusCls = r.status === 'answered' ? 'em-badge--ok' : 'em-badge--pending';
            return `<article class="em-ext-card">
                <div class="em-ext-card__head">
                    <strong>${esc(r.subject)}</strong>
                    <span class="em-badge ${statusCls}">${r.status === 'answered' ? '✅ پاسخ داده شد' : '⏳ در انتظار'}</span>
                </div>
                <div class="em-ext-card__meta"><span>${esc(types)}</span></div>
                <p class="em-ext-card__sub">${esc(r.description || '')}</p>
                ${r.response_text ? `<div class="em-investor-response"><strong>پاسخ کارشناس:</strong><pre>${esc(r.response_text)}</pre></div>` : ''}
            </article>`;
        }).join('');
    }

    function openExpertForm(listingId = null, matchId = null) {
        switchInvTab('requests');
        const form = $('expertReqForm');
        form.style.display = '';
        const typeChecks = Object.entries(meta.expert_types || {}).map(([k, v]) =>
            `<label class="em-check-label"><input type="checkbox" name="expert_types" value="${esc(k)}" ${['municipality', 'registry', 'legal'].includes(k) ? 'checked' : ''}> ${esc(v.icon || '')} ${esc(v.label || k)}</label>`
        ).join('');
        form.innerHTML = `<h3>درخواست کارشناسی</h3>
            <input type="hidden" name="listing_id" value="${listingId || ''}">
            <input type="hidden" name="match_id" value="${matchId || ''}">
            <div class="em-form-row"><label>موضوع</label><input class="red-inp" name="subject" placeholder="بررسی سند و بلامانع شهرداری"></div>
            <div class="em-form-row"><label>کارشناسان</label><div class="em-check-group">${typeChecks}</div></div>
            <div class="em-form-row"><label>توضیحات</label><textarea class="red-inp" name="description" rows="3"></textarea></div>
            <div class="em-ext-actions">
                <button type="button" class="red-btn red-btn--primary" data-ref="submitExpertBtn">📤 ارسال</button>
                <button type="button" class="red-btn" data-ref="cancelExpertBtn">انصراف</button>
            </div>`;
        $('submitExpertBtn')?.addEventListener('click', async () => {
            const body = {
                subject: form.querySelector('[name=subject]')?.value?.trim(),
                description: form.querySelector('[name=description]')?.value || '',
                expert_types: collectChecks(form, 'expert_types'),
                listing_id: form.querySelector('[name=listing_id]')?.value || null,
                match_id: form.querySelector('[name=match_id]')?.value || null,
            };
            try {
                await request('POST', 'melk/investor/expert-requests', body);
                form.style.display = 'none';
                await loadRequests();
                toast('درخواست ثبت شد');
            } catch (e) { toast(e.message, true); }
        }, { once: true });
        $('cancelExpertBtn')?.addEventListener('click', () => { form.style.display = 'none'; }, { once: true });
    }

    async function loadProfile() {
        let profile = {};
        try {
            const res = await request('GET', 'melk/investor/profile');
            profile = res?.data || {};
        } catch { /* */ }
        const form = $('profileForm');
        form.innerHTML = `<h3>پروفایل سرمایه‌گذار</h3>
            <div class="em-form-row"><label>عنوان / نام نمایشی</label><input class="red-inp" name="display_title" value="${esc(profile.display_title || '')}"></div>
            <div class="em-form-row"><label>سطح ثروت</label>
                <select class="red-sel" name="wealth_tier">
                    ${Object.entries(WEALTH_LABELS).map(([k, v]) => `<option value="${k}" ${profile.wealth_tier === k ? 'selected' : ''}>${v}</option>`).join('')}
                </select>
            </div>
            <div class="em-form-row"><label>تلفن</label><input class="red-inp" name="phone" value="${esc(profile.phone || '')}"></div>
            <div class="em-form-row"><label>بیو</label><textarea class="red-inp" name="bio" rows="3">${esc(profile.bio || '')}</textarea></div>
            <button type="button" class="red-btn red-btn--primary" data-ref="saveProfileBtn">💾 ذخیره پروفایل</button>`;
        $('saveProfileBtn')?.addEventListener('click', async () => {
            const body = {
                display_title: form.querySelector('[name=display_title]')?.value,
                wealth_tier: form.querySelector('[name=wealth_tier]')?.value,
                phone: form.querySelector('[name=phone]')?.value,
                bio: form.querySelector('[name=bio]')?.value,
            };
            try {
                await request('PUT', 'melk/investor/profile', body);
                toast('پروفایل ذخیره شد');
            } catch (e) { toast(e.message, true); }
        });
    }

    $('invUnseenOnly')?.addEventListener('change', () => loadMatches());
    $('reloadAlertsBtn')?.addEventListener('click', () => loadMatches());
    $('reloadCriteriaBtn')?.addEventListener('click', () => loadCriteria());
    $('reloadReqBtn')?.addEventListener('click', () => loadRequests());
    $('newCriteriaBtn')?.addEventListener('click', () => {
        editingCriteriaId = null;
        const form = $('criteriaForm');
        form.style.display = '';
        form.innerHTML = criteriaFormHtml(null);
        bindCriteriaForm();
    });
    $('newExpertReqBtn')?.addEventListener('click', () => openExpertForm());

    await Promise.all([loadMatches(), loadCriteria(), loadExperts(), loadRequests(), loadProfile()]);
}
