/* ============================================================
   Student — Medical fitness (simplified)
   Two-step flow:
     1. Download the RMP template (PDF).
     2. Upload the RMP-endorsed certificate (scan).
   Officer / accountable manager verifies.
   ============================================================ */

function StudentMedical({ ctx, rec }) {
  const { setToast } = ctx;
  const m = rec.medical;

  const set = (patch) => window.Store.patchStudent(rec.id, (r) => {
    Object.assign(r.medical, patch); return r;
  });

  const onDownload = () => {
    if (m.status === 'not-started') {
      set({ status: 'downloaded', downloadedAt: new Date().toISOString() });
    }
    setToast('Template downloaded — get it endorsed by an RMP');
  };

  const onUpload = (files) => {
    set({
      status: 'endorsed',
      endorsedAt: new Date().toISOString(),
      files: [...(m.files || []), ...files],
    });
    setToast('Endorsed certificate uploaded · awaiting officer verification');
  };

  const removeUpload = () => {
    // Purge any uploaded blobs from Storage so we don't pay for an
    // orphaned file that nothing references after this clears.
    (m.files || []).forEach(f => f && f.path && window.Store.deleteFile(f.path));
    set({ status: 'downloaded', files: [] });
    setToast('Removed — you can upload a fresh scan');
  };

  return (
    <div className="module">
      <ModuleHeader
        crumbs="MEDICAL FITNESS"
        title={tr("Medical fitness certificate")}
        sub={tr("DGCA requires a medical fitness certificate, endorsed by a Registered Medical Practitioner.")}
        right={<StatusPill status={m.status}/>}
      />

      <div className="grid g-side">
        <div className="stack">

          {/* Step 1 — Download */}
          <div className="card">
            <div className="card-hd">
              <div>
                <h3>{tr('Step 1 — Download the template')}</h3>
                <div className="sub">{tr('Print on A4, take to a Registered Medical Practitioner (RMP) for endorsement.')}</div>
              </div>
              {m.downloadedAt && <span className="pill pill-good"><i className="dotty"/>{tr('Downloaded')}</span>}
            </div>
            <div className="card-body">
              <a className="btn btn-primary" href="assets/Medical-Fitness-Certificate-RPA.pdf"
                 target="_blank" rel="noopener" onClick={onDownload}>
                {window.NavIcons.download} {tr('Download template (PDF)')}
              </a>
              {m.downloadedAt && (
                <div className="tiny muted" style={{marginTop:8}}>
                  {tr('Downloaded')} {UI.ago(m.downloadedAt)}.
                </div>
              )}
            </div>
          </div>

          {/* Step 2 — Upload endorsed certificate */}
          <div className="card">
            <div className="card-hd">
              <div>
                <h3>{tr('Step 2 — Upload the endorsed certificate')}</h3>
                <div className="sub">{tr('Clear scan of the RMP-signed and stamped form.')}</div>
              </div>
              {m.status === 'verified' && <StatusPill status="verified"/>}
              {m.status === 'endorsed' && <StatusPill status="pending"/>}
            </div>
            <div className="card-body">
              {m.status === 'verified' && (
                <div className="banner good" style={{marginBottom:12}}>
                  <div className="body"><b>{tr('Verified.')}</b> {tr('by')} {m.verifiedBy} {tr('on')} {UI.fmtDate(m.verifiedAt)}. {tr('This document is locked and will be included in your final RPA pilot file.')}</div>
                </div>
              )}
              {m.status === 'endorsed' && (
                <div className="banner warn" style={{marginBottom:12}}>
                  <div className="body"><b>{tr('Uploaded')} {UI.ago(m.endorsedAt)}.</b> {tr('Your instructor will verify shortly.')}</div>
                </div>
              )}
              {(m.files || []).length > 0 && (
                <div className="row-wrap" style={{marginBottom:12}}>
                  {(m.files || []).map((f,i) => <FileChip key={i} file={f}/>)}
                </div>
              )}
              {m.status !== 'verified' && (
                <FileDrop onFiles={onUpload} studentId={rec.id} docId="medical"
                  hint={tr('Scan of the endorsed certificate · PDF, JPG or PNG · under 2 MB')}/>
              )}
              {m.status === 'endorsed' && (
                <div className="row" style={{gap:8,marginTop:10}}>
                  <button className="btn btn-sm" onClick={removeUpload}>{tr('Replace upload')}</button>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Side — short timeline + RMP tip */}
        <div className="stack">
          <div className="card">
            <div className="card-hd"><h3>{tr('Your timeline')}</h3></div>
            <div className="card-body">
              <Timeline items={[
                { label:tr('Downloaded template'), ts: m.downloadedAt, done: !!m.downloadedAt },
                { label:tr('Endorsed & uploaded'), ts: m.endorsedAt,   done: !!m.endorsedAt },
                { label:tr('Verified by office'),  ts: m.verifiedAt,   done: !!m.verifiedAt },
              ]}/>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>{tr('Tips')}</h3></div>
            <div className="card-body small muted" style={{lineHeight:1.6}}>
              <p style={{margin:'0 0 8px'}}>{tr('Any Registered Medical Practitioner with a valid MCI registration number can endorse the form.')}</p>
              <p style={{margin:0}}>{tr("Check the scan shows the doctor's signature, stamp and registration number clearly.")}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Timeline({ items }) {
  return (
    <div style={{position:'relative',paddingLeft:18}}>
      <div style={{position:'absolute',left:5,top:6,bottom:6,width:2,background:'var(--line)'}}/>
      {items.map((i,n) => (
        <div key={n} style={{position:'relative',padding:'4px 0 10px'}}>
          <div style={{
            position:'absolute',left:-15,top:6,width:10,height:10,borderRadius:50,
            background: i.done ? 'var(--good)' : 'var(--surface)',
            border: i.done ? '0' : '2px solid var(--line-strong)',
          }}/>
          <div className="small" style={{color: i.done ? 'var(--ink)' : 'var(--muted)', fontWeight: i.done ? 500 : 400}}>{i.label}</div>
          <div className="tiny muted">{i.ts ? UI.fmtDateTime(i.ts) : tr('Pending')}</div>
        </div>
      ))}
    </div>
  );
}
window.Timeline = Timeline;

window.StudentMedical = StudentMedical;
