/* ============================================================
   Student — Attendance, Theory, Announcements, Certificate
   Smaller modules grouped in one file.
   ============================================================ */

/* ============================================================
   ATTENDANCE
   ============================================================ */
function StudentAttendance({ ctx, rec }) {
  const sessions = window.ATTENDANCE_SCHEDULE;
  const profile = rec.profile || {};
  const attMap = rec.attendance || {};
  const sDate = (s) => {
    const d = window.sessionDate(profile.startDate, s.day);
    return d ? UI.fmtDate(d) : `Day ${s.day}`;
  };
  const present = sessions.filter(s => attMap[s.id]?.status === 'present');
  const absent  = sessions.filter(s => attMap[s.id]?.status === 'absent');
  const pending = sessions.filter(s => attMap[s.id]?.status === 'pending');

  const groups = ['ground','sim','flying'];
  const groupLbl = { ground: 'Ground classes', sim: 'Simulator', flying: 'Flying' };
  const groupHrs = (g) => sessions.filter(s => s.kind === g)
    .filter(s => attMap[s.id]?.status === 'present')
    .reduce((sum, s) => sum + s.hours, 0);

  return (
    <div className="module">
      <ModuleHeader
        crumbs={`MODULE 5 OF 8 · ATTENDANCE`}
        title={tr("Attendance record")}
        sub={tr("Your training day-by-day. Officers mark presence; this view is read-only.")}
        right={
          <div className="row" style={{gap:8}}>
            <div className="pill pill-good"><i className="dotty"/>{present.length} {tr('present')}</div>
            <div className="pill pill-bad"><i className="dotty"/>{absent.length} {tr('absent')}</div>
            <div className="pill pill-ghost"><i className="dotty"/>{pending.length} {tr('pending')}</div>
          </div>
        }
      />

      <div className="grid g-4">
        {groups.map(g => (
          <div key={g} className="kpi">
            <div className="lbl">{tr(groupLbl[g])} · {tr('hours logged')}</div>
            <div className="val">{groupHrs(g).toFixed(1)}<span className="unit">{tr('hrs')}</span></div>
            <div className="delta">{sessions.filter(s => s.kind === g && rec.attendance[s.id]?.status === 'present').length} {tr('of')} {sessions.filter(s => s.kind === g).length} {tr('sessions')}</div>
          </div>
        ))}
        <div className="kpi accent">
          <div className="lbl">{tr('Total course hours')}</div>
          <div className="val">{sessions.filter(s => rec.attendance[s.id]?.status === 'present').reduce((sum,s)=>sum+s.hours,0).toFixed(1)}<span className="unit">{tr('hrs')}</span></div>
          <div className="delta">{tr('Out of')} {sessions.reduce((sum,s)=>sum+s.hours,0).toFixed(1)} {tr('scheduled')}</div>
        </div>
      </div>

      {/* Heat strip — sessions grouped by kind */}
      <div className="card">
        <div className="card-hd">
          <div><h3>{tr('Session-by-session')}</h3><div className="sub">{tr("Hover for date and hours. Pending sessions haven't happened yet.")}</div></div>
        </div>
        <div className="card-body">
          <div className="att-grid">
            {groups.map(g => {
              const list = sessions.filter(s => s.kind === g);
              return (
                <div key={g} className="att-row">
                  <div className="lbl"><b>{tr(groupLbl[g])}</b> · {list.length}</div>
                  <div className="cells">
                    {list.map((s, i) => {
                      const st = rec.attendance[s.id]?.status || 'pending';
                      return (
                        <div key={s.id} className={cls('att-cell', st)} title={`${s.title} · ${sDate(s)} · ${s.hours}h · ${st}`}>
                          {i+1}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
          <div className="row" style={{gap:14,marginTop:14,fontSize:11,color:'var(--muted)'}}>
            <span className="row" style={{gap:5}}><span className="att-cell present" style={{width:12,height:12}}/> {tr('Present')}</span>
            <span className="row" style={{gap:5}}><span className="att-cell absent" style={{width:12,height:12}}/> {tr('Absent')}</span>
            <span className="row" style={{gap:5}}><span className="att-cell" style={{width:12,height:12}}/> {tr('Pending')}</span>
          </div>
        </div>
      </div>

      {/* Tabular log */}
      <div className="card" style={{padding:0}}>
        <div className="card-hd">
          <div><h3>{tr('Detailed log')}</h3><div className="sub">{tr('Every session, every status change.')}</div></div>
        </div>
        <table className="tbl">
          <thead><tr>
            <th>{tr('Date')}</th><th>{tr('Session')}</th><th>{tr('Kind')}</th><th className="right">{tr('Hours')}</th><th>{tr('Status')}</th><th>{tr('Marked by')}</th>
          </tr></thead>
          <tbody>
            {sessions.map(s => {
              const a = rec.attendance[s.id];
              return (
                <tr key={s.id}>
                  <td className="mono">{sDate(s)}</td>
                  <td>{tr(s.title)}</td>
                  <td><span className="tag">{tr(s.kind)}</span></td>
                  <td className="right mono">{s.hours}</td>
                  <td><StatusPill status={a?.status || 'pending'}/></td>
                  <td className="small muted">{a?.markedBy || '—'}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
window.StudentAttendance = StudentAttendance;

/* ============================================================
   THEORY
   ============================================================ */
function StudentTheory({ ctx, rec, embedded }) {
  const subjects = window.THEORY_SUBJECTS;
  const bank = window.THEORY_BANK || [];
  const PASS = window.Store.getSettings().theoryPassPct || window.THEORY_PASS_PCT || 70;
  const t = rec.theory;

  // Single gate: the instructor must flip theory.unlocked. The video
  // quizzes are recommended practice but no longer a prerequisite —
  // once an instructor unlocks the test the student can sit it.
  const prog = window.calcProgress(rec);
  const instructorUnlocked = !!t.unlocked;
  const locked = !instructorUnlocked;
  const hasResult = t.pass !== null;

  const [retake, setRetake] = useState(false);
  const [answers, setAnswers] = useState({});
  const showExam = !locked && (!hasResult || retake);

  const grouped = subjects
    .map(s => ({ ...s, qs: bank.filter(q => q.subject === s.id) }))
    .filter(g => g.qs.length);
  const totalQ = bank.length;
  const answered = Object.keys(answers).length;

  const submit = () => {
    if (answered < totalQ) {
      ctx.setToast(`Answer all ${totalQ} questions (${answered}/${totalQ})`);
      return;
    }
    const scores = {};
    subjects.forEach(s => { scores[s.id] = null; });
    let totalCorrect = 0;
    grouped.forEach(g => {
      let c = 0;
      g.qs.forEach(q => { if (answers[q.id] === q.answer) c++; });
      scores[g.id] = Math.round((c / g.qs.length) * 100);
      totalCorrect += c;
    });
    const overall = totalQ ? Math.round((totalCorrect / totalQ) * 100) : 0;
    const pass = overall >= PASS;
    window.Store.patchStudent(rec.id, (r) => {
      r.theory.examDate = new Date().toISOString().slice(0, 10);
      r.theory.scores = scores;
      r.theory.overallPct = overall;
      r.theory.pass = pass;
      r.theory.filed = true;
      return r;
    });
    setRetake(false); setAnswers({});
    window.Store.logAudit(pass ? 'Theory passed' : 'Theory failed',
      rec.profile?.fullName || 'Student', `${overall}%`);
    ctx.setToast(pass ? `Passed — ${overall}%` : `Not cleared — ${overall}% (need ${PASS}%)`);
  };

  const headerRight =
    locked ? <StatusPill status="pending"/> :
    t.pass === true ? <StatusPill status="verified"/> :
    t.pass === false ? <StatusPill status="rejected"/> :
    <StatusPill status="pending"/>;

  const Header = () => (
    <ModuleHeader
      crumbs={`DGCA THEORY TEST`}
      title={tr("DGCA theory test")}
      sub={tr("Final exam — Air Regs, Aerodynamics, Meteo, RT, RPAS, Navigation, Human Performance.")}
      right={headerRight}
    />
  );

  const lockedBody = (
    <div className="card">
      <div className="card-body" style={{textAlign:'center',padding:'40px 24px'}}>
        <div style={{fontSize:30,marginBottom:8}}>🔒</div>
        <h3 style={{margin:'0 0 6px'}}>{tr('DGCA theory test locked')}</h3>
        <p className="small muted" style={{margin:'0 auto',maxWidth:480,lineHeight:1.6}}>
          {tr("Your instructor will unlock the DGCA theory test once they've signed off.")}
          {prog && prog.learnTotal
            ? <> {tr('In the meantime, work through the Online Classes — you have passed')} <b>{prog.quizzesPassed} {tr('of')} {prog.learnTotal}</b> {tr('video quizzes.')}</>
            : null}
        </p>
      </div>
    </div>
  );

  // When embedded inside StudentLearn we drop the page header — the
  // parent module owns it. Standalone render still gets the header.
  if (embedded && locked) return lockedBody;

  return (
    <div className={embedded ? '' : 'module'}>
      {!embedded && <Header/>}
      {locked && lockedBody}

      {/* EXAM */}
      {showExam && (
        <div className="grid g-side">
          <div className="stack">
            {hasResult && retake && (
              <div className="banner warn"><div className="body">
                {tr('Retaking — your previous result will be replaced when you submit.')} ({t.overallPct}%)
              </div></div>
            )}
            {grouped.map(g => (
              <div key={g.id} className="card">
                <div className="card-hd"><div><h3>{tr(g.label)}</h3>
                  <div className="sub">{g.qs.length} {g.qs.length>1?tr('questions'):tr('question')}</div></div></div>
                <div className="card-body stack-sm" style={{gap:18}}>
                  {g.qs.map((q, qi) => (
                    <div key={q.id}>
                      <div className="small" style={{fontWeight:600,marginBottom:8}}>
                        {qi+1}. {q.q}
                      </div>
                      <div className="stack-sm" style={{gap:6}}>
                        {q.options.map((opt, oi) => (
                          <label key={oi} className="row" style={{
                            gap:8,alignItems:'flex-start',cursor:'pointer',
                            padding:'7px 10px',borderRadius:8,
                            border:'1px solid var(--line)',
                            background: answers[q.id]===oi ? 'var(--accent-soft)' : 'var(--surface)'}}>
                            <input type="radio" name={q.id} checked={answers[q.id]===oi}
                              onChange={()=>setAnswers(a=>({ ...a, [q.id]: oi }))}
                              style={{marginTop:2}}/>
                            <span className="small">{opt}</span>
                          </label>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            {grouped.length === 0 && (
              <div className="banner"><div className="body">{tr('No questions loaded yet. Ask the office to publish the theory question bank.')}</div></div>
            )}
          </div>
          <div className="stack">
            <div className="card">
              <div className="card-hd"><h3>{tr('Submit')}</h3></div>
              <div className="card-body">
                <div style={{textAlign:'center',padding:'4px 0 14px'}}>
                  <Donut value={totalQ ? Math.round((answered/totalQ)*100) : 0} size={110} stroke={9} sub="answered"/>
                </div>
                <div className="small muted" style={{textAlign:'center',marginBottom:12}}>
                  {answered}/{totalQ} {tr('answered')} · {tr('pass mark')} {PASS}%
                </div>
                <button className="btn btn-primary" style={{width:'100%'}}
                  disabled={!totalQ} onClick={submit}>{tr('Submit test')}</button>
                {hasResult && (
                  <button className="btn btn-sm" style={{width:'100%',marginTop:8}}
                    onClick={()=>{setRetake(false);setAnswers({});}}>{tr('Cancel retake')}</button>
                )}
              </div>
            </div>
            <div className="card">
              <div className="card-hd"><h3>{tr('Instructions')}</h3></div>
              <div className="card-body small muted" style={{lineHeight:1.6}}>
                <p style={{margin:'0 0 6px'}}>{tr('Single best answer per question. All questions must be answered.')}</p>
                <p style={{margin:0}}>{tr('You need')} {PASS}% {tr("overall to pass. You may retake if you don't clear.")}</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* RESULT */}
      {!locked && hasResult && !retake && (
        <div className="grid g-side">
          <div className="stack">
            <div className="card">
              <div className="card-hd">
                <div><h3>{tr('Result by subject')}</h3>
                  <div className="sub">{t.examDate ? `${tr('Taken')} ${UI.fmtDate(t.examDate)}` : ''}</div></div>
              </div>
              <div className="card-body">
                <div className="stack-sm">
                  {subjects.map(s => {
                    const sc = t.scores[s.id];
                    return (
                      <div key={s.id}>
                        <div className="row" style={{justifyContent:'space-between',marginBottom:6,gap:10}}>
                          <span className="small" style={{flex:1,minWidth:0,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{tr(s.label)}</span>
                          <span className="small mono" style={{flexShrink:0,
                            color: sc === null ? 'var(--muted)' : sc >= PASS ? 'var(--good)' : 'var(--bad)'}}>
                            {sc === null ? '—' : `${sc}%`}
                          </span>
                        </div>
                        <div className="bar"><i style={{
                          width: `${sc || 0}%`,
                          background: sc === null ? 'var(--line-strong)' : sc >= PASS ? 'var(--good)' : 'var(--bad)'}}/></div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
          <div className="stack">
            <div className="card">
              <div className="card-body" style={{textAlign:'center',padding:'28px 20px'}}>
                <div className="tiny upper muted" style={{fontWeight:600,marginBottom:8}}>{tr('Overall')}</div>
                {t.pass === true ? (
                  <>
                    <div style={{fontSize:42,fontWeight:700,color:'var(--good)',lineHeight:1,letterSpacing:'-0.02em'}}>{tr('PASS')}</div>
                    <div className="small muted" style={{marginTop:6}}>{t.overallPct}% {tr('overall')}</div>
                  </>
                ) : (
                  <>
                    <div style={{fontSize:42,fontWeight:700,color:'var(--bad)',lineHeight:1,letterSpacing:'-0.02em'}}>{tr('FAIL')}</div>
                    <div className="small muted" style={{marginTop:6}}>{t.overallPct}% · {tr('need')} {PASS}%</div>
                  </>
                )}
                <button className="btn btn-primary btn-sm" style={{marginTop:16}}
                  onClick={()=>{setAnswers({});setRetake(true);}}>
                  {tr('Retake test')}
                </button>
              </div>
            </div>
            <div className="card">
              <div className="card-hd"><h3>{tr('Passing criteria')}</h3></div>
              <div className="card-body small muted" style={{lineHeight:1.6}}>
                <p style={{margin:'0 0 6px'}}>{PASS}% {tr('or higher overall to pass.')}</p>
                <p style={{margin:0}}>{tr("You can retake the test at no extra cost if you don't clear.")}</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
window.StudentTheory = StudentTheory;

/* ============================================================
   ANNOUNCEMENTS
   ============================================================ */
function StudentAnnouncements({ ctx, rec }) {
  const list = Object.values((ctx.store && ctx.store.announcements) || {})
    .sort((a, b) => (b.date || '').localeCompare(a.date || ''));
  return (
    <div className="module">
      <ModuleHeader
        crumbs={`COMMUNICATIONS · ANNOUNCEMENTS`}
        title={tr("Announcements")}
        sub={tr("Notices, reminders and feedback from your instructors and the IDA office.")}
        right={<div className="pill pill-info"><i className="dotty"/>{list.length}</div>}
      />
      <div className="card" style={{padding:0}}>
        <div>
          {list.length === 0 && (
            <div className="card-body small muted">{tr('No announcements yet. Check back soon.')}</div>
          )}
          {list.map(a => (
            <div key={a.id} className={cls('ann', a.tag)} style={{padding:'18px 20px'}}>
              <div className="stripe"/>
              <div className="body">
                <div className="meta">
                  <div className="who">
                    <b style={{color:'var(--ink)'}}>{a.from}</b>
                    <span className="tag" style={{marginLeft:8}}>{a.tag}</span>
                  </div>
                  <div className="when">{UI.fmtDateTime(a.date)} · {UI.ago(a.date)}</div>
                </div>
                <h4 style={{fontSize:14}}>{a.title}</h4>
                <p style={{fontSize:13,maxWidth:'72ch'}}>{a.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.StudentAnnouncements = StudentAnnouncements;

/* ============================================================
   CERTIFICATE (read-only) — visible to the student once cleared
   ============================================================ */
function StudentCertificate({ ctx, rec }) {
  const prog = window.calcProgress(rec);
  const cleared = rec.issuance?.cleared;
  return (
    <div className="module">
      <ModuleHeader
        crumbs={`COMMUNICATIONS · CERTIFICATE`}
        title={tr("Final certificate")}
        sub={tr("Issued by IDA once your full pilot file is approved.")}
        right={<StatusPill status={cleared ? 'verified' : 'pending'}/>}
      />
      {!cleared && (
        <div className="banner warn">
          <div className="body"><b>{tr('Not yet issued.')}</b> {tr('Your overall progress is at')} {prog.overall}%. {tr('Once every module is verified, the front office releases your RPTO certificate here.')}</div>
        </div>
      )}
      <div className="card">
        <div className="card-body" style={{padding:0}}>
          <div style={{
            background:'linear-gradient(135deg, var(--bg-2), var(--surface))',
            padding:'40px 30px',textAlign:'center',
            border:'2px solid var(--accent-line)',borderRadius:'10px',
            margin:20,
            position:'relative',
            opacity: cleared ? 1 : 0.5,
          }}>
            <div className="tiny upper" style={{color:'var(--muted)',fontWeight:600,letterSpacing:'.18em'}}>Remote Pilot Training Organisation</div>
            <div style={{margin:'10px 0 4px',fontSize:18,letterSpacing:'.1em',color:'var(--accent)',fontWeight:600}}>INDIA DRONE ACADEMY</div>
            <div className="muted small">Certificate No. {rec.issuance?.refNumber || 'IDA/—/—/—'}</div>

            <div style={{margin:'30px 0 6px',fontSize:11,color:'var(--muted)',letterSpacing:'.05em'}}>This is to certify that</div>
            <div style={{fontSize:28,fontWeight:600,letterSpacing:'-0.01em'}}>{rec.profile?.fullName || '—'}</div>
            <div style={{margin:'14px auto',maxWidth:520,fontSize:13,color:'var(--ink-2)',lineHeight:1.6}}>
              has successfully completed the <b>{rec.profile?.course || '—'}</b> as per DGCA-recognised
              syllabus, including ground, simulator and flying training, the theoretical examination
              and the final skill test.
            </div>
            <div className="row" style={{justifyContent:'center',gap:40,marginTop:30}}>
              <div className="tiny" style={{color:'var(--muted)'}}>
                <div style={{borderTop:'1px solid var(--ink-2)',width:140,paddingTop:4}}>Chief Instructor</div>
              </div>
              <div className="tiny" style={{color:'var(--muted)'}}>
                <div style={{borderTop:'1px solid var(--ink-2)',width:140,paddingTop:4}}>Director, IDA</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.StudentCertificate = StudentCertificate;
