/**
 * melk-advisory-panel.js — مالیات · حقوق · مشاور AI
 */

function mdLite(text, esc) {
    return esc(text)
        .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
        .replace(/\n/g, '<br>');
}

export function renderAdvisoryPanel(esc) {
    return `<div class="em-ext-panel em-advisory-panel" data-ref="advPanel">
        <div class="em-ext-intro em-ext-intro--advisory">
            <div class="em-ext-intro__text">
                <h2>📑 مالیات و حقوق ملک</h2>
                <p>بانک قوانین مالیاتی · راهنمای حقوقی · مشاور هوشمند AI</p>
            </div>
            <div class="em-advisory-ai-badge" data-ref="aiBadge">🤖 AI</div>
        </div>

        <div class="em-advisory-tabs" data-ref="advTabs">
            <button type="button" class="em-advisory-tab em-advisory-tab--active" data-adv-tab="ai">🤖 مشاور AI</button>
            <button type="button" class="em-advisory-tab" data-adv-tab="tax">📊 قوانین مالیاتی</button>
            <button type="button" class="em-advisory-tab" data-adv-tab="legal">⚖️ حقوق ملک</button>
            <button type="button" class="em-advisory-tab" data-adv-tab="history">📜 تاریخچه</button>
        </div>

        <div data-ref="advPaneAi" class="em-advisory-pane">
            <div class="em-advisory-disclaimer" data-ref="disclaimer"></div>
            <div class="em-advisory-topic">
                <label>حوزه:</label>
                <select class="red-sel" data-ref="aiTopic">
                    <option value="both">مالیات + حقوق</option>
                    <option value="tax">فقط مالیات</option>
                    <option value="legal">فقط حقوق</option>
                </select>
            </div>
            <div class="em-advisory-prompts" data-ref="prompts"></div>
            <div class="em-advisory-chat" data-ref="chatMsgs"></div>
            <div class="em-advisory-typing" data-ref="typing" style="display:none">⏳ در حال فکر کردن…</div>
            <div class="em-advisory-input-row">
                <textarea class="red-inp" data-ref="chatInput" rows="2" placeholder="سؤال مالیاتی یا حقوقی خود را بپرسید…"></textarea>
                <button type="button" class="red-btn red-btn--primary" data-ref="sendBtn">ارسال</button>
            </div>
            <div class="em-advisory-related" data-ref="related"></div>
            <button type="button" class="red-btn" data-ref="escalateBtn">👨‍⚕️ ارجاع به کارشناس رسمی</button>
        </div>

        <div data-ref="advPaneTax" class="em-advisory-pane" style="display:none">
            <div class="em-ext-toolbar">
                <input class="red-inp" data-ref="taxSearch" placeholder="🔍 جستجو در قوانین مالیاتی…">
            </div>
            <div class="em-advisory-kb-grid" data-ref="taxGrid"></div>
            <div class="em-advisory-detail" data-ref="taxDetail" style="display:none"></div>
        </div>

        <div data-ref="advPaneLegal" class="em-advisory-pane" style="display:none">
            <div class="em-ext-toolbar">
                <input class="red-inp" data-ref="legalSearch" placeholder="🔍 جستجو در حقوق ملک…">
            </div>
            <div class="em-advisory-kb-grid" data-ref="legalGrid"></div>
            <div class="em-advisory-detail" data-ref="legalDetail" style="display:none"></div>
        </div>

        <div data-ref="advPaneHistory" class="em-advisory-pane" style="display:none">
            <div class="em-ext-list" data-ref="historyList"></div>
        </div>
    </div>`;
}

export async function bindAdvisoryPanel(root, { request, esc, toast }) {
    const $ = (n) => root.querySelector(`[data-ref="${n}"]`);
    let meta = { prompts: [], ai: {} };
    let history = [];
    let sessionId = null;
    let loading = false;
    let taxItems = [];
    let legalItems = [];

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

    if ($('disclaimer')) {
        $('disclaimer').textContent = meta.ai?.disclaimer || 'مشاوره آموزشی — جایگزین مشاور رسمی نیست.';
    }
    if ($('aiBadge')) {
        $('aiBadge').textContent = meta.ai?.has_llm ? '🤖 AI فعال' : '📚 AI (حالت دانش‌نامه)';
        $('aiBadge').classList.toggle('em-advisory-ai-badge--on', !!meta.ai?.has_llm);
    }

    function switchTab(tab) {
        root.querySelectorAll('.em-advisory-tab').forEach(b =>
            b.classList.toggle('em-advisory-tab--active', b.dataset.advTab === tab));
        ['Ai', 'Tax', 'Legal', 'History'].forEach(p => {
            const el = $(`advPane${p}`);
            if (el) el.style.display = p.toLowerCase() === tab ? '' : 'none';
        });
    }

    root.querySelectorAll('[data-adv-tab]').forEach(btn => {
        btn.addEventListener('click', () => {
            switchTab(btn.dataset.advTab);
            if (btn.dataset.advTab === 'tax' && !taxItems.length) loadTax();
            if (btn.dataset.advTab === 'legal' && !legalItems.length) loadLegal();
            if (btn.dataset.advTab === 'history') loadHistory();
        });
    });

    function renderPrompts() {
        const el = $('prompts');
        if (!el) return;
        el.innerHTML = (meta.prompts || []).map(p =>
            `<button type="button" class="em-advisory-prompt" data-prompt="${esc(p.text)}" data-topic="${esc(p.topic)}">${esc(p.text)}</button>`
        ).join('');
        el.querySelectorAll('[data-prompt]').forEach(btn => {
            btn.addEventListener('click', () => {
                $('aiTopic').value = btn.dataset.topic || 'both';
                $('chatInput').value = btn.dataset.prompt;
                sendChat();
            });
        });
    }

    function paintChat(related = []) {
        const box = $('chatMsgs');
        if (!box) return;
        if (!history.length) {
            box.innerHTML = `<div class="em-advisory-welcome">
                <p>👋 سلام! من مشاور <strong>مالیات و حقوق ملک</strong> هستم.</p>
                <p>${esc(meta.ai?.disclaimer || '')}</p>
                <p>۱۰ قانون مالیاتی و ۱۰ موضوع حقوقی در بانک دانش موجود است.</p>
            </div>`;
        } else {
            box.innerHTML = history.map(h => `
                <div class="em-advisory-msg em-advisory-msg--${h.role}">
                    <div class="em-advisory-msg__bubble">${mdLite(h.content, esc)}</div>
                    ${h.engine ? `<small class="em-advisory-engine">${h.engine === 'llm' ? '🤖 AI' : '📚 دانش‌نامه'}</small>` : ''}
                </div>`).join('');
            box.scrollTop = box.scrollHeight;
        }
        const rel = $('related');
        if (rel) {
            rel.innerHTML = related.length
                ? '<p><strong>مطالب مرتبط:</strong> ' + related.map(r =>
                    `<button type="button" class="em-link-btn" data-rel-key="${esc(r.key)}" data-rel-type="${r.icon?.includes('⚖') ? 'legal' : 'tax'}">${esc(r.title || r.label)}</button>`
                ).join(' · ') + '</p>'
                : '';
            rel.querySelectorAll('[data-rel-key]').forEach(btn => {
                btn.addEventListener('click', () => openDetail(btn.dataset.relType, btn.dataset.relKey));
            });
        }
    }

    async function sendChat() {
        const text = $('chatInput')?.value?.trim();
        if (!text || loading) return;
        loading = true;
        $('sendBtn').disabled = true;
        $('typing').style.display = '';
        history.push({ role: 'user', content: text });
        $('chatInput').value = '';
        paintChat();

        try {
            const res = await request('POST', 'melk/advisory/chat', {
                message: text,
                history: history.slice(0, -1).map(h => ({ role: h.role, content: h.content })),
                topic: $('aiTopic')?.value || 'both',
                session_id: sessionId,
            });
            const d = res?.data ?? {};
            if (!d.success) throw new Error(d.message || 'خطا');
            sessionId = d.session_id || sessionId;
            history.push({ role: 'assistant', content: d.reply, engine: d.engine });
            paintChat(d.related || []);
        } catch (e) {
            history.push({ role: 'assistant', content: e.message || 'خطا در پاسخ', engine: 'error' });
            paintChat();
            toast(e.message, true);
        } finally {
            loading = false;
            $('sendBtn').disabled = false;
            $('typing').style.display = 'none';
        }
    }

    $('sendBtn')?.addEventListener('click', sendChat);
    $('chatInput')?.addEventListener('keydown', e => {
        if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChat(); }
    });

    $('escalateBtn')?.addEventListener('click', async () => {
        if (!sessionId && !history.length) {
            toast('ابتدا یک گفتگو با AI داشته باشید', true);
            return;
        }
        try {
            await request('POST', 'melk/advisory/escalate', {
                session_id: sessionId,
                topic: $('aiTopic')?.value || 'both',
                subject: 'ارجاع مشاور AI — بررسی رسمی',
            });
            toast('درخواست به کارشناس رسمی ارجاع شد');
        } catch (e) { toast(e.message, true); }
    });

    async function loadTax(q = '') {
        const res = await request('GET', `melk/advisory/tax${q ? '?q=' + encodeURIComponent(q) : ''}`);
        taxItems = res?.data ?? [];
        renderKbGrid('tax', taxItems);
    }

    async function loadLegal(q = '') {
        const res = await request('GET', `melk/advisory/legal${q ? '?q=' + encodeURIComponent(q) : ''}`);
        legalItems = res?.data ?? [];
        renderKbGrid('legal', legalItems);
    }

    function renderKbGrid(type, items) {
        const grid = $(type === 'tax' ? 'taxGrid' : 'legalGrid');
        if (!grid) return;
        grid.innerHTML = items.length ? items.map(it => `
            <article class="em-advisory-kb-card" data-kb-key="${esc(it.key)}" data-kb-type="${type}">
                <span class="em-advisory-kb-icon">${esc(it.icon || '📋')}</span>
                <strong>${esc(it.title)}</strong>
                <p>${esc(it.summary)}</p>
            </article>`).join('') : '<div class="em-empty">موردی یافت نشد</div>';
        grid.querySelectorAll('[data-kb-key]').forEach(card => {
            card.addEventListener('click', () => openDetail(card.dataset.kbType, card.dataset.kbKey));
        });
    }

    async function openDetail(type, key) {
        switchTab(type === 'tax' ? 'tax' : 'legal');
        const detailEl = $(type === 'tax' ? 'taxDetail' : 'legalDetail');
        const gridEl = $(type === 'tax' ? 'taxGrid' : 'legalGrid');
        try {
            const res = await request('GET', `melk/advisory/${type}/${key}`);
            const d = res?.data;
            if (!d) return;
            if (gridEl) gridEl.style.display = 'none';
            detailEl.style.display = '';
            detailEl.innerHTML = renderDetail(d, type, esc);
            detailEl.querySelector('[data-back-kb]')?.addEventListener('click', () => {
                detailEl.style.display = 'none';
                if (gridEl) gridEl.style.display = '';
            });
            detailEl.querySelector('[data-ask-ai]')?.addEventListener('click', () => {
                switchTab('ai');
                $('aiTopic').value = type === 'tax' ? 'tax' : 'legal';
                $('chatInput').value = `توضیح بیشتر درباره: ${d.title}`;
            });
        } catch (e) { toast(e.message, true); }
    }

    function renderDetail(d, type, escFn) {
        let body = `<button type="button" class="red-btn" data-back-kb>← بازگشت</button>
            <h3>${escFn(d.title)}</h3>
            <p>${escFn(d.summary)}</p>`;
        if (type === 'tax') {
            if (d.rate) body += `<p><strong>نرخ/مبنا:</strong> ${escFn(d.rate)}</p>`;
            if (d.obligations?.length) body += `<h4>تعهدات</h4><ul>${d.obligations.map(o => `<li>${escFn(o)}</li>`).join('')}</ul>`;
            if (d.exemptions?.length) body += `<h4>معافیت‌ها</h4><ul>${d.exemptions.map(o => `<li>${escFn(o)}</li>`).join('')}</ul>`;
            if (d.risks?.length) body += `<h4>⚠️ ریسک‌ها</h4><ul>${d.risks.map(o => `<li>${escFn(o)}</li>`).join('')}</ul>`;
        } else {
            if (d.points?.length) body += `<h4>نکات کلیدی</h4><ul>${d.points.map(o => `<li>${escFn(o)}</li>`).join('')}</ul>`;
            if (d.checklist?.length) body += `<h4>چک‌لیست</h4><ul>${d.checklist.map(o => `<li>${escFn(o)}</li>`).join('')}</ul>`;
        }
        if (d.refs?.length) body += `<p><small>مراجع: ${d.refs.map(r => escFn(r)).join(' · ')}</small></p>`;
        body += `<button type="button" class="red-btn red-btn--primary" data-ask-ai">🤖 پرسیدن از AI درباره این موضوع</button>`;
        return body;
    }

    async function loadHistory() {
        try {
            const res = await request('GET', 'melk/advisory/sessions');
            const rows = res?.data ?? [];
            $('historyList').innerHTML = rows.length ? rows.map(s => `
                <article class="em-ext-card" data-sess="${s.id}">
                    <strong>${esc(s.title || 'مشاوره')}</strong>
                    <span class="em-badge">${esc(s.topic)}</span>
                    <small>${esc(s.created_at)}</small>
                </article>`).join('') : '<div class="em-empty">تاریخچه‌ای نیست</div>';
            $('historyList').querySelectorAll('[data-sess]').forEach(card => {
                card.addEventListener('click', async () => {
                    const mres = await request('GET', `melk/advisory/sessions/${card.dataset.sess}/messages`);
                    sessionId = parseInt(card.dataset.sess, 10);
                    history = (mres?.data ?? []).map(m => ({
                        role: m.role === 'user' ? 'user' : 'assistant',
                        content: m.body,
                        engine: m.engine,
                    }));
                    switchTab('ai');
                    paintChat();
                });
            });
        } catch (e) { toast(e.message, true); }
    }

    let taxT;
    $('taxSearch')?.addEventListener('input', e => {
        clearTimeout(taxT);
        taxT = setTimeout(() => loadTax(e.target.value), 300);
    });
    let legT;
    $('legalSearch')?.addEventListener('input', e => {
        clearTimeout(legT);
        legT = setTimeout(() => loadLegal(e.target.value), 300);
    });

    renderPrompts();
    paintChat();
}
