/**
 * EduLifeCompanion — همراه مادام‌العمر · پروفایل · مسیر زندگی · بودجه
 */
import { esc, fmt } from './EduPanels.js';

export function renderCompanion(state, section = 'overview') {
    const profile = state?.profile || {};
    const path = state?.life_path || {};
    const schema = state?.schema || {};
    const learner = state?.learner || {};
    const comp = path.completeness || { pct: 0, missing: [] };

    const nav = [
        { key: 'overview', label: 'نمای کلی', icon: '🏠' },
        { key: 'identity', label: 'مشخصات', icon: '👤' },
        { key: 'history', label: 'سوابق', icon: '📚' },
        { key: 'reports', label: 'کارنامه', icon: '📄' },
        { key: 'trend', label: 'نمودار روند', icon: '📈' },
        { key: 'career', label: 'آینده', icon: '🎯' },
        { key: 'budget', label: 'بودجه', icon: '💰' },
        { key: 'parent', label: 'خانواده', icon: '👪' },
        { key: 'matching', label: 'Matching', icon: '🔗' },
        { key: 'path', label: 'مسیر', icon: '🗺' },
    ];

    return `<div class="edu-companion">
        <div class="edu-companion-hero">
            <div>
                <h2>همراه هوشمند EduBrain</h2>
                <p class="edu-muted">از کلاس اول — یا هر مقطعی که می‌پیوندید — تا مسیر شغلی</p>
            </div>
            <div class="edu-companion-progress" title="تکمیل پروفایل">
                <svg viewBox="0 0 36 36" class="edu-ring"><path class="edu-ring__bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                <path class="edu-ring__fill" stroke-dasharray="${comp.pct}, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                <text x="18" y="20.35" class="edu-ring__text">${comp.pct}%</text></svg>
            </div>
        </div>
        <nav class="edu-companion-nav">
            ${nav.map(n => `<button type="button" class="edu-companion-nav__btn ${section === n.key ? 'active' : ''}" data-comp-section="${n.key}">${n.icon} ${n.label}</button>`).join('')}
        </nav>
        <div id="edu-companion-body">
            ${section === 'overview' ? renderOverview(state, comp) : ''}
            ${section === 'identity' ? renderIdentity(profile, schema, learner) : ''}
            ${section === 'history' ? renderHistory(profile, schema) : ''}
            ${section === 'reports' ? renderReportImport(profile, schema) : ''}
            ${section === 'trend' ? renderGradeChart(state?.chart || {}) : ''}
            ${section === 'career' ? renderCareer(profile, schema) : ''}
            ${section === 'budget' ? renderBudget(profile, schema, path) : ''}
            ${section === 'parent' ? renderParentStatus(profile, path) : ''}
            ${section === 'matching' ? renderMatching(state?.matching || {}) : ''}
            ${section === 'path' ? renderLifePath(path) : ''}
        </div>
    </div>`;
}

export function renderOverview(state, comp) {
    const path = state?.life_path || {};
    const trend = path.academic_trend || {};
    const budget = path.budget || {};
    const missing = (comp.missing || []).map(m => ({
        identity: 'مشخصات', academic_history: 'سوابق تحصیلی', career: 'اهداف شغلی',
        family_budget: 'بودجه', grade_level: 'پایه فعلی',
    }[m] || m)).join(' · ');

    return `<div class="edu-panel edu-panel--flat">
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${trend.grades_count || 0}</strong><span>پایه ثبت‌شده</span></div>
            <div class="edu-stat"><strong>${trend.avg ?? '—'}</strong><span>میانگین معدل</span></div>
            <div class="edu-stat"><strong>${budget.tier_label || '—'}</strong><span>سطح بودجه</span></div>
        </div>
        ${missing ? `<div class="edu-alert edu-alert--warn" style="margin-top:16px">برای مسیر دقیق‌تر تکمیل کنید: ${esc(missing)}</div>` : ''}
        <p class="edu-muted" style="margin-top:12px">${esc(path.advisor_note || '')}</p>
        <div class="edu-form-actions">
            <button type="button" class="edu-btn edu-btn--accent edu-btn--sm" data-comp-section="history">ثبت سوابق تحصیلی</button>
            <button type="button" class="edu-btn edu-btn--primary edu-btn--sm" data-comp-section="path">مشاهده مسیر زندگی</button>
        </div>
    </div>`;
}

function renderIdentity(profile, schema, learner) {
    const id = profile.identity || {};
    const grades = schema.grades || {};
    return `<form id="edu-comp-identity-form" class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">مشخصات دانش‌آموز</h3>
        <div class="edu-grid-2">
            <div class="edu-field"><label>نام کامل</label><input name="full_name" value="${esc(id.full_name || '')}"></div>
            <div class="edu-field"><label>سال تولد</label><input name="birth_year" type="number" value="${esc(id.birth_year || '')}" placeholder="1390"></div>
            <div class="edu-field"><label>پایه فعلی *</label>
                <select name="grade_level">${Object.entries(grades).map(([k,v]) =>
                    `<option value="${k}" ${learner.grade_level === k ? 'selected' : ''}>${esc(v)}</option>`).join('')}</select></div>
            <div class="edu-field"><label>پایه ورود به پورتال</label>
                <select name="entry_grade">${Object.entries(grades).map(([k,v]) =>
                    `<option value="${k}" ${id.entry_grade === k ? 'selected' : ''}>${esc(v)}</option>`).join('')}</select>
                <span class="edu-muted">اگر الان join می‌کنید — از کدام پایه سوابق را وارد می‌کنید؟</span></div>
            <div class="edu-field"><label>شهر</label><input name="city" value="${esc(id.city || '')}"></div>
        </div>
        <button type="submit" class="edu-btn edu-btn--primary edu-btn--sm">ذخیره مشخصات</button>
    </form>`;
}

function renderHistory(profile, schema) {
    const grades = schema.grades || {};
    const rows = profile.academic_history || [];
    const rowHtml = (r, i) => `
        <div class="edu-history-row" data-idx="${i}">
            <div class="edu-grid-2">
                <div class="edu-field"><label>پایه</label><select class="edu-h-grade">
                    ${Object.entries(grades).filter(([k]) => k !== 'graduate').map(([k,v]) =>
                        `<option value="${k}" ${r.grade === k ? 'selected' : ''}>${esc(v)}</option>`).join('')}</select></div>
                <div class="edu-field"><label>سال تحصیلی</label><input class="edu-h-year" value="${esc(r.year || '')}" placeholder="1402"></div>
                <div class="edu-field"><label>نام مدرسه</label><input class="edu-h-school" value="${esc(r.school_name || '')}"></div>
                <div class="edu-field"><label>نام معلم (اصلی)</label><input class="edu-h-teacher" value="${esc(r.teacher_name || '')}"></div>
                <div class="edu-field"><label>معدل کارنامه</label><input class="edu-h-avg" type="number" step="0.01" min="0" max="20" value="${r.report_avg ?? ''}"></div>
                <div class="edu-field edu-field--full"><label>یادداشت</label><input class="edu-h-notes" value="${esc(r.notes || '')}" placeholder="رتبه، افتخارات…"></div>
            </div>
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm edu-h-remove">حذف</button>
        </div>`;

    return `<div class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">سوابق تحصیلی — از کلاس اول</h3>
        <p class="edu-muted">هر پایه: مدرسه، معلم، کارنامه. اگر تازه پیوسته‌اید، از پایه فعلی شروع کنید و gradually قبلی‌ها را اضافه کنید.</p>
        <div id="edu-history-rows">${rows.length ? rows.map(rowHtml).join('') : rowHtml({}, 0)}</div>
        <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-add-history-row">+ پایه تحصیلی</button>
        <button type="button" class="edu-btn edu-btn--secondary edu-btn--sm" id="edu-save-history">ذخیره سوابق</button>
    </div>`;
}

function renderCareer(profile, schema) {
    const c = profile.career || {};
    const careers = schema.career_catalog || {};
    const domains = schema.grades ? {} : {};
    const skillOpts = ['math','physics','english','music','programming','art','sport','language'];
    const domainLabels = { math:'ریاضی', physics:'فیزیک', english:'انگلیسی', music:'موسیقی', programming:'برنامه‌نویسی', art:'هنر', sport:'ورزش', language:'زبان' };

    const jobChecks = Object.entries(careers).map(([k, v]) => `
        <label class="edu-check"><input type="checkbox" name="dream_jobs" value="${k}" ${(c.dream_jobs||[]).includes(k)?'checked':''}> ${esc(v)}</label>`).join('');
    const skillChecks = skillOpts.map(k => `
        <label class="edu-check"><input type="checkbox" name="skills_wanted" value="${k}" ${(c.skills_wanted||[]).includes(k)?'checked':''}> ${esc(domainLabels[k]||k)}</label>`).join('');

    return `<form id="edu-comp-career-form" class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">شغل مورد علاقه و مهارت‌ها</h3>
        <div class="edu-field"><label>مشاغل رویایی</label><div class="edu-check-grid">${jobChecks}</div></div>
        <div class="edu-field"><label>مهارت‌هایی که دوست دارید یاد بگیرید</label><div class="edu-check-grid">${skillChecks}</div></div>
        <div class="edu-field"><label>دانشگاه / هدف تحصیلی</label>
            <input name="university_targets" value="${esc((c.university_targets||[]).join('، '))}" placeholder="مثال: شهید بهشتی، سمپاد"></div>
        <div class="edu-field"><label>ارزش‌ها و علایق</label>
            <input name="interests" value="${esc((c.interests||[]).join('، '))}" placeholder="کمک به دیگران، خلاقیت…"></div>
        <button type="submit" class="edu-btn edu-btn--accent edu-btn--sm">ذخیره اهداف</button>
    </form>`;
}

function renderBudget(profile, schema, path) {
    const f = profile.family || {};
    const tiers = schema.budget_tiers || {};
    const budget = path.budget || {};
    const tierOpts = Object.entries(tiers).map(([k, t]) =>
        `<option value="${k}" ${f.budget_tier === k ? 'selected' : ''}>${esc(t.label)} — ${esc(t.hint||'')}</option>`).join('');

    return `<form id="edu-comp-budget-form" class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">بودجه آموزشی خانواده</h3>
        <p class="edu-muted">مسیر پیشنهادی با مبلغی که خانواده مایل است ماهانه هزینه کند هماهنگ می‌شود.</p>
        <div class="edu-grid-2">
            <div class="edu-field"><label>بودجه ماهانه (ریال)</label>
                <input name="monthly_budget_rial" type="number" value="${f.monthly_budget_rial || ''}" placeholder="5000000"></div>
            <div class="edu-field"><label>سطح</label><select name="budget_tier">${tierOpts}</select></div>
            <div class="edu-field"><label>نام والد / سرپرست</label><input name="parent_name" value="${esc(f.parent_name||'')}"></div>
            <div class="edu-field"><label>تماس</label><input name="parent_phone" dir="ltr" value="${esc(f.parent_phone||'')}"></div>
        </div>
        ${budget.estimated_monthly_spend ? `<div class="edu-alert ${budget.within_budget ? '' : 'edu-alert--warn'}" style="margin-top:12px">
            تخمین هزینه پیشنهادی: <strong>${fmt(budget.estimated_monthly_spend)}</strong> ریال/ماه
            (${budget.suggested_sessions_per_month} جلسه) — ${budget.within_budget ? '✓ در بودجه' : '⚠ ممکن است از بودجه بیشتر شود'}
        </div>` : ''}
        <button type="submit" class="edu-btn edu-btn--primary edu-btn--sm">ذخیره بودجه</button>
    </form>`;
}

export function renderLifePath(path) {
    const phases = path?.phases || [];
    const trend = path?.academic_trend || {};
    const budget = path?.budget || {};

    return `<div class="edu-lifepath">
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${trend.avg ?? '—'}</strong><span>میانگین معدل</span></div>
            <div class="edu-stat"><strong>${{ rising:'صعودی', declining:'نزولی', stable:'ثابت', unknown:'—' }[trend.trend] || trend.trend}</strong><span>روند</span></div>
            <div class="edu-stat"><strong>${esc(budget.tier_label||'—')}</strong><span>بودجه</span></div>
        </div>
        ${phases.map(ph => `
            <div class="edu-lifepath-phase edu-lifepath-phase--${ph.horizon}">
                <h3>${esc(ph.label)}</h3>
                <ul>${(ph.items||[]).map(i => `<li>${esc(i)}</li>`).join('')}</ul>
            </div>`).join('')}
        <p class="edu-muted">${esc(path.advisor_note || '')}</p>
    </div>`;
}

export function renderEducatorFull(ed, meta) {
    const p = ed?.profile || {};
    const domains = meta?.skill_domains || {};
    const acvRows = (p.academic_cv || []).map((c, i) => `
        <div class="edu-cv-row" data-idx="${i}">
            <input class="edu-cv-degree" placeholder="مدرک" value="${esc(c.degree||c.title||'')}">
            <input class="edu-cv-inst" placeholder="مؤسسه" value="${esc(c.institution||'')}">
            <input class="edu-cv-years" type="number" placeholder="سال" value="${c.years||''}">
        </div>`).join('') || '<div class="edu-cv-row"><input class="edu-cv-degree" placeholder="مدرک"><input class="edu-cv-inst" placeholder="مؤسسه"><input class="edu-cv-years" type="number" placeholder="سال"></div>';

    const workRows = (p.work_history || []).map((w, i) => `
        <div class="edu-work-row" data-idx="${i}">
            <input class="edu-w-org" placeholder="مؤسسه/مدرسه" value="${esc(w.org||'')}">
            <input class="edu-w-role" placeholder="سمت" value="${esc(w.role||'')}">
            <input class="edu-w-years" type="number" placeholder="سال" value="${w.years||''}">
            <input class="edu-w-subject" placeholder="درس" value="${esc(w.subject||'')}">
        </div>`).join('') || '<div class="edu-work-row"><input class="edu-w-org" placeholder="مؤسسه"><input class="edu-w-role" placeholder="سمت"><input class="edu-w-years" type="number"><input class="edu-w-subject" placeholder="درس"></div>';

    const skillTags = Object.entries(domains).map(([k,v]) => {
        const on = (p.skill_cv||[]).includes(k);
        return `<label class="edu-check"><input type="checkbox" class="edu-skill-cv" value="${k}" ${on?'checked':''}> ${esc(v)}</label>`;
    }).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>${fmt(ed.hourly_rate)}</strong><span>نرخ/ساعت</span></div>
        </div>
        <section class="edu-form-section edu-panel--inner">
            <h3 class="edu-subtitle">سوابق تحصیلی</h3>
            <div id="edu-cv-rows">${acvRows}</div>
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-add-cv">+ مدرک</button>
        </section>
        <section class="edu-form-section edu-panel--inner">
            <h3 class="edu-subtitle">سوابق کاری (مدارس · مؤسسات)</h3>
            <div id="edu-work-rows">${workRows}</div>
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-add-work">+ سابقه کاری</button>
        </section>
        <section class="edu-form-section edu-panel--inner">
            <h3 class="edu-subtitle">حوزه‌های تخصص</h3>
            <div class="edu-check-grid">${skillTags}</div>
        </section>
        <section class="edu-form-section 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 class="edu-field edu-field--full"><label>بیوگرافی</label><textarea id="edu-e-bio" rows="3">${esc(p.bio||'')}</textarea></div>
            </div>
        </section>
        <button class="edu-btn edu-btn--accent" id="edu-save-educator-full">ذخیره رزومه کامل</button>
    </div>`;
}

export function renderOrgFacilities(org, meta) {
    const p = org?.profile || {};
    const facTypes = meta?.facility_types || {};
    const selected = p.facilities || [];
    const checks = Object.entries(facTypes).map(([k, v]) =>
        `<label class="edu-check"><input type="checkbox" class="edu-fac-cb" value="${k}" ${selected.includes(k)?'checked':''}> ${esc(v)}</label>`).join('');
    const resources = (org.resources || []).map(r =>
        `<li>${esc(r.name)} — ظرفیت ${r.capacity} · ${fmt(r.price_per_hour)}/ساعت</li>`).join('') || '<li>—</li>';

    return `<div class="edu-panel"><h2>${esc(org.name)} — امکانات</h2>
        <p class="edu-muted">${esc(org.city||'')} · ${esc(org.address_text||'')}</p>
        <section class="edu-form-section edu-panel--inner">
            <h3 class="edu-subtitle">امکانات آموزشی</h3>
            <div class="edu-check-grid edu-check-grid--3">${checks}</div>
        </section>
        <section class="edu-form-section edu-panel--inner">
            <h3 class="edu-subtitle">فضاها و منابع</h3>
            <ul class="edu-cv-list">${resources}</ul>
        </section>
        <div class="edu-grid-2">
            <div class="edu-field"><label>برنامه‌های فعال</label>
                <input id="edu-org-programs" value="${esc((p.programs||[]).join('، '))}" placeholder="کنکور، موسیقی، زبان…"></div>
            <div class="edu-field"><label>توضیح امکانات</label>
                <textarea id="edu-org-fac-notes" rows="2">${esc(p.facility_notes||'')}</textarea></div>
        </div>
        <button class="edu-btn edu-btn--primary edu-btn--sm" id="edu-save-org-fac">ذخیره امکانات</button>
    </div>`;
}

function renderReportImport(profile, schema) {
    const grades = schema.grades || {};
    const cards = profile.report_cards || [];
    const gradeOpts = Object.entries(grades).filter(([k]) => k !== 'graduate').map(([k, v]) =>
        `<option value="${k}">${esc(v)}</option>`).join('');
    const list = cards.length ? cards.map(c => `
        <div class="edu-report-item">
            <div class="edu-report-item__meta">
                <strong>${esc(grades[c.grade] || c.grade || '—')}</strong>
                <span class="edu-muted">${esc(c.year || '')}</span>
                <span class="edu-pill edu-pill--${c.status === 'parsed' ? 'ok' : 'warn'}">${c.status === 'parsed' ? 'ثبت‌شده' : 'در انتظار'}</span>
            </div>
            <div class="edu-report-item__avg">${c.parsed_avg != null ? `معدل: ${c.parsed_avg}` : '—'}</div>
            ${c.url ? `<a class="edu-btn edu-btn--ghost edu-btn--sm" href="${esc(c.url)}" target="_blank" rel="noopener">مشاهده فایل</a>` : ''}
        </div>`).join('') : '<p class="edu-muted">هنوز کارنامه‌ای بارگذاری نشده.</p>';

    return `<div class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">بارگذاری کارنامه</h3>
        <p class="edu-muted">JPG، PNG یا PDF — معدل به سوابق تحصیلی merge می‌شود.</p>
        <form id="edu-report-import-form" class="edu-upload-zone">
            <div class="edu-grid-2">
                <div class="edu-field"><label>پایه *</label><select name="grade" required>${gradeOpts}</select></div>
                <div class="edu-field"><label>سال تحصیلی</label><input name="year" placeholder="1403"></div>
                <div class="edu-field"><label>معدل (در صورت نبود OCR)</label><input name="report_avg" type="number" step="0.01" min="0" max="20"></div>
                <div class="edu-field"><label>نام مدرسه</label><input name="school_name"></div>
                <div class="edu-field edu-field--full"><label>یادداشت</label><input name="notes"></div>
                <div class="edu-field edu-field--full">
                    <label>فایل کارنامه *</label>
                    <input type="file" name="report" accept="image/jpeg,image/png,image/webp,application/pdf" required>
                </div>
            </div>
            <button type="submit" class="edu-btn edu-btn--accent edu-btn--sm">بارگذاری و ثبت</button>
        </form>
        <h3 class="edu-subtitle" style="margin-top:24px">کارنامه‌های ثبت‌شده</h3>
        <div class="edu-report-list">${list}</div>
    </div>`;
}

function renderGradeChart(chart) {
    const labels = chart.labels || [];
    const values = chart.values || [];
    const max = chart.max || 20;
    const trend = { rising: 'صعودی ↗', declining: 'نزولی ↘', stable: 'ثابت →', unknown: '—' }[chart.trend] || chart.trend;
    if (!labels.length) {
        return `<div class="edu-panel edu-panel--flat"><h3 class="edu-subtitle">نمودار روند معدل</h3>
            <p class="edu-muted">پس از ثبت سوابق یا import کارنامه، نمودار اینجا نمایش داده می‌شود.</p></div>`;
    }
    const bars = labels.map((lb, i) => {
        const v = values[i];
        const pct = v != null ? Math.round((v / max) * 100) : 0;
        return `<div class="edu-chart-bar">
            <div class="edu-chart-bar__col"><div class="edu-chart-bar__fill" style="height:${pct}%"></div></div>
            <span class="edu-chart-bar__val">${v != null ? v : '—'}</span>
            <span class="edu-chart-bar__lbl">${esc(lb)}</span>
        </div>`;
    }).join('');
    return `<div class="edu-panel edu-panel--flat">
        <div class="edu-chart-head">
            <h3 class="edu-subtitle">روند معدل پایه‌به‌پایه</h3>
            <span class="edu-pill edu-pill--info">روند: ${esc(trend)}</span>
        </div>
        <div class="edu-chart">${bars}</div>
    </div>`;
}

function renderParentStatus(profile, path) {
    const f = profile.family || {};
    const budget = path.budget || {};
    const approved = !!f.budget_approved;
    return `<div class="edu-panel edu-panel--flat">
        <h3 class="edu-subtitle">وضعیت خانواده و بودجه</h3>
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${fmt(f.monthly_budget_rial || 0)}</strong><span>بودجه ماهانه</span></div>
            <div class="edu-stat"><strong>${esc(budget.tier_label || f.budget_tier || '—')}</strong><span>سطح</span></div>
            <div class="edu-stat"><strong>${approved ? '✓ تأیید' : '⏳ در انتظار'}</strong><span>تأیید والد</span></div>
        </div>
        ${f.parent_name ? `<p class="edu-muted">والد: ${esc(f.parent_name)} ${f.parent_phone ? '· ' + esc(f.parent_phone) : ''}</p>` : ''}
        ${approved && f.budget_approved_at ? `<p class="edu-muted">تأیید در: ${esc(f.budget_approved_at)}</p>` : ''}
        ${f.parent_notes ? `<div class="edu-alert" style="margin-top:12px">${esc(f.parent_notes)}</div>` : ''}
        <div class="edu-form-actions" style="margin-top:16px">
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" data-comp-section="budget">ویرایش بودجه</button>
            ${!approved ? `<button type="button" class="edu-btn edu-btn--secondary edu-btn--sm" id="edu-learner-request-approve">درخواست تأیید والد</button>` : ''}
        </div>
    </div>`;
}

function renderMatching(matching) {
    const domain = matching.domain || 'math';
    const domains = { math: 'ریاضی', physics: 'فیزیک', english: 'انگلیسی', music: 'موسیقی', programming: 'برنامه‌نویسی', biology: 'زیست' };
    const domainOpts = Object.entries(domains).map(([k, v]) =>
        `<option value="${k}" ${domain === k ? 'selected' : ''}>${esc(v)}</option>`).join('');
    const orgRows = (matching.orgs || []).map(o => `
        <div class="edu-match-card">
            <div class="edu-match-card__head">
                <strong>${esc(o.org?.name || '—')}</strong>
                <span class="edu-match-score">${o.score}%</span>
            </div>
            <div class="edu-match-bar"><div class="edu-match-bar__fill" style="width:${o.score}%"></div></div>
            <p class="edu-muted">${esc(o.reason || '')}</p>
        </div>`).join('') || '<p class="edu-muted">پیشنهادی یافت نشد.</p>';
    const eduRows = (matching.educators || []).map(e => `
        <div class="edu-match-card">
            <div class="edu-match-card__head">
                <strong>${esc(e.educator?.display_name || e.educator?.user_login || '—')}</strong>
                <span class="edu-match-score">${e.score}%</span>
            </div>
            <div class="edu-match-bar"><div class="edu-match-bar__fill edu-match-bar__fill--accent" style="width:${e.score}%"></div></div>
            <p class="edu-muted">${esc(e.reason || '')} · ${fmt(e.educator?.hourly_rate)}/ساعت</p>
        </div>`).join('') || '<p class="edu-muted">مربی پیشنهادی یافت نشد.</p>';

    return `<div class="edu-panel edu-panel--flat">
        <div class="edu-chart-head">
            <h3 class="edu-subtitle">Matching — مدرسه و مربی</h3>
            <select id="edu-match-domain" class="edu-select-sm">${domainOpts}</select>
        </div>
        <p class="edu-muted">بر اساس بودجه خانواده، امکانات مؤسسه و حوزه مهارت.</p>
        <h4 class="edu-subtitle edu-subtitle--sm">مؤسسات پیشنهادی</h4>
        <div class="edu-match-list">${orgRows}</div>
        <h4 class="edu-subtitle edu-subtitle--sm" style="margin-top:20px">مربیان پیشنهادی</h4>
        <div class="edu-match-list">${eduRows}</div>
    </div>`;
}

export function renderParentDashboard(data) {
    if (!data?.success) {
        return `<div class="edu-panel"><h2>پنل والدین</h2>
            <div class="edu-alert edu-alert--warn">${esc(data?.message || 'فرزند متصل نیست')}</div></div>`;
    }
    const st = data.companion || {};
    const profile = st.profile || {};
    const f = profile.family || {};
    const path = st.life_path || {};
    const name = data.student_name || profile.identity?.full_name || 'فرزند';
    return `<div class="edu-parent-dash">
        <div class="edu-companion-hero">
            <div><h2>پنل والدین — ${esc(name)}</h2>
                <p class="edu-muted">پیگیری تحصیلی · بودجه · پیشنهاد مؤسسه/مربی</p></div>
        </div>
        <div class="edu-stat-row">
            <div class="edu-stat"><strong>${esc(st.learner?.grade_level || '—')}</strong><span>پایه</span></div>
            <div class="edu-stat"><strong>${path.academic_trend?.avg ?? '—'}</strong><span>میانگین</span></div>
            <div class="edu-stat"><strong>${f.budget_approved ? '✓' : '⏳'}</strong><span>بودجه</span></div>
        </div>
        ${renderGradeChart(data.chart || {})}
        <form id="edu-parent-approve-form" class="edu-panel edu-panel--flat" style="margin-top:16px">
            <h3 class="edu-subtitle">تأیید بودجه آموزشی</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>بودجه ماهانه (ریال)</label>
                    <input name="monthly_budget_rial" type="number" value="${f.monthly_budget_rial || ''}"></div>
                <div class="edu-field"><label>یادداشت والد</label>
                    <input name="parent_notes" value="${esc(f.parent_notes || '')}"></div>
            </div>
            <input type="hidden" name="learner_user_id" value="${data.learner_user_id || ''}">
            <button type="submit" class="edu-btn edu-btn--primary edu-btn--sm">${f.budget_approved ? 'به‌روزرسانی تأیید' : 'تأیید بودجه'}</button>
        </form>
        <div style="margin-top:16px">${renderMatching(data.matching || {})}</div>
    </div>`;
}

export function renderCompanionSection(state, section) {
    const profile = state?.profile || {};
    const path = state?.life_path || {};
    const schema = state?.schema || {};
    const learner = state?.learner || {};
    const comp = path.completeness || { pct: 0, missing: [] };
    switch (section) {
        case 'identity': return renderIdentity(profile, schema, learner);
        case 'history': return renderHistory(profile, schema);
        case 'reports': return renderReportImport(profile, schema);
        case 'trend': return renderGradeChart(state?.chart || {});
        case 'career': return renderCareer(profile, schema);
        case 'budget': return renderBudget(profile, schema, path);
        case 'parent': return renderParentStatus(profile, path);
        case 'matching': return renderMatching(state?.matching || {});
        case 'path': return renderLifePath(path);
        default: return renderOverview(state, comp);
    }
}

export function collectHistoryRows(root) {
    return [...root.querySelectorAll('.edu-history-row')].map(row => ({
        grade: row.querySelector('.edu-h-grade')?.value,
        year: row.querySelector('.edu-h-year')?.value,
        school_name: row.querySelector('.edu-h-school')?.value,
        teacher_name: row.querySelector('.edu-h-teacher')?.value,
        report_avg: parseFloat(row.querySelector('.edu-h-avg')?.value) || null,
        notes: row.querySelector('.edu-h-notes')?.value,
    })).filter(r => r.grade || r.school_name);
}

export function collectEducatorProfile(root) {
    const academic_cv = [...root.querySelectorAll('.edu-cv-row')].map(row => ({
        degree: row.querySelector('.edu-cv-degree')?.value,
        institution: row.querySelector('.edu-cv-inst')?.value,
        years: +(row.querySelector('.edu-cv-years')?.value || 0),
    })).filter(r => r.degree);
    const work_history = [...root.querySelectorAll('.edu-work-row')].map(row => ({
        org: row.querySelector('.edu-w-org')?.value,
        role: row.querySelector('.edu-w-role')?.value,
        years: +(row.querySelector('.edu-w-years')?.value || 0),
        subject: row.querySelector('.edu-w-subject')?.value,
    })).filter(r => r.org);
    const skill_cv = [...root.querySelectorAll('.edu-skill-cv:checked')].map(el => el.value);
    return {
        profile: { academic_cv, work_history, skill_cv, bio: root.querySelector('#edu-e-bio')?.value || '' },
        educator_type: root.querySelector('#edu-e-type')?.value,
        hourly_rate: +(root.querySelector('#edu-e-rate')?.value || 0),
    };
}
