/**
 * EduPanels — پنل‌های UI کامل EduBrain
 */
export function esc(s) {
    return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

export function fmt(n) {
    return Number(n || 0).toLocaleString('fa-IR');
}

export function masteryBar(label, pct, key = '') {
    const p = Math.max(0, Math.min(100, pct));
    const color = p >= 70 ? '#22c55e' : p >= 50 ? '#eab308' : '#ef4444';
    return `<div class="edu-mastery-row" data-domain="${esc(key)}">
        <div class="edu-mastery-row__head"><span>${esc(label)}</span><span>${p}%</span></div>
        <div class="edu-mastery-bar"><div class="edu-mastery-bar__fill" style="width:${p}%;background:${color}"></div></div>
    </div>`;
}

export function renderBrainState(state, meta) {
    const domains = meta?.skill_domains || {};
    const mastery = state?.mastery || {};
    const weaknesses = state?.weaknesses || [];
    const plan = state?.plan?.plan || {};
    const assessments = state?.assessments || [];

    const bars = Object.keys(domains).map(k => {
        const pct = Math.round((mastery[k] ?? 0) * 100) || 0;
        return masteryBar(domains[k], pct, k);
    }).join('');

    const gdina = weaknesses.length
        ? weaknesses.map(w => `<tr><td>${esc(w.label)}</td><td><span class="edu-badge edu-badge--warn">${Math.round((w.mastery||0)*100)}%</span></td><td>remedial + mock</td></tr>`).join('')
        : '<tr><td colspan="3">ضعف شاخصی ثبت نشده — تسلط کافی</td></tr>';

    const planWeeks = (plan.weeks || []).map(w => `
        <div class="edu-plan-week">
            <h4>هفته ${w.week || ''} — ${esc(w.label || w.domain || '')}</h4>
            <p class="edu-plan-goal">${esc(w.goal || '')}</p>
            <ul>${(w.tasks || []).map(t => `<li>${esc(t)}</li>`).join('')}</ul>
        </div>`).join('') || '<p class="edu-muted">هنوز برنامه فعال نیست — Placement را اجرا کنید.</p>';

    const history = assessments.map(a => {
        const res = a.results || {};
        const weakN = (res.weaknesses || []).length;
        return `<div class="edu-history-item">
            <strong>Placement #${a.id}</strong>
            <span class="edu-muted">${esc(a.created_at || '')}</span>
            <span class="edu-badge">${esc(a.track || '')}</span>
            <span>${weakN} ضعف · ${Object.keys(res.mastery || {}).length} حوزه</span>
        </div>`;
    }).join('') || '<p class="edu-muted">تاریخچه خالی</p>';

    return `
    <div class="edu-panel"><h2>EduBrain — CDM · G-DINA · ALEKS</h2>
        <div class="edu-framework-tags">
            <span class="edu-pill">CDM</span><span class="edu-pill">G-DINA</span>
            <span class="edu-pill">ALEKS/KST</span><span class="edu-pill">EduLoop</span>
        </div>
        <div class="edu-grid-2 edu-grid-2--wide">
            <div>
                <h3 class="edu-subtitle">نقشه تسلط (Knowledge Space)</h3>
                <div class="edu-mastery-grid">${bars}</div>
            </div>
            <div>
                <h3 class="edu-subtitle">ماتریس G-DINA — ضعف‌های اولویت‌دار</h3>
                <table class="edu-table"><thead><tr><th>حوزه</th><th>تسلط</th><th>اقدام</th></tr></thead>
                <tbody>${gdina}</tbody></table>
            </div>
        </div>
        <h3 class="edu-subtitle" style="margin-top:20px">برنامه شخصی (EduLoop)</h3>
        ${planWeeks}
        <h3 class="edu-subtitle" style="margin-top:20px">تاریخچه Placement</h3>
        <div class="edu-history-list">${history}</div>
    </div>
    <div class="edu-panel"><h2>Placement جدید</h2>
        <p class="edu-muted">درصد تسلط ۰–۱۰۰ در هر حوزه را وارد کنید</p>
        <div class="edu-grid-2" id="edu-plc-form">
            ${Object.entries(domains).slice(0, 10).map(([k, v]) => `
                <div class="edu-field"><label>${esc(v)}</label>
                <input type="number" min="0" max="100" data-domain="${k}" class="edu-plc-input"
                    value="${Math.round((mastery[k] ?? 0.5) * 100)}"></div>`).join('')}
        </div>
        <div class="edu-field" style="margin-top:12px">
            <label>مسیر</label>
            <select id="edu-plc-track">
                ${Object.entries(meta?.tracks || {}).map(([k,v]) =>
                    `<option value="${k}" ${state?.learner?.track === k ? 'selected' : ''}>${esc(v)}</option>`).join('')}
            </select>
        </div>
        <button class="edu-btn edu-btn--sm" id="edu-run-placement">اجرای Placement و به‌روزرسانی برنامه</button>
        <div id="edu-placement-result"></div>
    </div>`;
}

export function renderTimeline(data) {
    const learner = data?.learner || {};
    const profile = learner.profile || {};
    const academic = data?.academic || [];
    const skill = data?.skill || [];

    const item = (row, type) => {
        let payload = {};
        try { payload = JSON.parse(row.payload_json || '{}'); } catch { payload = {}; }
        return `<div class="edu-timeline-item edu-timeline-item--${type}">
            <div class="edu-timeline-item__date">${esc(row.entry_date || row.created_at?.slice(0,10) || '')}</div>
            <div class="edu-timeline-item__body">
                <strong>${esc(row.title || payload.title || '—')}</strong>
                <span class="edu-badge">${esc(row.category || '')}</span>
                ${payload.score != null ? `<span>نمره: ${payload.score}</span>` : ''}
                ${payload.report?.summary ? `<p class="edu-muted">${esc(payload.report.summary)}</p>` : ''}
            </div>
        </div>`;
    };

    return `<div class="edu-panel"><h2>پروفایل ۳۶۰°</h2>
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${esc(learner.grade_level || '—')}</strong><span>پایه</span></div>
            <div class="edu-stat"><strong>${esc(learner.track || '—')}</strong><span>مسیر</span></div>
            <div class="edu-stat"><strong>${(profile.goals || []).length}</strong><span>هدف</span></div>
        </div>
        ${(profile.goals || []).length ? `<p style="margin:12px 0;color:#c4b5fd">اهداف: ${(profile.goals||[]).map(g=>esc(g)).join(' · ')}</p>` : ''}
        <div class="edu-grid-2 edu-grid-2--wide">
            <div>
                <h3 class="edu-subtitle">📚 Timeline تحصیلی</h3>
                <div class="edu-timeline">${academic.length ? academic.map(r => item(r, 'academic')).join('') : '<p class="edu-muted">خالی</p>'}</div>
            </div>
            <div>
                <h3 class="edu-subtitle">🎵 Timeline مهارتی</h3>
                <div class="edu-timeline">${skill.length ? skill.map(r => item(r, 'skill')).join('') : '<p class="edu-muted">خالی</p>'}</div>
            </div>
        </div>
        <div class="edu-panel edu-panel--inner" style="margin-top:16px">
            <h3 class="edu-subtitle">افزودن رویداد</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>نوع</label><select id="edu-log-type"><option value="academic">تحصیلی</option><option value="skill">مهارتی</option></select></div>
                <div class="edu-field"><label>عنوان</label><input id="edu-log-title" placeholder="Mock / کارنامه / ..."></div>
            </div>
            <button class="edu-btn edu-btn--sm" id="edu-add-log">ثبت در Timeline</button>
        </div>
    </div>`;
}

export function renderAiChat() {
    const chips = ['برنامه کنکور من چیست؟', 'تیزهوشان از کجا شروع کنم؟', 'هزینه جلسه منزل؟', 'Placement چیست؟'];
    return `<div class="edu-panel edu-ai-panel"><h2>🤖 EduBrain AI — Graph-aware</h2>
        <p class="edu-muted">مشاور هوشمند · CDM · کنکور · تیزهوشان · Graph-RAG lite</p>
        <div class="edu-ai-chips">${chips.map(c => `<button type="button" class="edu-ai-chip" data-msg="${esc(c)}">${esc(c)}</button>`).join('')}</div>
        <div class="edu-ai-messages" id="edu-ai-messages">
            <div class="edu-ai-msg edu-ai-msg--bot">سلام! من EduBrain هستم. درباره برنامه، جلسه، یا کنکور بپرسید.</div>
        </div>
        <div class="edu-ai-input-row">
            <input id="edu-ai-input" placeholder="سؤال خود را بنویسید..." autocomplete="off">
            <button class="edu-btn edu-btn--sm" id="edu-ai-send">ارسال</button>
        </div>
    </div>`;
}

export function renderMarketplace(orgs, educators) {
    const orgCards = (orgs || []).map(o => `
        <div class="edu-market-card" data-org-id="${o.id}">
            <h4>${esc(o.name)}</h4>
            <span class="edu-badge">${esc(o.org_type)}</span>
            <p class="edu-muted">${esc(o.city)} — ${esc(o.address_text || '')}</p>
            ${o.lat ? `<p class="edu-muted">📍 ${o.lat}, ${o.lng}</p>` : ''}
            <button class="edu-btn edu-btn--sm edu-btn--ghost edu-org-detail" data-org="${o.id}">جزئیات و اسلات</button>
        </div>`).join('');

    const eduCards = (educators || []).map(e => `
        <div class="edu-market-card">
            <h4>${esc(e.display_name || 'مربی')}</h4>
            <span class="edu-badge edu-badge--ok">${esc(e.verified_status || '')}</span>
            <p class="edu-muted">${esc(e.educator_type || 'mentor')} · ${fmt(e.hourly_rate)}/ساعت</p>
            <p class="edu-muted">${((e.profile?.skill_cv)||[]).join(' · ')}</p>
        </div>`).join('');

    return `<div class="edu-panel"><h2>🏪 Marketplace آموزش</h2>
        <h3 class="edu-subtitle">مدارس و مؤسسات</h3>
        <div class="edu-market-grid">${orgCards || '<p class="edu-muted">—</p>'}</div>
        <h3 class="edu-subtitle" style="margin-top:20px">مربیان تأیید‌شده</h3>
        <div class="edu-market-grid">${eduCards || '<p class="edu-muted">—</p>'}</div>
        <div id="edu-org-detail-box"></div>
    </div>`;
}

export function renderOrgDetail(org) {
    if (!org) return '';
    const slots = (org.schedule || []).map(s => `
        <tr><td>${esc(s.slot_date)}</td><td>${esc(String(s.start_time).slice(0,5))}–${esc(String(s.end_time).slice(0,5))}</td>
        <td><span class="edu-badge">${esc(s.status)}</span></td></tr>`).join('');
    const resources = (org.resources || []).map(r =>
        `<li>${esc(r.name)} — ${fmt(r.price_per_hour)}/ساعت · ظرفیت ${r.capacity}</li>`).join('');
    return `<div class="edu-panel edu-panel--inner">
        <h3>${esc(org.name)}</h3>
        <p class="edu-muted">${esc(org.city)} · ${esc(org.address_text || '')}</p>
        <ul>${resources}</ul>
        <table class="edu-table"><thead><tr><th>تاریخ</th><th>ساعت</th><th>وضعیت</th></tr></thead>
        <tbody>${slots || '<tr><td colspan="3">اسلاتی نیست</td></tr>'}</tbody></table>
    </div>`;
}

export function renderScheduleAdmin(orgs, schedule, selectedOrgId) {
    const opts = (orgs || []).map(o =>
        `<option value="${o.id}" ${+o.id === +selectedOrgId ? 'selected' : ''}>${esc(o.name)}</option>`).join('');
    const rows = (schedule || []).map(s => `
        <tr><td>${esc(s.slot_date)}</td><td>${esc(String(s.start_time).slice(0,5))}</td>
        <td>${esc(String(s.end_time).slice(0,5))}</td><td><span class="edu-badge">${esc(s.status)}</span></td></tr>`).join('');

    return `<div class="edu-panel"><h2>📅 برنامه کلاس‌ها — Org Admin</h2>
        <div class="edu-field"><label>مؤسسه</label><select id="edu-sched-org">${opts}</select></div>
        <table class="edu-table"><thead><tr><th>تاریخ</th><th>شروع</th><th>پایان</th><th>وضعیت</th></tr></thead>
        <tbody>${rows || '<tr><td colspan="4">اسلاتی نیست</td></tr>'}</tbody></table>
        <div class="edu-panel edu-panel--inner" style="margin-top:16px">
            <h3 class="edu-subtitle">افزودن اسلات</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>تاریخ</label><input type="date" id="edu-slot-date"></div>
                <div class="edu-field"><label>شروع</label><input type="time" id="edu-slot-start" value="09:00"></div>
                <div class="edu-field"><label>پایان</label><input type="time" id="edu-slot-end" value="11:00"></div>
            </div>
            <button class="edu-btn edu-btn--sm" id="edu-add-slot">ثبت اسلات available</button>
        </div>
    </div>`;
}

export function renderEducatorProfile(ed) {
    const p = ed?.profile || {};
    const acv = (p.academic_cv || []).map(c =>
        `<li>${esc(c.degree || c.title || '')} — ${c.years || ''} سال</li>`).join('') || '<li>—</li>';
    const skills = (p.skill_cv || []).map(s => `<span class="edu-pill">${esc(s)}</span>`).join('');
    const modes = (ed.delivery_modes || []).map(m => `<span class="edu-badge">${esc(m)}</span>`).join('');
    const venues = (ed.venue_types || []).map(v => `<span class="edu-badge">${esc(v)}</span>`).join('');

    return `<div class="edu-panel"><h2>رزومه حرفه‌ای ۳۶۰°</h2>
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${esc(ed.educator_type || 'mentor')}</strong><span>نقش</span></div>
            <div class="edu-stat"><strong>${esc(ed.verified_status || 'pending')}</strong><span>وضعیت</span></div>
            <div class="edu-stat"><strong>${ed.rating_avg || '—'}</strong><span>امتیاز</span></div>
            <div class="edu-stat"><strong>${fmt(ed.hourly_rate)}</strong><span>نرخ/ساعت</span></div>
        </div>
        <h3 class="edu-subtitle">سوابق تحصیلی / حرفه‌ای</h3>
        <ul class="edu-cv-list">${acv}</ul>
        <h3 class="edu-subtitle">حوزه‌های تخصص</h3>
        <div class="edu-pill-row">${skills || '—'}</div>
        <h3 class="edu-subtitle">نحوه برگزاری</h3>
        <p>${modes}</p>
        <h3 class="edu-subtitle">محل تدریس</h3>
        <p>${venues}</p>
        <div class="edu-panel edu-panel--inner">
            <h3 class="edu-subtitle">ویرایش</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>نوع</label><select id="edu-e-type">
                    <option value="mentor" ${ed.educator_type==='mentor'?'selected':''}>مربی</option>
                    <option value="teacher" ${ed.educator_type==='teacher'?'selected':''}>معلم</option></select></div>
                <div class="edu-field"><label>نرخ ساعتی</label><input id="edu-e-rate" type="number" value="${ed.hourly_rate || 800000}"></div>
            </div>
            <button class="edu-btn edu-btn--sm" id="edu-save-educator">ذخیره</button>
        </div>
    </div>`;
}

export function renderSessionDetail(session) {
    if (!session) return '<p class="edu-muted">جلسه یافت نشد</p>';
    const quote = session.quote?.lines || [];
    const costs = session.costs || {};
    return `<div class="edu-panel edu-panel--inner edu-session-detail">
        <h3>جلسه #${session.id} — ${esc(session.domain)}</h3>
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${esc(session.status)}</strong><span>وضعیت</span></div>
            <div class="edu-stat"><strong>${esc(session.venue_type)}</strong><span>محل</span></div>
            <div class="edu-stat"><strong>${session.distance_km || 0} km</strong><span>فاصله</span></div>
            <div class="edu-stat"><strong>${fmt(session.amount_total)}</strong><span>مبلغ</span></div>
        </div>
        <h4 class="edu-subtitle">پیش‌فاکتور / بهای تمام‌شده</h4>
        <div class="edu-quote-lines">
            ${quote.map(l => `<div><span>${esc(l.label)}</span><span>${fmt(l.amount)}</span></div>`).join('')}
            ${costs.mentor_fee ? `<div class="edu-muted" style="margin-top:8px">ثبت‌شده: مربی ${fmt(costs.mentor_fee)} · سربار ${fmt(costs.overhead)}</div>` : ''}
        </div>
        ${session.report?.summary ? `<p><strong>گزارش:</strong> ${esc(session.report.summary)}</p>` : ''}
    </div>`;
}

export function renderSessionsList(sessions, detailHtml = '') {
    const rows = (sessions || []).map(s => `
        <tr class="edu-session-row" data-session-id="${s.id}">
            <td>${s.id}</td><td>${esc(s.domain)}</td><td>${esc(s.venue_type)}</td>
            <td><span class="edu-badge">${esc(s.status)}</span></td>
            <td>${fmt(s.amount_total)}</td>
            <td><button class="edu-btn edu-btn--sm edu-btn--ghost edu-session-view" data-sid="${s.id}">جزئیات</button></td>
        </tr>`).join('');
    return `<div class="edu-panel"><h2>جلسات</h2>
        <table class="edu-table"><thead><tr><th>#</th><th>حوزه</th><th>محل</th><th>وضعیت</th><th>مبلغ</th><th></th></tr></thead>
        <tbody>${rows || '<tr><td colspan="6">جلسه‌ای نیست</td></tr>'}</tbody></table>
        <div id="edu-session-detail-mount">${detailHtml}</div>
    </div>`;
}

export function renderAccountingEnhanced(pending, splitsHtml = '') {
    const rows = (pending || []).map(s => `
        <tr><td>#${s.id}</td><td>${esc(s.domain)}</td><td>${fmt(s.amount_total)}</td>
        <td><button class="edu-btn edu-btn--sm" data-post="${s.id}">قطعی</button>
        <button class="edu-btn edu-btn--sm edu-btn--ghost edu-splits-btn" data-sid="${s.id}">تفکیک</button></td></tr>`).join('');
    return `<div class="edu-panel"><h2>حسابداری — Graph ERP</h2>
        <table class="edu-table"><thead><tr><th>جلسه</th><th>حوزه</th><th>مبلغ</th><th></th></tr></thead>
        <tbody>${rows || '<tr><td colspan="4">صف خالی</td></tr>'}</tbody></table>
        <div id="edu-splits-mount">${splitsHtml}</div>
        <p style="margin-top:12px"><a href="/acc-engine/education-accounting.php" class="edu-link">دفتر کل · سرفصل‌ها · تراز ↗</a></p>
    </div>`;
}

export function renderSplits(splits) {
    if (!splits?.length) return '<p class="edu-muted">تفکیکی نیست</p>';
    return `<div class="edu-panel edu-panel--inner"><h4>تفکیک حق‌الزحمه</h4>
        <table class="edu-table"><thead><tr><th>نوع</th><th>مبلغ</th></tr></thead>
        <tbody>${splits.map(s => `<tr><td>${esc(s.entity_type)}</td><td>${fmt(s.amount)}</td></tr>`).join('')}</tbody></table></div>`;
}

export function renderBookForm(meta, orgs) {
    const m = meta || {};
    const st = m.session_types || {};
    const dom = m.skill_domains || {};
    const dm = m.delivery_modes || {};
    const vt = m.venue_types || {};
    const orgOpts = (orgs || []).map(o => `<option value="${o.id}">${esc(o.name)} (${esc(o.city)})</option>`).join('');
    return `<div class="edu-panel"><h2>رزرو جلسه — پیش‌فاکتور شفاف</h2>
        <div class="edu-grid-2">
            <div class="edu-field"><label>نوع</label><select id="edu-b-stype">${Object.entries(st).map(([k,v])=>`<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
            <div class="edu-field"><label>حوزه</label><select id="edu-b-domain">${Object.entries(dom).map(([k,v])=>`<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
            <div class="edu-field"><label>برگزاری</label><select id="edu-b-delivery">${Object.entries(dm).map(([k,v])=>`<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
            <div class="edu-field"><label>محل</label><select id="edu-b-venue">${Object.entries(vt).map(([k,v])=>`<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
            <div class="edu-field"><label>مؤسسه (اختیاری)</label><select id="edu-b-org"><option value="">—</option>${orgOpts}</select></div>
            <div class="edu-field"><label>مدت (دقیقه)</label><input id="edu-b-dur" type="number" value="90"></div>
            <div class="edu-field"><label>فاصله km (منزل — یا خودکار از GIS)</label><input id="edu-b-km" type="number" value="0" placeholder="0 = محاسبه خودکار"></div>
        </div>
        <button class="edu-btn edu-btn--sm" id="edu-calc-quote">محاسبه پیش‌فاکتور</button>
        <button class="edu-btn edu-btn--sm edu-btn--ghost" id="edu-submit-session">ثبت درخواست</button>
        <div id="edu-quote-box"></div>
    </div>`;
}
