/* ============================================================
   Student — Progress & Skill test reports (read-only + sign)
   Three reports filled by examiners. Student can review and sign.
   ============================================================ */

function StudentTests({ ctx, rec }) {
  const { setToast } = ctx;
  const [tab, setTab] = useState('simulator');
  // Legacy records may be missing `tests` entirely or any of its three keys.
  const tests = rec.tests || {};
  const t = tests[tab] || window.makeEmptyTest?.(tab) || { items:{}, finalised:false };

  const test = window.PROGRESS_ITEMS;
  const items = tab === 'skill' ? window.SKILL_ITEMS : null;

  return (
    <div className="module">
      <ModuleHeader
        crumbs={`MODULE 4 OF 8 · PROGRESS & SKILL TESTS`}
        title={tr("Progress & Skill test reports")}
        sub={tr("Filled by your examiner during training. You review and sign once the report is finalised.")}
        right={
          <div className="row" style={{gap:8}}>
            <TestStateChip t={tests.simulator} label="Simulator"/>
            <TestStateChip t={tests.rpa} label="RPA"/>
            <TestStateChip t={tests.skill} label="Skill test"/>
          </div>
        }
      />

      <div className="tabs">
        {[
          { id:'simulator', lbl:'Simulator progress', t: tests.simulator },
          { id:'rpa',       lbl:'RPA progress',       t: tests.rpa },
          { id:'skill',     lbl:'Final skill test',   t: tests.skill },
        ].map(o => (
          <button key={o.id} className={cls('tab', tab===o.id && 'active')} onClick={()=>setTab(o.id)}>
            {tr(o.lbl)}<span className="count">{o.t.finalised ? '✓' : '·'}</span>
          </button>
        ))}
      </div>

      <div className="grid g-side">
        <div className="stack">
          {!t.finalised && (
            <div className="banner warn">
              <div className="body"><b>{tr('Not yet finalised.')}</b> {tr("Your examiner is still filling this report. You'll be able to view and sign once they finalise it.")}</div>
            </div>
          )}
          {t.finalised && (
            <div className="banner good">
              <div className="body"><b>{tr('Report finalised.')}</b> {tr('Filed to your RPA pilot file on')} {t.finalisedAt ? UI.fmtDateTime(t.finalisedAt) : '—'}.</div>
            </div>
          )}

          {/* Header card with examiner + meta */}
          <div className="card">
            <div className="card-hd">
              <div>
                <h3>{tab === 'simulator' ? tr('Simulator Progress Test') :
                      tab === 'rpa' ? tr('RPA Progress Test') :
                      tr('Final Skill Test')}</h3>
                <div className="sub">{
                  tab === 'simulator' ? tr('Conducted on the IDA flight simulator') :
                  tab === 'rpa' ? tr('Hand-flown progress assessment') :
                  tr('DGCA-recognised final skill evaluation')
                }</div>
              </div>
              <StatusPill status={t.finalised ? (t.traineeSig ? 'verified' : 'submitted') : 'draft'}/>
            </div>
            <div className="card-body">
              <div className="grid g-4" style={{gap:14}}>
                <Meta label="Examiner" v={t.examinerName || '—'}/>
                <Meta label="Examiner ID" v={t.examinerId || '—'} mono/>
                <Meta label="Date" v={t.date ? UI.fmtDate(t.date) : '—'} mono/>
                {tab === 'skill' && <Meta label="Type" v={t.rpaType ? t.rpaType.toUpperCase() : '—'}/>}
                {tab !== 'skill' && <Meta label="Items rated" v={Object.values(t.items).filter(i=>i.status).length + '/' + Object.keys(t.items).length}/>}
                {/* Meta translates its label via tr() internally. */}
              </div>
            </div>
          </div>

          {/* Items table */}
          {tab !== 'skill' && (
            <ProgressItemsTable items={test} state={t.items}/>
          )}
          {tab === 'skill' && (
            <SkillItemsTable items={items} state={t.items}/>
          )}

          {/* Examiner comments */}
          <div className="card">
            <div className="card-hd"><h3>{tr('Examiner remarks')}</h3></div>
            <div className="card-body">
              {t.comments ? (
                <p style={{margin:0,fontSize:13,lineHeight:1.55,color:'var(--ink-2)'}}>{t.comments}</p>
              ) : (
                <p className="muted small" style={{margin:0,fontStyle:'italic'}}>{tr('No remarks recorded yet.')}</p>
              )}
            </div>
          </div>

          {/* Examiner signature (read-only; student no longer signs) */}
          <div className="card">
            <div className="card-hd"><h3>{tr('Examiner signature')}</h3></div>
            <div className="card-body">
              <div className="tiny upper muted" style={{marginBottom:8,fontWeight:600}}>{t.examinerName || tr('Pending')}</div>
              <div className="sig-pad signed" style={{height:80}}>
                {t.examinerSig ?
                  <div style={{padding:'8px 12px',fontSize:11,color:'var(--muted)',fontFamily:'var(--font-mono)'}}>✓ {tr('Signed')}</div> :
                  <div className="ph">{tr('Awaiting examiner')}</div>
                }
              </div>
            </div>
          </div>
        </div>

        {/* Side — summary */}
        <div className="stack">
          <div className="card">
            <div className="card-hd"><h3>{tr('Report summary')}</h3></div>
            <div className="card-body">
              <TestSummary t={t} tab={tab}/>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>{tr('About this report')}</h3></div>
            <div className="card-body small muted" style={{lineHeight:1.55}}>
              {tab === 'simulator' && <p style={{margin:0}}>{tr('Simulator progress is the first formal assessment. Your examiner watches you complete pre-flight, manoeuvres and the emergency procedure on the simulator before clearing you for hand-flown training.')}</p>}
              {tab === 'rpa' && <p style={{margin:0}}>{tr('RPA progress is the in-the-loop equivalent — same syllabus, but flying a real drone. You must be cleared here before the final skill test.')}</p>}
              {tab === 'skill' && <p style={{margin:0}}>{tr('The skill test is the gating examination for your remote pilot certificate. Conducted by an authorised examiner; result is "Pass" or "Fail".')}</p>}
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>{tr('Source')}</h3></div>
            <div className="card-body">
              <a className="btn btn-sm" href="assets/DGCA-Progress-Skill-Test.pdf" target="_blank" rel="noopener">
                {window.NavIcons.ext} {tr('DGCA template (PDF)')}
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- tiny chip showing test state ---------- */
function TestStateChip({ t, label }) {
  const status = t.finalised ? (t.traineeSig ? 'verified' : 'submitted') : 'draft';
  return (
    <div className="row" style={{gap:5}}>
      <span className="tiny muted" style={{fontWeight:600}}>{tr(label)}:</span>
      <StatusPill status={status}/>
    </div>
  );
}

function Meta({ label, v, mono }) {
  return (
    <div>
      <div className="tiny upper muted" style={{fontWeight:600,marginBottom:3}}>{tr(label)}</div>
      <div className={cls('small', mono && 'mono')} style={{color:'var(--ink)'}}>{v}</div>
    </div>
  );
}

/* ---------- items tables (read-only) ---------- */
function ProgressItemsTable({ items, state }) {
  return (
    <div className="card" style={{padding:0}}>
      <table className="score-tbl">
        <thead><tr>
          <th style={{width:'60%'}}>{tr('Item')}</th>
          <th>{tr('Result')}</th>
          <th>{tr('Examiner remark')}</th>
        </tr></thead>
        <tbody>
          <tr className="group-h"><td colSpan={3}>{tr('Pre-flight')}</td></tr>
          {items.preflight.map(it => <Row key={it.id} item={it} s={state[it.id]}/>)}
          <tr className="group-h"><td colSpan={3}>{tr('Performance manoeuvres')}</td></tr>
          {items.performance.map(it => <Row key={it.id} item={it} s={state[it.id]}/>)}
          <tr className="group-h"><td colSpan={3}>{tr('Overall')}</td></tr>
          {items.summary.map(it => <Row key={it.id} item={it} s={state[it.id]}/>)}
        </tbody>
      </table>
    </div>
  );
}
function SkillItemsTable({ items, state }) {
  return (
    <div className="card" style={{padding:0}}>
      <table className="score-tbl">
        <thead><tr>
          <th style={{width:'60%'}}>{tr('Item')}</th>
          <th>{tr('Result')}</th>
          <th>{tr('Examiner remark')}</th>
        </tr></thead>
        <tbody>{items.map(it => <Row key={it.id} item={it} s={state[it.id]}/>)}</tbody>
      </table>
    </div>
  );
}
function Row({ item, s }) {
  return (
    <tr>
      <td>{tr(item.label)}</td>
      <td><ResultBadge v={s?.status}/></td>
      <td className="small muted" style={{maxWidth:240}}>{s?.remark || '—'}</td>
    </tr>
  );
}
function ResultBadge({ v }) {
  if (v === 'sat')   return <span className="pill pill-good">{tr('Sat.')}</span>;
  if (v === 'unsat') return <span className="pill pill-bad">{tr('Unsat.')}</span>;
  if (v === 'na')    return <span className="pill pill-ghost">{tr('N/A')}</span>;
  return <span className="pill pill-ghost">{tr('Pending')}</span>;
}
window.ResultBadge = ResultBadge;

function TestSummary({ t, tab }) {
  const counts = Object.values(t.items).reduce((acc, x) => {
    acc[x.status || 'pending'] = (acc[x.status || 'pending'] || 0) + 1;
    return acc;
  }, {});
  const total = Object.keys(t.items).length;
  return (
    <div className="stack-sm" style={{gap:14}}>
      {tab !== 'skill' ? (
        <>
          <SummaryRow label="Satisfactory" count={counts.sat || 0} total={total} kind="good"/>
          <SummaryRow label="Unsatisfactory" count={counts.unsat || 0} total={total} kind="bad"/>
          <SummaryRow label="Not applicable" count={counts.na || 0} total={total} kind="ghost"/>
          <SummaryRow label="Pending" count={counts.pending || 0} total={total} kind="ghost"/>
        </>
      ) : (
        <>
          <div style={{display:'grid',placeItems:'center',padding:'8px 0'}}>
            <div className="tiny upper muted" style={{fontWeight:600,marginBottom:8}}>{tr('Result')}</div>
            {t.result === 'pass' && <div style={{fontSize:34,fontWeight:700,color:'var(--good)'}}>PASS</div>}
            {t.result === 'fail' && <div style={{fontSize:34,fontWeight:700,color:'var(--bad)'}}>FAIL</div>}
            {!t.result && <div style={{fontSize:18,color:'var(--muted)'}}>—</div>}
          </div>
          <div className="divider"/>
          <SummaryRow label="Satisfactory" count={counts.sat || 0} total={total} kind="good"/>
          <SummaryRow label="Unsatisfactory" count={counts.unsat || 0} total={total} kind="bad"/>
        </>
      )}
    </div>
  );
}
function SummaryRow({ label, count, total, kind }) {
  const color = kind === 'good' ? 'var(--good)' : kind === 'bad' ? 'var(--bad)' : 'var(--muted)';
  return (
    <div>
      <div className="row" style={{justifyContent:'space-between',marginBottom:4}}>
        <span className="small">{tr(label)}</span>
        <span className="small mono" style={{color}}>{count}/{total}</span>
      </div>
      <div className="bar"><i style={{width: `${(count/total)*100}%`, background: color}}/></div>
    </div>
  );
}
window.TestSummary = TestSummary;

window.StudentTests = StudentTests;
