/**
 * melk-listings-panel.js — بازار ملک با بانک فرم استاندارد
 */
import { renderFormSections, collectFormData, validateRequired } from './melk-form-renderer.js';

export function renderListingsPanel(esc, { canPublish = true } = {}) {
    return `<div class="em-ext-panel em-listings-panel" data-ref="listingsPanel">
        <div class="em-ext-intro em-ext-intro--listings">
            <div class="em-ext-intro__text">
                <h2>🏠 بازار ملک</h2>
                <p>انتخاب فرم استاندارد → تکمیل اطلاعات → انتخاب مخاطب</p>
            </div>
            <div class="em-ext-kpis" data-ref="listingKpis"></div>
        </div>
        <div class="em-ext-toolbar">
            <h2 class="em-ext-title">فهرست آگهی‌ها</h2>
            <select class="red-sel" data-ref="dealFilter"><option value="">همه معاملات</option></select>
            <select class="red-sel" data-ref="propFilter"><option value="">همه املاک</option></select>
            <button type="button" class="red-btn" data-ref="myListingsBtn">آگهی‌های من</button>
            ${canPublish ? '<button type="button" class="red-btn red-btn--primary" data-ref="newListingBtn">➕ آگهی جدید</button>' : ''}
            <button type="button" class="red-btn" data-ref="reloadListingsBtn">↻</button>
        </div>

        <div class="em-listing-wizard" data-ref="listingWizard" style="display:none">
            <div class="em-wizard-steps">
                <span class="em-wiz-step em-wiz-step--active" data-step="1">۱. انتخاب فرم</span>
                <span class="em-wiz-step" data-step="2">۲. تکمیل اطلاعات</span>
                <span class="em-wiz-step" data-step="3">۳. مخاطبان</span>
            </div>

            <div data-ref="stepFormBank" class="em-wizard-pane">
                <h3>📚 بانک فرم‌های استاندارد آگهی</h3>
                <p class="em-form-bank-hint">فرم مناسب نوع معامله را انتخاب کنید — فیلدهای الزامی طبق استاندارد RESO / بین‌المللی</p>
                <div class="em-form-bank-grid" data-ref="formBankGrid"></div>
            </div>

            <div data-ref="stepFormFill" class="em-wizard-pane" style="display:none">
                <div class="em-selected-form-head" data-ref="selectedFormHead"></div>
                <div data-ref="dynamicFormFields"></div>
                <div class="em-ext-actions">
                    <button type="button" class="red-btn" data-ref="backToBankBtn">← بازگشت به بانک فرم</button>
                    <button type="button" class="red-btn red-btn--primary" data-ref="toAudienceBtn">ادامه → مخاطبان</button>
                </div>
            </div>

            <div data-ref="stepAudience" class="em-wizard-pane" style="display:none">
                <fieldset class="em-vis-fieldset em-audience-fieldset">
                    <legend>🔒 مخاطبان — چه کسانی این آگهی را ببینند؟</legend>
                    <select class="red-sel" data-ref="lstVisMode"></select>
                    <p class="em-vis-hint" data-ref="lstVisHint"></p>
                    <div data-ref="lstVisGeo" class="em-vis-block" style="display:none">
                        <label>مناطق مخاطب</label>
                        <div data-ref="lstDistrictSelected" class="em-vis-picks"></div>
                        <div data-ref="lstDistrictPickBtns" class="em-vis-pick-btns"></div>
                        <label>محلات مخاطب</label>
                        <div data-ref="lstNeighSelected" class="em-vis-picks"></div>
                        <div data-ref="lstNeighPickBtns" class="em-vis-pick-btns"></div>
                    </div>
                    <div data-ref="lstVisRoles" class="em-vis-roles em-vis-block" style="display:none"></div>
                    <div data-ref="lstVisUsers" class="em-vis-block" style="display:none">
                        <div class="em-user-add-row">
                            <input class="red-inp" data-ref="lstUserQ" placeholder="جستجو نام یا یوزرنیم...">
                            <input class="red-inp" data-ref="lstUserLogin" placeholder="یوزرنیم: melk_agent" dir="ltr">
                            <button type="button" class="red-btn" data-ref="lstAddUserBtn">➕</button>
                        </div>
                        <div data-ref="lstUserPicks" class="em-vis-picks"></div>
                        <div data-ref="lstUserResults" class="em-user-results"></div>
                    </div>
                </fieldset>
                <div class="em-ext-actions">
                    <button type="button" class="red-btn" data-ref="backToFillBtn">← بازگشت</button>
                    <button type="button" class="red-btn red-btn--primary" data-ref="saveListingBtn">📢 انتشار آگهی</button>
                    <button type="button" class="red-btn" data-ref="cancelListingBtn">انصراف</button>
                </div>
            </div>
        </div>

        <div class="em-ext-list" data-ref="listingList"></div>
        <div class="em-listing-modal" data-ref="listingModal" style="display:none">
            <div class="em-listing-modal__box">
                <div class="em-listing-modal__head">
                    <h3 data-ref="modalTitle">فرم پیوست آگهی</h3>
                    <button type="button" class="em-listing-modal__close" data-ref="modalClose">✕</button>
                </div>
                <div class="em-listing-modal__body" data-ref="modalBody"></div>
            </div>
        </div>
    </div>`;
}

export async function bindListingsPanel(root, { request, esc, toast, can }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    const canPublish = can('melk.manage') || can('melk.listings.publish') || can('*');
    let mineOnly = false;
    let options = { deal_types: [], property_types: [], modes: [], roles: [], rent_periods: [] };
    let districts = [];
    let neighborhoods = [];
    let formBank = [];
    let selectedForm = null;
    let selectedConfig = null;
    let visUserIds = [];
    let visUsernames = [];
    let visDistrictIds = [];
    let visNeighIds = [];
    let wizardStep = 1;

    try {
        const [optRes, distRes, bankRes] = await Promise.all([
            request('GET', 'melk/listing-visibility-options'),
            request('GET', 'gis/districts').catch(() => ({ data: [] })),
            request('GET', 'melk/listing-form-bank'),
        ]);
        options = optRes?.data ?? options;
        districts = distRes?.data ?? distRes?.districts ?? [];
        formBank = bankRes?.data ?? [];
    } catch { /* defaults */ }

    function fillSelect(sel, items, placeholder) {
        if (!sel) return;
        sel.innerHTML = placeholder ? `<option value="">${placeholder}</option>` : '';
        items.forEach(i => {
            sel.innerHTML += `<option value="${esc(i.key)}">${esc(i.label)}</option>`;
        });
    }

    fillSelect($('dealFilter'), options.deal_types, 'همه معاملات');
    fillSelect($('propFilter'), options.property_types, 'همه املاک');
    fillSelect($('lstVisMode'), options.modes, null);

    if ($('lstVisRoles')) {
        $('lstVisRoles').innerHTML = options.roles.map(r =>
            `<label><input type="checkbox" value="${esc(r.key)}"> ${esc(r.label)}</label>`).join('');
    }

    function setWizardStep(step) {
        wizardStep = step;
        root.querySelectorAll('.em-wiz-step').forEach(el => {
            el.classList.toggle('em-wiz-step--active', +el.dataset.step === step);
            el.classList.toggle('em-wiz-step--done', +el.dataset.step < step);
        });
        $('stepFormBank').style.display = step === 1 ? '' : 'none';
        $('stepFormFill').style.display = step === 2 ? '' : 'none';
        $('stepAudience').style.display = step === 3 ? '' : 'none';
    }

    function renderFormBank() {
        const grid = $('formBankGrid');
        if (!grid) return;
        if (!formBank.length) {
            grid.innerHTML = '<div class="em-empty-inline">فرمی در بانک یافت نشد</div>';
            return;
        }
        grid.innerHTML = formBank.map(f => `
            <button type="button" class="em-form-bank-card" data-form-key="${esc(f.form_key)}">
                <span class="em-form-bank-icon">${esc(f.icon || '📋')}</span>
                <strong>${esc(f.title)}</strong>
                <span class="em-form-bank-sub">${esc(f.subtitle || '')}</span>
                <span class="em-form-bank-std">${esc(f.standard || '')}</span>
                <span class="em-form-bank-meta">${f.section_count || 0} بخش · ${(f.min_fields || []).length} فیلد الزامی</span>
            </button>
        `).join('');
        grid.querySelectorAll('.em-form-bank-card').forEach(btn => {
            btn.addEventListener('click', () => selectForm(btn.dataset.formKey));
        });
    }

    async function selectForm(formKey) {
        try {
            const res = await request('GET', `melk/listing-form-config?form_key=${encodeURIComponent(formKey)}`);
            selectedConfig = res?.data;
            selectedForm = formBank.find(f => f.form_key === formKey) || selectedConfig;
            if (!selectedConfig) { toast('فرم یافت نشد', true); return; }
            $('selectedFormHead').innerHTML = `
                <div class="em-selected-form-badge">${esc(selectedConfig.icon || '📋')}</div>
                <div><strong>${esc(selectedConfig.title)}</strong>
                <span class="em-form-bank-sub">${esc(selectedConfig.subtitle || '')} · ${esc(selectedConfig.standard || '')}</span></div>`;
            $('dynamicFormFields').innerHTML = renderFormSections(selectedConfig.sections || [], esc, districts);
            bindDistrictNeighborhood();
            setWizardStep(2);
            $('listingWizard').scrollIntoView({ behavior: 'smooth', block: 'start' });
        } catch (e) { toast(e.message, true); }
    }

    function bindDistrictNeighborhood() {
        const distSel = $('dynamicFormFields')?.querySelector('[data-field="district_id"]');
        const neighSel = $('dynamicFormFields')?.querySelector('[data-field="neighborhood_id"]');
        if (!distSel || !neighSel) return;
        distSel.addEventListener('change', async () => {
            const did = distSel.value;
            neighSel.innerHTML = '<option value="">انتخاب محله</option>';
            if (!did) return;
            try {
                const res = await request('GET', `gis/neighborhoods?district_id=${did}`);
                (res?.data ?? []).forEach(n => {
                    neighSel.innerHTML += `<option value="${n.id}">${esc(n.name)}</option>`;
                });
            } catch { /* ignore */ }
        });
    }

    /* ── visibility helpers (unchanged) ── */
    function renderSelectedChips(container, items, type) {
        if (!container) return;
        container.innerHTML = items.map(item => {
            const label = type === 'district'
                ? (districts.find(d => +d.id === +item)?.name || `#${item}`)
                : (neighborhoods.find(n => +n.id === +item)?.name || `#${item}`);
            const val = type === 'user' ? item.login : item;
            const display = type === 'user' ? `@${esc(item.login)}` : esc(label);
            return `<span class="em-vis-chip" data-rm="${esc(String(val))}" data-type="${type}">${display} ✕</span>`;
        }).join('');
        container.querySelectorAll('[data-rm]').forEach(ch => {
            ch.addEventListener('click', () => {
                const t = ch.dataset.type;
                const v = ch.dataset.rm;
                if (t === 'district') visDistrictIds = visDistrictIds.filter(x => String(x) !== v);
                if (t === 'neigh') visNeighIds = visNeighIds.filter(x => String(x) !== v);
                if (t === 'user') { visUsernames = visUsernames.filter(x => x !== v); visUserIds = visUserIds.filter(x => String(x) !== v); }
                if (t === 'district') renderSelectedChips($('lstDistrictSelected'), visDistrictIds, 'district');
                if (t === 'neigh') renderSelectedChips($('lstNeighSelected'), visNeighIds, 'neigh');
                if (t === 'user') renderUserPicks();
            });
        });
    }

    function renderUserPicks() {
        renderSelectedChips($('lstUserPicks'), visUsernames.map(u => ({ login: u })), 'user');
    }

    function updateVisUI() {
        const mode = $('lstVisMode')?.value || 'network';
        const modeObj = options.modes.find(m => m.key === mode);
        if ($('lstVisHint')) $('lstVisHint').textContent = modeObj?.desc || '';
        $('lstVisGeo').style.display = mode === 'geo' ? '' : 'none';
        $('lstVisRoles').style.display = mode === 'role' ? '' : 'none';
        $('lstVisUsers').style.display = (mode === 'users' || mode === 'private') ? '' : 'none';
        if (mode === 'geo' && districts.length) {
            const btnBox = $('lstDistrictPickBtns');
            if (btnBox) {
                btnBox.innerHTML = districts.map(d =>
                    `<button type="button" class="em-vis-chip em-vis-chip--btn" data-pick-district="${d.id}">+ ${esc(d.name)}</button>`
                ).join('');
                btnBox.querySelectorAll('[data-pick-district]').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const id = +btn.dataset.pickDistrict;
                        if (!visDistrictIds.includes(id)) {
                            visDistrictIds.push(id);
                            renderSelectedChips($('lstDistrictSelected'), visDistrictIds, 'district');
                        }
                    });
                });
            }
        }
    }

    $('lstVisMode')?.addEventListener('change', updateVisUI);

    function listingCard(l) {
        const price = l.price ? `${Number(l.price).toLocaleString('fa-IR')} ت` : 'توافقی';
        const hasForm = l.form_template_key && (l.form_attachment?.length || Object.keys(l.form_data || {}).length);
        const formBadge = hasForm
            ? `<span class="em-badge em-badge--form">${esc(l.form_template_icon || '📋')} ${esc(l.form_template_title || 'فرم پیوست')}</span>`
            : `<span class="em-badge em-badge--warn">بدون فرم</span>`;
        const previewFields = (l.form_attachment || []).slice(0, 4);
        const previewHtml = previewFields.length
            ? `<div class="em-form-attach-preview">${previewFields.map(f =>
                `<div class="em-form-attach-row"><span>${esc(f.label)}</span><strong>${esc(f.value)}</strong></div>`
            ).join('')}</div>` : '';
        const viewBtn = hasForm
            ? `<button type="button" class="red-btn red-btn--sm em-view-form-btn" data-listing-id="${l.id}">📋 مشاهده فرم پیوست</button>`
            : '';
        return `<div class="em-ext-card em-ext-card--listing" data-listing-id="${l.id}">
            <div class="em-ext-card-head">
                <strong>${esc(l.title)}</strong>
                <span class="em-badge">${esc(l.deal_type_label)}</span>
                <span class="em-badge">${esc(l.property_type_label || '')}</span>
                <span class="em-badge em-badge--vis">👁 ${esc(l.visibility_label)}</span>
                ${formBadge}
            </div>
            <div class="em-ext-card-meta">
                <code dir="ltr">${esc(l.listing_key)}</code> · ${price}
                ${l.area_sqm ? ` · ${l.area_sqm} m²` : ''}
                ${l.rooms ? ` · ${l.rooms} خواب` : ''}
            </div>
            <div class="em-ext-card-meta">ناشر: ${esc(l.created_by_name)}</div>
            <p class="em-ext-desc">${esc((l.description || '').slice(0, 140))}</p>
            ${previewHtml}
            <div class="em-ext-card-actions">${viewBtn}</div>
        </div>`;
    }

    let listingsCache = [];

    function showFormModal(listing) {
        const modal = $('listingModal');
        const body = $('modalBody');
        if (!modal || !body || !listing) return;
        $('modalTitle').textContent = `${listing.form_template_icon || '📋'} ${listing.form_template_title || 'فرم پیوست'}`;
        const std = listing.form_template_standard
            ? `<p class="em-form-attach-std">${esc(listing.form_template_standard)}</p>` : '';
        const rows = (listing.form_attachment || []).map(f =>
            `<div class="em-form-attach-row em-form-attach-row--full"><span>${esc(f.label)}</span><strong>${esc(f.value)}</strong></div>`
        ).join('');
        body.innerHTML = `
            ${std}
            <div class="em-form-attach-sheet">${rows || '<p class="em-empty-inline">داده فرم موجود نیست</p>'}</div>
            <p class="em-form-attach-meta"><code dir="ltr">${esc(listing.listing_key)}</code> · ${esc(listing.title)}</p>`;
        modal.style.display = '';
    }

    function bindListingCardActions() {
        $('listingList')?.querySelectorAll('.em-view-form-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const id = +btn.dataset.listingId;
                const listing = listingsCache.find(x => x.id === id);
                if (listing) showFormModal(listing);
            });
        });
    }

    $('modalClose')?.addEventListener('click', () => { $('listingModal').style.display = 'none'; });
    $('listingModal')?.addEventListener('click', (e) => {
        if (e.target === $('listingModal')) $('listingModal').style.display = 'none';
    });

    async function load() {
        const list = $('listingList');
        list.innerHTML = '<div class="em-empty-inline">...</div>';
        const qs = new URLSearchParams();
        if ($('dealFilter')?.value) qs.set('deal_type', $('dealFilter').value);
        if ($('propFilter')?.value) qs.set('property_type', $('propFilter').value);
        if (mineOnly) qs.set('mine', '1');
        try {
            const res = await request('GET', `melk/listings${qs.toString() ? '?' + qs : ''}`);
            const items = res?.data ?? [];
            listingsCache = items;
            $('listingKpis').innerHTML = `<div class="em-kpi"><strong>${items.length}</strong><span>آگهی</span></div>`;
            list.innerHTML = items.length
                ? items.map(l => listingCard(l)).join('')
                : '<div class="em-empty-inline">آگهی‌ای یافت نشد</div>';
            bindListingCardActions();
        } catch (e) {
            list.innerHTML = `<div class="em-empty-inline">${esc(e.message)}</div>`;
        }
    }

    function resetWizard() {
        selectedForm = null;
        selectedConfig = null;
        visUserIds = []; visUsernames = []; visDistrictIds = []; visNeighIds = [];
        if ($('lstVisMode')) $('lstVisMode').value = 'network';
        $('lstUserResults').innerHTML = '';
        renderUserPicks();
        updateVisUI();
        setWizardStep(1);
    }

    $('newListingBtn')?.addEventListener('click', () => {
        if (!canPublish) { toast('دسترسی انتشار ندارید', true); return; }
        resetWizard();
        renderFormBank();
        $('listingWizard').style.display = '';
        $('listingWizard').scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
    $('cancelListingBtn')?.addEventListener('click', () => { $('listingWizard').style.display = 'none'; resetWizard(); });
    $('backToBankBtn')?.addEventListener('click', () => setWizardStep(1));
    $('backToFillBtn')?.addEventListener('click', () => setWizardStep(2));
    $('toAudienceBtn')?.addEventListener('click', () => {
        if (!selectedConfig) { toast('ابتدا فرم را انتخاب کنید', true); return; }
        const missing = validateRequired($('dynamicFormFields'), selectedConfig.sections || []);
        if (missing.length) { toast('فیلدهای الزامی: ' + missing.join('، '), true); return; }
        setWizardStep(3);
    });
    $('reloadListingsBtn')?.addEventListener('click', load);
    $('dealFilter')?.addEventListener('change', load);
    $('propFilter')?.addEventListener('change', load);
    $('myListingsBtn')?.addEventListener('click', () => {
        mineOnly = !mineOnly;
        $('myListingsBtn').classList.toggle('red-btn--primary', mineOnly);
        load();
    });

    $('lstAddUserBtn')?.addEventListener('click', () => {
        const login = $('lstUserLogin')?.value?.trim();
        if (login && !visUsernames.includes(login)) {
            visUsernames.push(login);
            $('lstUserLogin').value = '';
            renderUserPicks();
        }
    });

    const userQ = $('lstUserQ');
    if (userQ) {
        let t;
        userQ.addEventListener('input', () => {
            clearTimeout(t);
            t = setTimeout(async () => {
                const q = userQ.value.trim();
                const userRes = $('lstUserResults');
                if (!q) { userRes.innerHTML = ''; return; }
                const ur = await request('GET', `melk/users?q=${encodeURIComponent(q)}`);
                userRes.innerHTML = (ur?.data ?? []).map(u =>
                    `<button type="button" class="em-user-pick" data-uid="${u.id}" data-login="${esc(u.user_login)}">${esc(u.display_name)} <code>@${esc(u.user_login)}</code></button>`
                ).join('');
                userRes.querySelectorAll('.em-user-pick').forEach(pb => {
                    pb.addEventListener('click', () => {
                        const uid = +pb.dataset.uid;
                        const login = pb.dataset.login;
                        if (!visUserIds.includes(uid)) visUserIds.push(uid);
                        if (login && !visUsernames.includes(login)) visUsernames.push(login);
                        renderUserPicks();
                    });
                });
            }, 300);
        });
    }

    $('saveListingBtn')?.addEventListener('click', async () => {
        if (!selectedConfig) { toast('فرم انتخاب نشده', true); return; }
        const formData = collectFormData($('dynamicFormFields'));
        const mode = $('lstVisMode')?.value || 'network';
        const roles = mode === 'role'
            ? [...$('lstVisRoles').querySelectorAll('input:checked')].map(c => c.value)
            : [];
        try {
            await request('POST', 'melk/listings', {
                form_template_key: selectedConfig.form_key,
                form_data: formData,
                deal_type: selectedConfig.deal_type,
                property_type: selectedConfig.property_type,
                visibility_mode: mode,
                visibility_roles: roles,
                visibility_user_ids: (mode === 'users' || mode === 'private') ? visUserIds : [],
                visibility_usernames: (mode === 'users' || mode === 'private') ? visUsernames : [],
                visibility_district_ids: mode === 'geo' ? visDistrictIds : [],
                visibility_neighborhood_ids: mode === 'geo' ? visNeighIds : [],
                status: 'active',
            });
            $('listingWizard').style.display = 'none';
            resetWizard();
            toast('آگهی منتشر شد');
            load();
        } catch (e) { toast(e.message, true); }
    });

    if (!canPublish) $('newListingBtn')?.remove();

    renderFormBank();
    updateVisUI();
    await load();
}
