/* ============================================================
   Student — Home
   The first thing a student lands on. Headline: overall progress
   + the single next action. Dense module grid below it.
   ============================================================ */

function StudentHome({ ctx, rec }) {
  const prog = window.calcProgress(rec);
  const { setRoute } = ctx;
  // Legacy records may be missing entire subtrees — default each before reading.
  const profile  = rec.profile  || {};
  const medical  = rec.medical  || {};
  const theory   = rec.theory   || {};
  const social   = rec.social   || {};
  const attMap   = rec.attendance || {};
  const startDate = profile.startDate;
  const endDate = window.courseEndDate(startDate, profile.course);
  const upcoming = window.ATTENDANCE_SCHEDULE.filter(s => attMap[s.id]?.status === 'pending').slice(0, 3);
  const announcements = Object.values((ctx.store && ctx.store.announcements) || {})
    .sort((a, b) => (b.date || '').localeCompare(a.date || '')).slice(0, 3);
  const firstName = (profile.fullName || ctx.session?.userName || tr('Student')).split(' ')[0];

  // Module summary cards
  const modules = [
    { id:'registration', label:'Registration',  pct: prog.registrationPct,
      meta: prog.registrationDone ? 'Verified by officer' : 'In progress' },
    { id:'documents',    label:'Documents',     pct: prog.documentsPct,
      meta: `${prog.docVerified}/${prog.docTotal} verified · ${prog.docDone}/${prog.docTotal} uploaded` },
    { id:'medical',      label:'Medical',       pct: prog.medicalPct,
      meta: medical.status === 'verified' ? 'Verified' :
            medical.status === 'endorsed' ? 'Awaiting verification' :
            medical.status === 'downloaded' ? 'Template downloaded' : 'Not started' },
    { id:'tests',        label:'Progress & skill', pct: prog.testsPct,
      meta: `${prog.testFinalised}/3 reports filed` },
    { id:'attendance',   label:'Attendance',    pct: prog.attendancePct,
      meta: `${prog.attPresent} present · ${prog.attAbsent} absent · ${prog.attTotal - prog.attPresent - prog.attAbsent} pending` },
    { id:'online-classes', label:'Online Classes', pct: prog.theoryPct,
      meta: theory.pass === true ? `DGCA pass · ${theory.overallPct}%` :
            theory.pass === false ? 'DGCA fail — retake' :
            `${prog.quizzesPassed||0}/${prog.learnTotal||10} quizzes passed` },
    { id:'social',       label:'Social media',  pct: prog.socialPct,
      meta: `${prog.reqDone}/${prog.reqTotal} follows · ${social.status || 'not started'}` },
  ];

  return (
    <div className="module">
      <ModuleHeader
        crumbs={`HOME · BATCH ${profile.batch || '—'}`}
        title={`${tr('Welcome back')}, ${firstName}.`}
        sub={(startDate ? `${tr('Started')} ${UI.fmtDate(startDate)}` : tr('Start date not set'))
          + (endDate ? ` · ${tr('completes')} ${UI.fmtDate(endDate)}` : '')
          + (profile.course ? ` · ${profile.course}` : '')}
      />

      {/* Hero card — overall progress + next action */}
      <div className="grid g-hero">
        <div className="card">
          <div className="card-body pad-lg">
            <div className="home-hero" style={{display:'grid'}}>
              <div className="home-hero-donut"><Donut value={prog.overall} size={140} stroke={12} sub="overall"/></div>
              <div>
                <div className="tag" style={{marginBottom:8}}>{tr('YOUR NEXT ACTION')}</div>
                <h2 style={{margin:0, fontSize:22, fontWeight:600, letterSpacing:'-0.01em', lineHeight:1.2}}>
                  {tr(prog.next.label)}
                </h2>
                <p style={{margin:'8px 0 14px', color:'var(--muted)', fontSize:13, maxWidth:420}}>
                  {tr(nextActionHint(prog.next.module))}
                </p>
                <div className="row" style={{gap:8, flexWrap:'wrap'}}>
                  <button className="btn btn-primary" style={{whiteSpace:'nowrap'}} onClick={()=>setRoute(prog.next.module)}>
                    {tr('Open this module')} →
                  </button>
                  <button className="btn" style={{whiteSpace:'nowrap'}} onClick={()=>setRoute('documents')}>
                    {tr('Document checklist')}
                  </button>
                </div>
              </div>
            </div>

            {/* Mixed weight bar */}
            <div style={{marginTop:22, paddingTop:16, borderTop:'1px solid var(--line)'}}>
              <div className="row" style={{justifyContent:'space-between', marginBottom:8, gap:14}}>
                <div className="tiny upper muted" style={{fontWeight:600,whiteSpace:'nowrap'}}>{tr('Module weight breakdown')}</div>
                <div className="tiny muted" style={{whiteSpace:'nowrap'}}>{tr('Hover a segment for details')}</div>
              </div>
              <WeightedBar prog={prog}/>
              <WeightLegend prog={prog} onSelect={setRoute}/>
            </div>
          </div>
        </div>

        {/* KPI strip */}
        <div className="stack">
          <Kpi label="Days to completion" val={endDate ? daysTo(endDate) : '—'} unit={endDate ? 'd' : ''}
               sub={endDate ? `${tr('Completes')} ${UI.fmtDate(endDate)}` : tr('Set start date & course')} accent/>
          <Kpi label="Flying hours logged" val="5.0" unit="hrs"
               sub="6 ground · 4 sim · 3 flights"
               viz={<MiniBars values={[4,4,3,3,3,2,2,2,1.5,1.5,2,2]}
                              fill={[true,true,true,true,false,true,true,true,true,true,false,false]}/>}/>
          <Kpi label="Documents" val={`${prog.docDone}/${prog.docTotal}`}
               sub={`${prog.docVerified} ${tr('verified')} · ${prog.docTotal - prog.docDone} ${tr('pending')}`}/>
        </div>
      </div>

      {/* Module grid */}
      <div>
        <div className="section-hd" style={{marginBottom:10, gap:16}}>
          <div style={{minWidth:0}}>
            <h2>{tr('Modules')}</h2>
            <div className="sub">{tr('Tap a card to open the module. Officers sign off; you fill in your part.')}</div>
          </div>
          <div className="row" style={{gap:6,flexShrink:0}}>
            <div className="pill pill-good" style={{whiteSpace:'nowrap'}}><i className="dotty"/>{Math.round(prog.overall)}% {tr('complete')}</div>
          </div>
        </div>
        <div className="grid g-4">
          {modules.map(m => (
            <button key={m.id} className="card" style={{textAlign:'left',cursor:'pointer',border:'1px solid var(--line)'}} onClick={()=>setRoute(m.id)}>
              <div className="card-body pad-sm">
                <div className="row" style={{justifyContent:'space-between', marginBottom:8, gap:8}}>
                  <div className="tiny upper muted" style={{fontWeight:600,flex:1,minWidth:0,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{tr(m.label)}</div>
                  <span className="mono small" style={{flexShrink:0}}>{m.pct}%</span>
                </div>
                <div className={cls('bar', m.pct === 100 && 'bar-good')}>
                  <i style={{width:`${m.pct}%`}}/>
                </div>
                <div className="small muted" style={{marginTop:10}}>{tr(m.meta)}</div>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Bottom row — upcoming + announcements */}
      <div className="grid g-2">
        <div className="card">
          <div className="card-hd">
            <div>
              <h3>{tr('Upcoming classes')}</h3>
              <div className="sub">{tr('Next sessions you need to attend')}</div>
            </div>
            <button className="btn btn-sm" onClick={()=>setRoute('attendance')}>{tr('Full schedule')} →</button>
          </div>
          <div className="list">
            {upcoming.length === 0 && <div className="card-body muted small">{tr('No pending sessions. Skill test is next.')}</div>}
            {upcoming.map(s => (
              <div key={s.id} className="list-row" style={{cursor:'default'}}>
                <div className="ix" style={{background:'var(--accent-soft)',color:'var(--accent-soft-ink)'}}>
                  {s.kind === 'ground' ? 'G' : s.kind === 'sim' ? 'S' : 'F'}
                </div>
                <div className="nm">
                  <div className="ttl">{tr(s.title)}</div>
                  <div className="desc">{s.kind === 'ground' ? tr('Ground class') : s.kind === 'sim' ? tr('Simulator session') : tr('Flying')} · {s.hours}h</div>
                </div>
                <div className="meta mono">{(()=>{const d=window.sessionDate(startDate,s.day);return d?UI.fmtDate(d):`${tr('Day')} ${s.day}`;})()}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-hd">
            <div>
              <h3>{tr('Recent notices')}</h3>
              <div className="sub">{tr('From your instructors and the office')}</div>
            </div>
            <button className="btn btn-sm" onClick={()=>setRoute('announcements')}>{tr('View all')} →</button>
          </div>
          <div>
            {announcements.map(a => (
              <div key={a.id} className={cls('ann', a.tag)}>
                <div className="stripe"/>
                <div className="body">
                  <div className="meta">
                    <div className="who">{a.from}</div>
                    <div className="when">{UI.ago(a.date)}</div>
                  </div>
                  <h4>{a.title}</h4>
                  <p style={{display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden'}}>{a.body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Local helpers ---------- */
function nextActionHint(mod) {
  return {
    registration: 'Fill in the digital registration form — it auto-saves as you type.',
    documents:    'Upload pending documents from the master checklist.',
    medical:      'Download the template, get it endorsed by an RMP, then upload it back here.',
    tests:        'Your examiner will fill the reports — you only need to sign once they are finalised.',
    attendance:   'Mark yourself present for sessions you attended (officer will verify).',
    theory:           'Open Online Classes, watch the 10 lectures and clear each quiz before the DGCA theory test.',
    learn:            'Open Online Classes, watch the 10 lectures and clear each quiz before the DGCA theory test.',
    'online-classes': 'Open Online Classes, watch the 10 lectures and clear each quiz before the DGCA theory test.',
    social:       'Follow the IDA brands on Instagram, YouTube and Facebook and submit a short review.',
    home:         'All set — wait for the office to release your certificate.',
  }[mod] || 'Open the module to continue.';
}
function daysTo(iso) {
  if (!iso) return '—';
  const d = Math.max(0, Math.ceil((new Date(iso) - new Date()) / (1000*60*60*24)));
  return d;
}

function Kpi({ label, val, unit, sub, viz, accent }) {
  return (
    <div className={cls('kpi', accent && 'accent')}>
      <div className="lbl">{tr(label)}</div>
      <div className="row" style={{justifyContent:'space-between',alignItems:'flex-end',gap:10}}>
        <div className="val">{val}{unit && <span className="unit">{unit}</span>}</div>
        {viz}
      </div>
      {sub && <div className="delta">{sub}</div>}
    </div>
  );
}

function MiniBars({ values, fill = [] }) {
  const max = Math.max(...values, 1);
  return (
    <div className="mini-bars">
      {values.map((v,i) => (
        <i key={i} style={{height: `${Math.max(10,(v/max)*100)}%`}}
           className={fill[i] === false ? 'dim' : ''}/>
      ))}
    </div>
  );
}

/* ---------- Weighted module bar (segmented) ---------- */
function WeightedBar({ prog }) {
  const W = { registration:12, documents:18, medical:12, tests:24, attendance:14, theory:10, social:10 };
  const segs = [
    { id:'registration', w:W.registration, pct:prog.registrationPct, label:'Registration' },
    { id:'documents',    w:W.documents,    pct:prog.documentsPct,    label:'Documents' },
    { id:'medical',      w:W.medical,      pct:prog.medicalPct,      label:'Medical' },
    { id:'tests',        w:W.tests,        pct:prog.testsPct,        label:'Tests' },
    { id:'attendance',   w:W.attendance,   pct:prog.attendancePct,   label:'Attendance' },
    { id:'online-classes', w:W.theory,     pct:prog.theoryPct,       label:'Online Classes' },
    { id:'social',       w:W.social,       pct:prog.socialPct,       label:'Social' },
  ];
  return (
    <div style={{display:'flex',gap:2,height:14,borderRadius:6,overflow:'hidden'}}>
      {segs.map(s => (
        <div key={s.id} title={`${s.label} — ${s.pct}% (weight ${s.w}%)`}
          style={{flex:s.w, background:'var(--bg-2)', position:'relative', overflow:'hidden'}}>
          <div style={{
            position:'absolute',left:0,top:0,bottom:0,
            width:`${s.pct}%`,
            background: s.pct === 100 ? 'var(--good)' : 'var(--accent)',
          }}/>
        </div>
      ))}
    </div>
  );
}

function WeightLegend({ prog, onSelect }) {
  const items = [
    { id:'registration', label:'Reg.', pct: prog.registrationPct, w:12 },
    { id:'documents',    label:'Docs', pct: prog.documentsPct,    w:18 },
    { id:'medical',      label:'Med.', pct: prog.medicalPct,      w:12 },
    { id:'tests',        label:'Tests',pct: prog.testsPct,        w:24 },
    { id:'attendance',   label:'Att.', pct: prog.attendancePct,   w:14 },
    { id:'online-classes', label:'Online', pct: prog.theoryPct,    w:10 },
    { id:'social',       label:'Social',pct: prog.socialPct,      w:10 },
  ];
  return (
    <div className="row-wrap" style={{marginTop:10, gap:14}}>
      {items.map(i => (
        <button key={i.id} className="row" style={{
          background:'transparent',border:0,cursor:'pointer',padding:0,gap:6,
        }} onClick={()=>onSelect(i.id)}>
          <span style={{width:8,height:8,borderRadius:2,
            background: i.pct === 100 ? 'var(--good)' : i.pct > 0 ? 'var(--accent)' : 'var(--line-strong)'}}/>
          <span className="tiny" style={{color:'var(--ink-2)'}}>{tr(i.label)}</span>
          <span className="tiny mono muted">{i.pct}%</span>
        </button>
      ))}
    </div>
  );
}

window.StudentHome = StudentHome;
