/**
 * EduRequestFlow — درخواست استاندارد → آزمون آنلاین → نتیجه
 */
import { esc, fmt } from './EduPanels.js';

const ACADEMIC_TRACKS = ['konkur', 'tizhooshan', 'general'];
const SKILL_TRACKS = ['skill'];
const ACADEMIC_DOMAINS = ['math', 'physics', 'chemistry', 'biology', 'persian', 'english'];
const SKILL_DOMAINS = ['music', 'programming', 'art', 'sport', 'language'];

export function renderRequestWizard(meta, requests = [], step = 'form', ctx = {}) {
    const steps = [
        { key: 'form', label: '۱. درخواست', icon: '📋' },
        { key: 'test', label: '۲. آزمون آنلاین', icon: '📝' },
        { key: 'result', label: '۳. نتیجه', icon: '✅' },
    ];
    const stepIdx = steps.findIndex(s => s.key === step);

    return `<div class="edu-flow">
        <div class="edu-flow-hero">
            <h2>ثبت درخواست آموزشی</h2>
            <p class="edu-muted">کنکور · تقویتی · تیزهوشان · مهارت — استاندارد EduLoop / CDM</p>
        </div>
        <div class="edu-stepper">
            ${steps.map((s, i) => `
                <div class="edu-stepper__item ${i <= stepIdx ? 'edu-stepper__item--done' : ''} ${i === stepIdx ? 'edu-stepper__item--active' : ''}">
                    <span class="edu-stepper__icon">${s.icon}</span>
                    <span>${s.label}</span>
                </div>`).join('')}
        </div>
        <div id="edu-flow-body">
            ${step === 'form' ? renderRequestForm(meta, requests) : ''}
            ${step === 'test' ? renderOnlineTest(ctx) : ''}
            ${step === 'result' ? renderTestResult(ctx) : ''}
        </div>
    </div>`;
}

export function renderRequestForm(meta, requests = []) {
    const m = meta || {};
    const tracks = m.tracks || {};
    const domains = m.skill_domains || {};
    const grades = m.grade_levels || {};
    const goals = m.learning_goals || {};
    const dm = m.delivery_modes || {};
    const vt = m.venue_types || {};
    const st = m.session_types || {};

    const pending = (requests || []).filter(r => r.status === 'placement_pending');
    const pendingBanner = pending.length ? `
        <div class="edu-alert edu-alert--warn">
            <strong>${pending.length} درخواست در انتظار آزمون</strong>
            ${pending.map(r => `<button type="button" class="edu-btn edu-btn--accent edu-btn--sm edu-resume-test" data-rid="${r.id}">ادامه آزمون ${esc(r.ref_code)}</button>`).join(' ')}
        </div>` : '';

    const recent = (requests || []).slice(0, 5);
    const recentRows = recent.map(r => `
        <tr><td><code>${esc(r.ref_code)}</code></td>
        <td>${esc(st[r.session_type] || r.session_type)}</td>
        <td>${esc(domains[r.domain] || r.domain)}</td>
        <td><span class="edu-badge ${r.status === 'placement_done' ? 'edu-badge--ok' : ''}">${esc((m.request_statuses||{})[r.status] || r.status)}</span></td>
        <td>${r.status === 'placement_pending' ? `<button class="edu-btn edu-btn--sm edu-btn--accent edu-resume-test" data-rid="${r.id}">آزمون</button>` : ''}</td></tr>`).join('');

    return `${pendingBanner}
    <form class="edu-request-form" id="edu-request-form">
        <section class="edu-form-section">
            <h3 class="edu-form-section__title"><span class="edu-form-section__num">۱</span> مشخصات دانش‌آموز</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>نام و نام خانوادگی *</label><input name="full_name" required placeholder="مثال: سارا احمدی"></div>
                <div class="edu-field"><label>پایه تحصیلی *</label>
                    <select name="grade_level" required><option value="">انتخاب…</option>
                    ${Object.entries(grades).map(([k,v]) => `<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
                <div class="edu-field edu-field--full"><label>نام مدرسه</label><input name="school_name" placeholder="اختیاری"></div>
            </div>
        </section>
        <section class="edu-form-section">
            <h3 class="edu-form-section__title"><span class="edu-form-section__num">۲</span> نوع برنامه آموزشی</h3>
            <div class="edu-choice-cards" id="edu-stype-cards">
                <label class="edu-choice-card edu-choice-card--active" data-stype="academic">
                    <input type="radio" name="session_type" value="academic" checked>
                    <span class="edu-choice-card__icon">📚</span>
                    <strong>آموزش درسی</strong>
                    <span>کنکور · تقویتی · تیزهوشان</span>
                </label>
                <label class="edu-choice-card" data-stype="skill">
                    <input type="radio" name="session_type" value="skill">
                    <span class="edu-choice-card__icon">🎵</span>
                    <strong>آموزش غیردرسی</strong>
                    <span>مهارت · هنر · ورزش · استعداد‌یابی</span>
                </label>
            </div>
            <div class="edu-grid-2 edu-grid-2--mt">
                <div class="edu-field"><label>مسیر *</label>
                    <select name="track" id="edu-req-track" required>
                        ${ACADEMIC_TRACKS.map(k => `<option value="${k}">${esc(tracks[k]||k)}</option>`).join('')}
                    </select></div>
                <div class="edu-field"><label>حوزه / درس اصلی *</label>
                    <select name="domain" id="edu-req-domain" required>
                        ${ACADEMIC_DOMAINS.map(k => `<option value="${k}">${esc(domains[k]||k)}</option>`).join('')}
                    </select></div>
            </div>
            <div class="edu-field edu-field--full">
                <label>اهداف یادگیری *</label>
                <div class="edu-check-grid" id="edu-goals-grid">
                    ${Object.entries(goals).slice(0, 5).map(([k,v]) => `
                        <label class="edu-check"><input type="checkbox" name="goals" value="${k}"> ${esc(v)}</label>`).join('')}
                </div>
            </div>
        </section>
        <section class="edu-form-section">
            <h3 class="edu-form-section__title"><span class="edu-form-section__num">۳</span> نحوه برگزاری</h3>
            <div class="edu-grid-2">
                <div class="edu-field"><label>برگزاری *</label>
                    <select name="delivery_mode" required>${Object.entries(dm).map(([k,v]) => `<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
                <div class="edu-field"><label>محل ترجیحی *</label>
                    <select name="venue_type" required>${Object.entries(vt).map(([k,v]) => `<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
                <div class="edu-field"><label>ساعات هفتگی</label>
                    <select name="weekly_hours"><option value="">—</option><option value="2">۲ ساعت</option><option value="4">۴ ساعت</option><option value="6">۶+ ساعت</option></select></div>
                <div class="edu-field edu-field--full"><label>توضیحات</label><textarea name="notes" rows="2" placeholder="زمان ترجیحی، محدودیت‌ها…"></textarea></div>
            </div>
        </section>
        <section class="edu-form-section edu-form-section--consent">
            <label class="edu-check edu-check--consent">
                <input type="checkbox" name="consent_privacy" required>
                با ذخیره اطلاعات برای <strong>تعیین سطح</strong> و طراحی برنامه شخصی موافقم (GDPR / حریم خصوصی).
            </label>
        </section>
        <div class="edu-form-actions">
            <button type="submit" class="edu-btn edu-btn--accent" id="edu-submit-request">ثبت درخواست و ورود به آزمون ←</button>
        </div>
    </form>
    ${recent.length ? `<div class="edu-panel edu-panel--inner edu-panel--flat" style="margin-top:20px">
        <h3 class="edu-subtitle">درخواست‌های اخیر</h3>
        <table class="edu-table"><thead><tr><th>کد</th><th>نوع</th><th>حوزه</th><th>وضعیت</th><th></th></tr></thead>
        <tbody>${recentRows}</tbody></table></div>` : ''}`;
}

export function renderOnlineTest(ctx) {
    const test = ctx.test || {};
    const phase = test.phases?.[ctx.phaseIdx || 0];
    if (!phase) return `<div class="edu-err">آزمون بارگذاری نشد</div>`;

    const isLikert = phase.type === 'skill_talent';
    const questions = (phase.questions || []).map((q, qi) => {
        if (isLikert) {
            return `<div class="edu-q-card" data-qid="${esc(q.id)}">
                <div class="edu-q-card__num">${qi + 1}</div>
                <p class="edu-q-card__stem">${esc(q.stem)}</p>
                <div class="edu-likert">${[1,2,3,4,5].map(n => `
                    <label class="edu-likert__opt"><input type="radio" name="q_${q.id}" value="${n}"><span>${n}</span></label>`).join('')}
                </div>
                <div class="edu-likert-labels"><span>اصلاً</span><span>کاملاً</span></div>
            </div>`;
        }
        const hasChoices = q.choices?.length;
        if (hasChoices) {
            return `<div class="edu-q-card" data-qid="${esc(q.id)}">
                <div class="edu-q-card__num">${qi + 1}</div>
                <p class="edu-q-card__stem">${esc(q.stem)}</p>
                <div class="edu-mcq">${q.choices.map((c, ci) => `
                    <label class="edu-mcq__opt"><input type="radio" name="q_${q.id}" value="${ci}"><span>${esc(c)}</span></label>`).join('')}
                </div>
            </div>`;
        }
        return '';
    }).join('');

    const phaseNav = (test.phases || []).length > 1 ? `
        <div class="edu-phase-tabs">${test.phases.map((p, i) => `
            <span class="edu-phase-tab ${i === (ctx.phaseIdx||0) ? 'active' : ''}">${esc(p.title)}</span>`).join('')}</div>` : '';

    return `<div class="edu-test-panel">
        <div class="edu-test-head">
            <div><code>${esc(test.ref_code || '')}</code> · ${esc(test.domain_label || '')}</div>
            <div class="edu-test-timer" id="edu-test-timer">⏱ ${ctx.session_type === 'skill' ? '۲۵' : '۲۰'} دقیقه</div>
        </div>
        ${phaseNav}
        <h3 class="edu-subtitle">${esc(phase.title)}</h3>
        <p class="edu-muted">${isLikert ? 'هر جمله را از ۱ (اصلاً) تا ۵ (کاملاً) ارزیابی کنید.' : 'یک گزینه را انتخاب کنید.'}</p>
        <div class="edu-q-list" id="edu-q-list">${questions}</div>
        <div class="edu-form-actions">
            ${(ctx.phaseIdx || 0) > 0 ? `<button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-test-prev">مرحله قبل</button>` : ''}
            ${(ctx.phaseIdx || 0) < (test.phases?.length || 1) - 1
                ? `<button type="button" class="edu-btn edu-btn--primary edu-btn--sm" id="edu-test-next">مرحله بعد ←</button>`
                : `<button type="button" class="edu-btn edu-btn--accent" id="edu-submit-test">ارسال پاسخ‌ها و مشاهده نتیجه</button>`}
        </div>
    </div>`;
}

export function renderTestResult(ctx) {
    const r = ctx.results || {};
    const phases = r.phases || [];
    const req = ctx.request || {};

    const phaseCards = phases.map(p => {
        if (p.type === 'academic_placement') {
            return `<div class="edu-result-card edu-result-card--primary">
                <h4>تعیین سطح درسی</h4>
                <div class="edu-result-score">${p.score_pct ?? 0}%</div>
                <p><span class="edu-badge edu-badge--ok">${esc(p.level_label || '')}</span></p>
                <p class="edu-muted">${p.correct ?? 0} از ${p.total ?? 0} پاسخ صحیح</p>
            </div>`;
        }
        if (p.type === 'skill_talent') {
            return `<div class="edu-result-card edu-result-card--secondary">
                <h4>شاخص استعداد</h4>
                <div class="edu-result-score">${p.talent_index ?? 0}</div>
                <p><span class="edu-badge edu-badge--ok">${esc(p.talent_label || '')}</span></p>
            </div>`;
        }
        if (p.type === 'skill_level') {
            return `<div class="edu-result-card edu-result-card--accent">
                <h4>سطح مهارتی</h4>
                <div class="edu-result-score">${p.level_pct ?? 0}%</div>
                <p><span class="edu-badge">${esc(p.level_label || '')}</span></p>
            </div>`;
        }
        return '';
    }).join('');

    const plan = r.plan?.weeks?.slice(0, 2) || [];
    const planHtml = plan.length ? `<div class="edu-panel edu-panel--inner">
        <h3 class="edu-subtitle">برنامه پیشنهادی (EduLoop)</h3>
        ${plan.map(w => `<div class="edu-plan-week"><h4>هفته ${w.week} — ${esc(w.label||'')}</h4><ul>${(w.tasks||[]).map(t=>`<li>${esc(t)}</li>`).join('')}</ul></div>`).join('')}
    </div>` : '';

    return `<div class="edu-result-panel">
        <div class="edu-result-hero">
            <span class="edu-result-hero__icon">🎉</span>
            <h2>تعیین سطح انجام شد</h2>
            <p class="edu-muted">کد درخواست: <code>${esc(req.ref_code || ctx.ref_code || '')}</code></p>
        </div>
        <div class="edu-result-grid">${phaseCards}</div>
        ${planHtml}
        <div class="edu-form-actions">
            <button type="button" class="edu-btn edu-btn--accent" id="edu-goto-book">رزرو اولین جلسه ←</button>
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-goto-brain">مشاهده EduBrain</button>
            <button type="button" class="edu-btn edu-btn--ghost edu-btn--sm" id="edu-new-request">درخواست جدید</button>
        </div>
    </div>`;
}

export function collectTestAnswers(root) {
    const answers = {};
    root.querySelectorAll('.edu-q-card').forEach(card => {
        const qid = card.dataset.qid;
        const checked = card.querySelector(`input[name="q_${qid}"]:checked`);
        if (checked) answers[qid] = checked.value;
    });
    return answers;
}

export function parseRequestForm(form) {
    const fd = new FormData(form);
    const goals = [];
    form.querySelectorAll('input[name="goals"]:checked').forEach(el => goals.push(el.value));
    return {
        full_name: fd.get('full_name'),
        grade_level: fd.get('grade_level'),
        school_name: fd.get('school_name'),
        session_type: fd.get('session_type'),
        track: fd.get('track'),
        domain: fd.get('domain'),
        goals,
        delivery_mode: fd.get('delivery_mode'),
        venue_type: fd.get('venue_type'),
        weekly_hours: fd.get('weekly_hours'),
        notes: fd.get('notes'),
        consent_privacy: form.querySelector('[name="consent_privacy"]')?.checked,
    };
}

export const TRACK_DOMAINS = { ACADEMIC_TRACKS, SKILL_TRACKS, ACADEMIC_DOMAINS, SKILL_DOMAINS };
