/**
 * melk-building-specialists-panel.js — فهرست / مناقصه / بانک فرم تخصص
 */
import { renderFormSections, collectFormData, validateRequired } from './melk-form-renderer.js';

const SPEC_STATUS_COLORS = {
    pending_approval: '#f59e0b', approved: '#22c55e',
    rejected: '#ef4444', suspended: '#94a3b8',
};

export function renderBuildingSpecialistsPanel(esc, { canApprove = false, canRegister = false } = {}) {
    return `<div class="em-ext-panel" data-ref="specialistsPanel">
        <div class="em-ext-intro em-ext-intro--specialists">
            <div class="em-ext-intro__text">
                <h2>👷 متخصصان حوزه ساختمان</h2>
                <p>فهرست متخصصان یا پنل مناقصه — بسته به نقش شما</p>
            </div>
            <div class="em-ext-kpis" data-ref="specKpis"></div>
        </div>
        <div class="em-ext-toolbar">
            <h2 class="em-ext-title">فهرست و مدیریت</h2>
            <div class="em-sub-tabs" data-ref="specTabs">
                <button type="button" class="em-sub-tab" data-spec-tab="directory" data-role-tab="browse">📋 فهرست</button>
                <button type="button" class="em-sub-tab" data-spec-tab="tenders" data-role-tab="spec">📢 مناقصه‌ها</button>
                <button type="button" class="em-sub-tab" data-spec-tab="mybids" data-role-tab="spec">💰 پیشنهادهای من</button>
                ${canRegister ? '<button type="button" class="em-sub-tab" data-spec-tab="profile">📝 پروفایل من</button>' : ''}
                ${canApprove ? '<button type="button" class="em-sub-tab" data-spec-tab="queue" data-role-tab="browse">⏳ صف تأیید</button>' : ''}
            </div>
        </div>
        <div data-ref="specDirectory" style="display:none">
            <div class="em-ext-toolbar em-ext-toolbar--sub">
                <select class="red-sel" data-ref="specFilter">
                    <option value="">همه تخصص‌ها</option>
                    <option value="architect">معمار</option>
                    <option value="structural">کارشناس سازه</option>
                    <option value="mep">کارشناس تاسیسات</option>
                    <option value="supervisor">ناظر ساختمان</option>
                    <option value="civil">مهندس عمران</option>
                    <option value="interior">طراح داخلی</option>
                    <option value="surveyor">نقشه‌بردار</option>
                    <option value="quantity_surveyor">متره و برآورد</option>
                </select>
                <button type="button" class="red-btn" data-ref="reloadSpecBtn">↻</button>
            </div>
            <div class="em-ext-list" data-ref="specList"></div>
        </div>
        <div data-ref="specTenders" style="display:none">
            <div class="em-ext-list" data-ref="tenderList"></div>
        </div>
        <div data-ref="specMyBids" style="display:none">
            <div class="em-ext-list" data-ref="myBidList"></div>
        </div>
        <div data-ref="specProfile" style="display:none">
            <div data-ref="specApprovedView" class="em-ext-form" style="display:none">
                <h3>پروفایل تأیید‌شده</h3>
                <p data-ref="specApprovedSummary"></p>
                <button type="button" class="red-btn" data-ref="viewMyFormBtn">📋 مشاهده فرم من</button>
            </div>
            <div class="em-listing-wizard em-spec-wizard" data-ref="specWizard">
                <div class="em-wizard-steps">
                    <span class="em-wiz-step em-wiz-step--active" data-spec-step="1">۱. انتخاب فرم تخصص</span>
                    <span class="em-wiz-step" data-spec-step="2">۲. تکمیل اطلاعات</span>
                    <span class="em-wiz-step" data-spec-step="3">۳. ارسال</span>
                </div>
                <div data-ref="specStepBank" class="em-wizard-pane">
                    <h3>📚 بانک فرم‌های تخصصی</h3>
                    <p class="em-form-bank-hint">فرم استاندارد متناسب با تخصص خود را انتخاب کنید</p>
                    <div class="em-form-bank-grid" data-ref="specFormBankGrid"></div>
                </div>
                <div data-ref="specStepFill" class="em-wizard-pane" style="display:none">
                    <div class="em-selected-form-head" data-ref="specSelectedHead"></div>
                    <div data-ref="specDynamicFields"></div>
                    <div class="em-ext-actions">
                        <button type="button" class="red-btn" data-ref="specBackBankBtn">← بازگشت</button>
                        <button type="button" class="red-btn red-btn--primary" data-ref="specToSubmitBtn">ادامه →</button>
                    </div>
                </div>
                <div data-ref="specStepSubmit" class="em-wizard-pane" style="display:none">
                    <div class="em-spec-review" data-ref="specReview"></div>
                    <div class="em-ext-actions">
                        <button type="button" class="red-btn" data-ref="specBackFillBtn">← بازگشت</button>
                        <button type="button" class="red-btn red-btn--primary" data-ref="saveSpecBtn">📤 ارسال برای تأیید</button>
                    </div>
                    <div data-ref="specStatusBox" class="em-spec-status-box" style="display:none"></div>
                </div>
            </div>
        </div>
        <div data-ref="specQueue" style="display:none">
            <div class="em-ext-list" data-ref="specQueueList"></div>
        </div>
        <div class="em-listing-modal" data-ref="specModal" style="display:none">
            <div class="em-listing-modal__box">
                <div class="em-listing-modal__head">
                    <h3 data-ref="specModalTitle">فرم تخصص</h3>
                    <button type="button" class="em-listing-modal__close" data-ref="specModalClose">✕</button>
                </div>
                <div class="em-listing-modal__body" data-ref="specModalBody"></div>
            </div>
        </div>
    </div>`;
}

export async function bindBuildingSpecialistsPanel(root, { request, esc, toast, can }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    const canApprove = can('melk.manage') || can('melk.specialists.approve') || can('*');
    const canRegister = can('melk.specialists.register') || canApprove;
    let myProfile = null;
    let formBank = [];
    let selectedSpecForm = null;
    let selectedSpecConfig = null;
    let specialistsCache = [];
    let specWizardStep = 1;

    try {
        const [profRes, bankRes] = await Promise.all([
            request('GET', 'melk/building-specialists?mine=1'),
            request('GET', 'melk/specialist-form-bank'),
        ]);
        myProfile = (profRes?.data ?? [])[0] || null;
        formBank = bankRes?.data ?? [];
    } catch { /* ignore */ }

    const canBrowse = canApprove || can('*')
        || (can('melk.specialists.view') && myProfile?.status !== 'approved');
    const specialistMode = !!(myProfile?.status === 'approved' && !canBrowse);

    if (specialistMode) {
        root.querySelector('.em-ext-intro__text h2').textContent = '👷 پنل متخصص — مناقصه و پیشنهاد قیمت';
        root.querySelector('.em-ext-intro__text p').textContent =
            'فقط کارهای پیشنهادی و پیشنهادهای خودتان — اطلاعات سایر متخصصان محرمانه است';
        root.querySelector('.em-ext-title').textContent = 'مناقصه و پیشنهاد';
        root.querySelectorAll('[data-role-tab="browse"]').forEach(el => { el.style.display = 'none'; });
    } else {
        root.querySelectorAll('[data-role-tab="spec"]').forEach(el => { el.style.display = 'none'; });
        if (!canBrowse) {
            const dirTab = root.querySelector('[data-spec-tab="directory"]');
            if (dirTab) dirTab.style.display = 'none';
        }
    }

    function fmtAmount(n) {
        if (!n) return '—';
        return Number(n).toLocaleString('fa-IR') + ' تومان';
    }

    function statusBadge(item, colors = SPEC_STATUS_COLORS) {
        const color = colors[item.status] || '#64748b';
        return `<span class="em-status" style="background:${color}">${esc(item.status_label)}</span>`;
    }

    function specialistCard(s, { showActions = false } = {}) {
        const hasForm = s.form_template_key && (s.form_attachment?.length || Object.keys(s.form_data || {}).length);
        const formBadge = hasForm
            ? `<span class="em-badge em-badge--form">${esc(s.form_template_icon || '📋')} ${esc(s.form_template_title || 'فرم تخصص')}</span>`
            : '';
        const preview = (s.form_attachment || []).slice(0, 3).map(f =>
            `<div class="em-form-attach-row"><span>${esc(f.label)}</span><strong>${esc(f.value)}</strong></div>`
        ).join('');
        const viewBtn = hasForm
            ? `<button type="button" class="red-btn red-btn--sm em-view-spec-form" data-spec-id="${s.id}">📋 فرم تخصص</button>` : '';
        return `<div class="em-ext-card em-ext-card--specialist" data-spec-id="${s.id}">
            <div class="em-ext-card-head">
                <strong>${esc(s.display_name)}</strong>
                <span class="em-badge">${esc(s.specialty_label)}</span>
                ${formBadge}
                ${statusBadge(s)}
            </div>
            <div class="em-ext-card-meta">${s.years_experience ? `${s.years_experience} سال · ` : ''}${esc(s.county || '')}</div>
            <p class="em-ext-desc">${esc((s.bio || '').slice(0, 160))}</p>
            ${preview ? `<div class="em-form-attach-preview">${preview}</div>` : ''}
            ${s.contact_phone ? `<div class="em-ext-contact">📞 <span dir="ltr">${esc(s.contact_phone)}</span></div>` : ''}
            <div class="em-ext-card-actions">${viewBtn}
            ${showActions ? `
                <button type="button" class="red-btn red-btn--primary" data-approve="${s.id}">✅ تأیید</button>
                <button type="button" class="red-btn" data-reject="${s.id}">❌ رد</button>` : ''}
            </div>
        </div>`;
    }

    function showSpecFormModal(s) {
        const modal = $('specModal');
        if (!modal || !s) return;
        $('specModalTitle').textContent = `${s.form_template_icon || '📋'} ${s.form_template_title || 'فرم تخصص'} — ${s.display_name}`;
        const rows = (s.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('');
        $('specModalBody').innerHTML = `
            ${s.form_template_standard ? `<p class="em-form-attach-std">${esc(s.form_template_standard)}</p>` : ''}
            <div class="em-form-attach-sheet">${rows || '<p class="em-empty-inline">فرم پیوست ندارد</p>'}</div>`;
        modal.style.display = '';
    }

    function bindSpecCardActions() {
        root.querySelectorAll('.em-view-spec-form').forEach(btn => {
            btn.addEventListener('click', () => {
                const s = specialistsCache.find(x => x.id === +btn.dataset.specId);
                if (s) showSpecFormModal(s);
            });
        });
    }

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

    function setSpecWizardStep(step) {
        specWizardStep = step;
        root.querySelectorAll('[data-spec-step]').forEach(el => {
            el.classList.toggle('em-wiz-step--active', +el.dataset.specStep === step);
            el.classList.toggle('em-wiz-step--done', +el.dataset.specStep < step);
        });
        $('specStepBank').style.display = step === 1 ? '' : 'none';
        $('specStepFill').style.display = step === 2 ? '' : 'none';
        $('specStepSubmit').style.display = step === 3 ? '' : 'none';
    }

    function renderSpecFormBank() {
        const grid = $('specFormBankGrid');
        if (!grid) return;
        grid.innerHTML = formBank.length ? formBank.map(f => `
            <button type="button" class="em-form-bank-card" data-spec-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>
            </button>
        `).join('') : '<div class="em-empty-inline">فرمی در بانک نیست</div>';
        grid.querySelectorAll('[data-spec-form-key]').forEach(btn => {
            btn.addEventListener('click', () => selectSpecForm(btn.dataset.specFormKey));
        });
    }

    async function selectSpecForm(formKey) {
        try {
            const res = await request('GET', `melk/specialist-form-config?form_key=${encodeURIComponent(formKey)}`);
            selectedSpecConfig = res?.data;
            selectedSpecForm = formBank.find(f => f.form_key === formKey) || selectedSpecConfig;
            if (!selectedSpecConfig) { toast('فرم یافت نشد', true); return; }
            $('specSelectedHead').innerHTML = `
                <div class="em-selected-form-badge">${esc(selectedSpecConfig.icon || '📋')}</div>
                <div><strong>${esc(selectedSpecConfig.title)}</strong>
                <span class="em-form-bank-sub">${esc(selectedSpecConfig.subtitle || '')}</span></div>`;
            $('specDynamicFields').innerHTML = renderFormSections(selectedSpecConfig.sections || [], esc);
            setSpecWizardStep(2);
        } catch (e) { toast(e.message, true); }
    }

    function buildSpecReview() {
        const data = collectFormData($('specDynamicFields'));
        const rows = Object.entries(data).filter(([, v]) => v !== '' && v != null)
            .map(([k, v]) => `<div class="em-form-attach-row"><span>${esc(k)}</span><strong>${esc(Array.isArray(v) ? v.join('، ') : String(v))}</strong></div>`);
        $('specReview').innerHTML = `
            <h4>بررسی نهایی — ${esc(selectedSpecConfig?.title || '')}</h4>
            <div class="em-form-attach-preview">${rows.join('')}</div>`;
    }

    function tenderCard(t) {
        const hasBid = t.my_bid;
        const budget = t.budget_min || t.budget_max
            ? `${t.budget_min ? fmtAmount(t.budget_min) : '؟'} — ${t.budget_max ? fmtAmount(t.budget_max) : '؟'}`
            : 'توافقی';
        return `<div class="em-ext-card em-ext-card--tender">
            <div class="em-ext-card-head">
                <strong>${esc(t.title)}</strong>
                <span class="em-badge">${esc(t.specialty_label)}</span>
                ${hasBid ? '<span class="em-verified-badge">✓ پیشنهاد داده‌اید</span>' : ''}
            </div>
            <div class="em-ext-card-meta"><code dir="ltr">${esc(t.tender_key)}</code> · ${esc(t.location_county || '')}</div>
            <p class="em-ext-desc">${esc((t.description || '').slice(0, 200))}</p>
            <div class="em-ext-card-meta">بودجه: ${budget}</div>
            ${hasBid ? `<div class="em-ext-note">پیشنهاد شما: <strong>${fmtAmount(hasBid.amount)}</strong></div>` : ''}
            <div class="em-ext-card-actions em-tender-bid-form" data-bid-tender="${t.id}">
                <input class="red-inp em-bid-amount" type="number" min="1" placeholder="مبلغ (تومان)" dir="ltr" value="${hasBid?.amount || ''}">
                <input class="red-inp em-bid-days" type="number" min="1" placeholder="مدت (روز)" dir="ltr" value="${hasBid?.delivery_days || ''}">
                <input class="red-inp em-bid-note" placeholder="توضیح پیشنهاد">
                <button type="button" class="red-btn red-btn--primary" data-submit-bid="${t.id}">
                    ${hasBid ? '✏️ به‌روز پیشنهاد' : '💰 ارسال پیشنهاد'}
                </button>
            </div>
        </div>`;
    }

    function bidCard(b) {
        return `<div class="em-ext-card em-ext-card--bid">
            <div class="em-ext-card-head"><strong>${esc(b.tender_title || '')}</strong>${statusBadge(b)}</div>
            <div class="em-ext-card-meta">${fmtAmount(b.amount)}${b.delivery_days ? ` · ${b.delivery_days} روز` : ''}</div>
            ${b.proposal_text ? `<p class="em-ext-desc">${esc(b.proposal_text)}</p>` : ''}
        </div>`;
    }

    async function loadDirectory() {
        if (!canBrowse) return;
        const list = $('specList');
        list.innerHTML = '...';
        const qs = $('specFilter')?.value ? `?specialty=${$('specFilter').value}` : '';
        try {
            const items = (await request('GET', `melk/building-specialists${qs}`))?.data ?? [];
            specialistsCache = items;
            $('specKpis').innerHTML = `<div class="em-kpi em-kpi--ok"><strong>${items.length}</strong><span>متخصص</span></div>`;
            list.innerHTML = items.length ? items.map(s => specialistCard(s)).join('')
                : '<div class="em-empty-inline">متخصصی یافت نشد.</div>';
            bindSpecCardActions();
        } catch (e) { list.innerHTML = esc(e.message); }
    }

    async function loadTenders() {
        const list = $('tenderList');
        list.innerHTML = '...';
        try {
            const items = (await request('GET', 'melk/specialist-tenders'))?.data ?? [];
            $('specKpis').innerHTML = `
                <div class="em-kpi"><strong>${items.filter(t => t.status === 'open').length}</strong><span>مناقصه باز</span></div>
                <div class="em-kpi em-kpi--ok"><strong>${items.filter(t => t.my_bid).length}</strong><span>پیشنهاد شما</span></div>`;
            list.innerHTML = items.length ? items.map(t => tenderCard(t)).join('')
                : '<div class="em-empty-inline">مناقصه‌ای برای تخصص شما نیست.</div>';
            list.querySelectorAll('[data-submit-bid]').forEach(btn => {
                btn.addEventListener('click', async () => {
                    const form = btn.closest('[data-bid-tender]');
                    const amount = form?.querySelector('.em-bid-amount')?.value;
                    if (!amount || +amount <= 0) { toast('مبلغ الزامی است', true); return; }
                    try {
                        await request('POST', `melk/specialist-tenders/${btn.dataset.submitBid}/bids`, {
                            amount: +amount,
                            delivery_days: form?.querySelector('.em-bid-days')?.value ? +form.querySelector('.em-bid-days').value : null,
                            proposal_text: form?.querySelector('.em-bid-note')?.value || '',
                        });
                        toast('پیشنهاد ثبت شد');
                        loadTenders();
                        loadMyBids();
                    } catch (e) { toast(e.message, true); }
                });
            });
        } catch (e) { list.innerHTML = esc(e.message); }
    }

    async function loadMyBids() {
        const list = $('myBidList');
        list.innerHTML = '...';
        try {
            const items = (await request('GET', 'melk/specialist-bids'))?.data ?? [];
            list.innerHTML = items.length ? items.map(b => bidCard(b)).join('')
                : '<div class="em-empty-inline">پیشنهادی ثبت نشده.</div>';
        } catch (e) { list.innerHTML = esc(e.message); }
    }

    async function loadQueue() {
        const list = $('specQueueList');
        list.innerHTML = '...';
        try {
            const items = (await request('GET', 'melk/building-specialists?all=1&status=pending_approval'))?.data ?? [];
            specialistsCache = items;
            list.innerHTML = items.length ? items.map(s => specialistCard(s, { showActions: true })).join('')
                : '<div class="em-empty-inline">در انتظار تأیید نیست.</div>';
            bindSpecCardActions();
            list.querySelectorAll('[data-approve]').forEach(btn => {
                btn.addEventListener('click', async () => {
                    try {
                        await request('PUT', `melk/building-specialists/${btn.dataset.approve}/approve`);
                        toast('تأیید شد'); loadQueue(); loadDirectory();
                    } catch (e) { toast(e.message, true); }
                });
            });
            list.querySelectorAll('[data-reject]').forEach(btn => {
                btn.addEventListener('click', async () => {
                    try {
                        await request('PUT', `melk/building-specialists/${btn.dataset.reject}/reject`, {
                            reason: prompt('دلیل رد:') || '',
                        });
                        toast('رد شد'); loadQueue();
                    } catch (e) { toast(e.message, true); }
                });
            });
        } catch (e) { list.innerHTML = esc(e.message); }
    }

    async function loadMyProfile() {
        try {
            myProfile = ((await request('GET', 'melk/building-specialists?mine=1'))?.data ?? [])[0] || null;
            const box = $('specStatusBox');
            const wizard = $('specWizard');
            if (myProfile) {
                if (myProfile.status === 'approved') {
                    wizard.style.display = 'none';
                    $('specApprovedView').style.display = '';
                    $('specApprovedSummary').textContent =
                        `${myProfile.form_template_title || myProfile.specialty_label} — ${myProfile.display_name}`;
                    $('viewMyFormBtn')?.addEventListener('click', () => showSpecFormModal(myProfile), { once: true });
                } else {
                    $('specApprovedView').style.display = 'none';
                    wizard.style.display = '';
                    box.style.display = '';
                    box.innerHTML = `<div class="em-spec-status em-spec-status--${myProfile.status}">
                        وضعیت: <strong>${esc(myProfile.status_label)}</strong></div>`;
                    $('saveSpecBtn').style.display = myProfile.status === 'approved' ? 'none' : '';
                    if (myProfile.form_template_key) {
                        await selectSpecForm(myProfile.form_template_key);
                        // پر کردن فیلدها از پروفایل موجود
                        const container = $('specDynamicFields');
                        if (container) {
                            const all = { ...myProfile.form_data, license_no: myProfile.license_no,
                                years_experience: myProfile.years_experience, county: myProfile.county,
                                city: myProfile.city, contact_phone: myProfile.contact_phone,
                                contact_email: myProfile.contact_email, bio: myProfile.bio,
                                credentials: myProfile.credentials,
                                service_areas: (myProfile.service_areas || []).join('، ') };
                            Object.entries(all).forEach(([k, v]) => {
                                const els = container.querySelectorAll(`[data-field="${k}"]`);
                                els.forEach(el => {
                                    if (el.type === 'checkbox') el.checked = Array.isArray(v) ? v.includes(el.value) : false;
                                    else if (v != null) el.value = Array.isArray(v) ? v.join('، ') : v;
                                });
                            });
                        }
                    }
                }
            } else {
                wizard.style.display = '';
                box.style.display = 'none';
                $('saveSpecBtn').style.display = '';
                setSpecWizardStep(1);
                renderSpecFormBank();
            }
        } catch (e) { toast(e.message, true); }
    }

    function switchTab(tab) {
        $('specTabs')?.querySelectorAll('.em-sub-tab').forEach(b =>
            b.classList.toggle('em-sub-tab--active', b.dataset.specTab === tab));
        $('specDirectory').style.display = tab === 'directory' ? '' : 'none';
        $('specTenders').style.display = tab === 'tenders' ? '' : 'none';
        $('specMyBids').style.display = tab === 'mybids' ? '' : 'none';
        $('specProfile').style.display = tab === 'profile' ? '' : 'none';
        $('specQueue').style.display = tab === 'queue' ? '' : 'none';
        if (tab === 'directory') loadDirectory();
        if (tab === 'tenders') loadTenders();
        if (tab === 'mybids') loadMyBids();
        if (tab === 'profile') loadMyProfile();
        if (tab === 'queue') loadQueue();
    }

    $('specTabs')?.querySelectorAll('[data-spec-tab]').forEach(btn => {
        btn.addEventListener('click', () => switchTab(btn.dataset.specTab));
    });

    $('specBackBankBtn')?.addEventListener('click', () => setSpecWizardStep(1));
    $('specBackFillBtn')?.addEventListener('click', () => setSpecWizardStep(2));
    $('specToSubmitBtn')?.addEventListener('click', () => {
        if (!selectedSpecConfig) { toast('فرم انتخاب نشده', true); return; }
        const missing = validateRequired($('specDynamicFields'), selectedSpecConfig.sections || []);
        if (missing.length) { toast('فیلدهای الزامی: ' + missing.join('، '), true); return; }
        buildSpecReview();
        setSpecWizardStep(3);
    });

    $('saveSpecBtn')?.addEventListener('click', async () => {
        if (!selectedSpecConfig) { toast('فرم انتخاب نشده', true); return; }
        const formData = collectFormData($('specDynamicFields'));
        try {
            await request('POST', 'melk/building-specialists', {
                form_template_key: selectedSpecConfig.form_key,
                form_data: formData,
                specialty: selectedSpecConfig.specialty,
            });
            toast('پروفایل ارسال شد');
            loadMyProfile();
        } catch (e) { toast(e.message, true); }
    });

    $('reloadSpecBtn')?.addEventListener('click', loadDirectory);
    $('specFilter')?.addEventListener('change', loadDirectory);

    renderSpecFormBank();
    if (specialistMode) switchTab('tenders');
    else if (canBrowse) switchTab('directory');
    else if (canRegister) switchTab('profile');
}
