/* ============================================================
   Student — Learn (LMS)
   10 lecture videos (5 on Day 1, 5 on Day 2). Each video pairs
   with a 5-question quiz. Watching a video auto-marks attendance
   for that day's ground sessions. Once all 10 quizzes are passed
   AND the instructor unlocks it, the DGCA theory exam opens (the
   StudentTheory component is embedded below as the final stage).
   ============================================================ */

function StudentLearn({ ctx, rec }) {
  const language = (rec.learn && rec.learn.language) || null;
  const videos = (window.LEARN_VIDEOS_FOR || (() => window.LEARN_VIDEOS || []))(language) || [];
  const sched = window.ATTENDANCE_SCHEDULE || [];
  const PASS = window.LEARN_QUIZ_PASS_PCT || 60;
  const learn = (rec.learn && rec.learn.videos) || {};

  const pickLanguage = (lang) => {
    window.Store.patchStudent(rec.id, (r) => {
      r.learn = r.learn || { videos: {} };
      r.learn.language = lang;
      return r;
    });
    window.Store.logAudit('Online Classes language picked',
      rec.profile.fullName, lang === 'te' ? 'Telugu' : 'English');
  };

  const prog = window.calcProgress(rec) || {};
  const quizzesPassed = prog.quizzesPassed || 0;

  // Mark this video opened, and (first time only) mark its matching
  // ground session as 'present'. Each Learn video maps 1:1 to one
  // ground session via the session's `videoId` field in
  // ATTENDANCE_SCHEDULE — opening v3 marks only the "Module 3" session,
  // not every Day-1 session.
  const openVideo = (v) => {
    // Telugu pack may have null URLs while the real links are pending —
    // fall back to the English video so the student isn't blocked.
    const fallback = (window.LEARN_VIDEOS_EN || []).find(x => x.id === v.id);
    const url = v.youtube || (fallback && fallback.youtube);
    if (url) window.open(url, '_blank', 'noopener');
    const alreadyWatched = !!(learn[v.id] && learn[v.id].watched);
    const session = sched.find(s => s.videoId === v.id);
    window.Store.patchStudent(rec.id, (r) => {
      r.learn = r.learn || { videos: {} };
      r.learn.videos = r.learn.videos || {};
      const prev = r.learn.videos[v.id] || {};
      r.learn.videos[v.id] = {
        ...prev,
        watched: true,
        watchedAt: prev.watchedAt || new Date().toISOString(),
      };
      if (!alreadyWatched && session) {
        r.attendance = r.attendance || {};
        const cell = r.attendance[session.id] || { status: 'pending' };
        if (cell.status !== 'present') {
          r.attendance[session.id] = {
            ...cell,
            status: 'present',
            markedAt: new Date().toISOString(),
            markedBy: 'Self (Learn module)',
          };
        }
      }
      return r;
    });
    if (!alreadyWatched) {
      window.Store.logAudit('Learn video opened', v.title,
        session ? `Day ${v.day} · ${session.title}` : `Day ${v.day}`);
      ctx.setToast(session
        ? `${v.title} opened · attendance marked for ${session.title}`
        : `${v.title} opened`);
    }
  };

  const headerRight = (
    <div className="row" style={{gap:8}}>
      <div className="pill pill-good"><i className="dotty"/>{quizzesPassed}/{videos.length} {tr('quizzes passed')}</div>
      {prog.allQuizzesPassed
        ? <StatusPill status={rec.theory.unlocked ? 'verified' : 'pending'}/>
        : <StatusPill status="pending"/>}
    </div>
  );

  // First visit — show the language picker before the videos.
  if (!language) {
    return (
      <div className="module">
        <ModuleHeader
          crumbs="ONLINE CLASSES"
          title={tr("Online Classes")}
          sub={tr("Pick the language you want to learn in. Your progress is shared across both — you can switch later from the Online Classes page.")}
        />
        <div className="grid g-2" style={{maxWidth:640,margin:'0 auto',gap:16}}>
          {(window.LEARN_LANGUAGES || []).map(L => (
            <button key={L.id} className="card lang-card"
              onClick={()=>pickLanguage(L.id)}
              style={{textAlign:'left',cursor:'pointer',padding:'24px 22px',border:'1px solid var(--line-strong)',background:'var(--surface)'}}>
              <div className="tiny upper muted" style={{fontWeight:600,marginBottom:8}}>{L.label}</div>
              <div style={{fontSize:26,fontWeight:700,marginBottom:8}}>{L.native}</div>
              <div className="small muted" style={{lineHeight:1.5}}>
                {L.id === 'en'
                  ? 'Ten English lectures aligned to the DGCA syllabus, each followed by a 5-question quiz.'
                  : 'పది తెలుగు పాఠాలు, ప్రతి దాని తర్వాత 5-ప్రశ్నల క్విజ్. (Telugu videos coming soon — quizzes are ready.)'}
              </div>
              <div className="row" style={{gap:8,marginTop:14}}>
                <button className="btn btn-primary btn-sm">{tr('Choose')} {L.label} →</button>
              </div>
            </button>
          ))}
        </div>
      </div>
    );
  }

  const day1 = videos.filter(v => v.day === 1);
  const day2 = videos.filter(v => v.day === 2);
  const langLabel = (window.LEARN_LANGUAGES || []).find(L => L.id === language)?.label || 'English';
  const otherLang = language === 'te' ? 'en' : 'te';
  const otherLangLabel = otherLang === 'te' ? 'Telugu' : 'English';

  return (
    <div className="module">
      <ModuleHeader
        crumbs="ONLINE CLASSES"
        title={tr("Online Classes")}
        sub={`${tr("Ten lectures across Day 1 and Day 2. Watch each video, take the 5-question quiz, then sit the DGCA theory test at the end.")} · ${tr('Language')}: ${langLabel}`}
        right={headerRight}
      />

      <div className="row" style={{justifyContent:'flex-end',gap:8,marginBottom:10}}>
        <button className="btn btn-sm" onClick={()=>pickLanguage(otherLang)}>
          Switch to {otherLangLabel}
        </button>
      </div>

      <div className="grid g-side">
        <div className="stack">
          <DaySection day={1} videos={day1} learn={learn} pass={PASS} onOpen={openVideo} ctx={ctx} rec={rec}/>
          <DaySection day={2} videos={day2} learn={learn} pass={PASS} onOpen={openVideo} ctx={ctx} rec={rec}/>

          {/* Final DGCA exam — rendered inline; the embedded
              StudentTheory shows the lock card with the right
              prerequisite message OR the exam itself. */}
          <div className="card">
            <div className="card-hd">
              <div>
                <h3>{tr('DGCA theory test')}</h3>
                <div className="sub">{tr('Opens when your instructor unlocks it. The video quizzes are recommended practice.')}</div>
              </div>
            </div>
          </div>
          <StudentTheory ctx={ctx} rec={rec} embedded={true}/>
        </div>

        {/* Side — slides + progress + tips */}
        <div className="stack">
          <div className="card">
            <div className="card-hd"><h3>{tr('Course slides')}</h3><div className="sub">{tr('Shared Google Drive folder.')}</div></div>
            <div className="card-body">
              <a className="btn btn-primary btn-sm" href={window.LEARN_SLIDES_URL}
                target="_blank" rel="noopener noreferrer">
                {tr('Open slides folder')} ↗
              </a>
              <p className="tiny muted" style={{margin:'10px 0 0',lineHeight:1.5}}>
                {tr('Slides cover everything in the videos. Open in a side window while you watch.')}
              </p>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>{tr('Progress')}</h3></div>
            <div className="card-body" style={{textAlign:'center'}}>
              <Donut value={videos.length ? Math.round((quizzesPassed/videos.length)*100) : 0}
                size={120} stroke={10} sub="quizzes"/>
              <div className="small muted" style={{marginTop:8}}>
                {quizzesPassed} {tr('of')} {videos.length} {tr('quizzes passed')} · {tr('pass mark')} {PASS}%
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-hd"><h3>{tr('How it works')}</h3></div>
            <div className="card-body small muted" style={{lineHeight:1.6}}>
              <ol style={{margin:0,paddingLeft:18}}>
                <li>{tr('Tap a video — it opens in a new tab on YouTube.')}</li>
                <li>{tr('The first time you open a Day-1 video, Day-1 ground attendance is marked. Same for Day 2.')}</li>
                <li>{tr('Come back and answer the 5-question quiz under the video.')} {PASS}%+ {tr('to pass.')}</li>
                <li>{tr('The DGCA theory test opens whenever your instructor unlocks it — the quizzes are recommended practice, not a lock.')}</li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function DaySection({ day, videos, learn, pass, onOpen, ctx, rec }) {
  return (
    <div className="card">
      <div className="card-hd">
        <div>
          <h3>{tr('Day')} {day} · {day===1 ? tr('Foundations') : tr('Operations & Safety')}</h3>
          <div className="sub">{videos.length} {videos.length===1?tr('lecture'):tr('lectures')} · {videos.length*5} {tr('quiz questions')}</div>
        </div>
        <div className="pill pill-ghost">
          {videos.filter(v => learn[v.id] && learn[v.id].quizPassed).length}/{videos.length} {tr('passed')}
        </div>
      </div>
      <div className="card-body stack-sm" style={{gap:12,padding:'10px 14px 16px'}}>
        {videos.map((v, ix) => (
          <VideoRow key={v.id} ix={ix+1} v={v}
            state={learn[v.id] || {}} pass={pass}
            onOpen={()=>onOpen(v)} ctx={ctx} rec={rec}/>
        ))}
      </div>
    </div>
  );
}

function VideoRow({ ix, v, state, pass, onOpen, ctx, rec }) {
  const [open, setOpen] = useState(false);
  const watched = !!state.watched;
  const passed  = !!state.quizPassed;
  const score   = state.quizScore;

  return (
    <div style={{
      border:'1px solid var(--line)',
      borderRadius:8,
      background: passed ? 'var(--good-soft)' : 'var(--surface)',
    }}>
      <div className="row" style={{padding:'10px 12px',gap:10,alignItems:'center'}}>
        <div style={{
          width:30,height:30,borderRadius:8,display:'grid',placeItems:'center',
          background: passed ? 'var(--good)' : watched ? 'var(--accent-soft)' : 'var(--bg-2)',
          color: passed ? '#fff' : watched ? 'var(--accent)' : 'var(--ink-2)',
          fontWeight:600,fontSize:12,flexShrink:0,
        }}>
          {passed ? '✓' : String(ix).padStart(2,'0')}
        </div>
        <div style={{flex:1,minWidth:0}}>
          <div className="small" style={{fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{v.title}</div>
          <div className="tiny muted">
            {watched
              ? <>{tr('Opened')} {state.watchedAt ? UI.fmtDateTime(state.watchedAt) : ''}{passed ? ` · ${tr('quiz')} ${score}%` : score!=null ? ` · ${tr('quiz')} ${score}% (${tr('need')} ${pass}%)` : ` · ${tr('quiz not taken yet')}`}</>
              : <>{tr('Day')} {v.day} · {tr('5-question quiz after watching')}</>}
          </div>
        </div>
        <button className="btn btn-sm" onClick={onOpen}>
          {watched ? `${tr('Re-open video')} ↗` : `${tr('Watch video')} ↗`}
        </button>
        <button className={cls('btn btn-sm', passed && 'btn-good')}
          onClick={()=>setOpen(o=>!o)}>
          {passed ? tr('Review quiz') : open ? tr('Hide quiz') : tr('Take quiz')}
        </button>
      </div>
      {open && (
        <div style={{borderTop:'1px dashed var(--line-strong)',padding:'12px 14px 14px',background:'var(--bg)'}}>
          <QuizPanel v={v} state={state} pass={pass} ctx={ctx} rec={rec}/>
        </div>
      )}
    </div>
  );
}

function QuizPanel({ v, state, pass, ctx, rec }) {
  // Pre-fill with previous answers so a passed quiz can be reviewed.
  const [answers, setAnswers] = useState(state.quizAnswers || {});
  const [submitted, setSubmitted] = useState(!!state.quizDone);
  // Keep in sync if the underlying record changes (e.g. another tab).
  useEffect(() => {
    setAnswers(state.quizAnswers || {});
    setSubmitted(!!state.quizDone);
  }, [v.id, state.quizDone]);

  const allAnswered = v.quiz.every(q => answers[q.q] != null);
  const showResult = submitted;

  const submit = () => {
    if (!allAnswered) {
      ctx.setToast(`Answer all ${v.quiz.length} questions`);
      return;
    }
    const correct = v.quiz.filter(q => answers[q.q] === q.answer).length;
    const pct = Math.round((correct / v.quiz.length) * 100);
    const ok = pct >= pass;
    window.Store.patchStudent(rec.id, (r) => {
      r.learn = r.learn || { videos: {} };
      r.learn.videos = r.learn.videos || {};
      const prev = r.learn.videos[v.id] || {};
      r.learn.videos[v.id] = {
        ...prev,
        quizDone: true,
        quizScore: pct,
        quizPassed: ok,
        quizAnswers: answers,
        quizAt: new Date().toISOString(),
      };
      return r;
    });
    setSubmitted(true);
    window.Store.logAudit(ok ? 'Learn quiz passed' : 'Learn quiz failed', v.title, `${pct}%`);
    ctx.setToast(ok ? `Passed quiz — ${pct}%` : `Not cleared — ${pct}% (need ${pass}%)`);
  };

  const retake = () => {
    setSubmitted(false);
    setAnswers({});
  };

  return (
    <div className="stack-sm" style={{gap:14}}>
      {v.quiz.map((q, qi) => {
        const picked = answers[q.q];
        return (
          <div key={qi}>
            <div className="small" style={{fontWeight:600,marginBottom:6}}>{qi+1}. {q.q}</div>
            <div className="stack-sm" style={{gap:5}}>
              {q.options.map((opt, oi) => {
                const isPicked = picked === oi;
                const isCorrect = q.answer === oi;
                let bg = 'var(--surface)';
                let bd = 'var(--line)';
                if (showResult && isCorrect) { bg = 'var(--good-soft)'; bd = 'var(--good)'; }
                else if (showResult && isPicked && !isCorrect) { bg = 'var(--bad-soft)'; bd = 'var(--bad)'; }
                else if (isPicked) { bg = 'var(--accent-soft)'; bd = 'var(--accent)'; }
                return (
                  <label key={oi} className="row" style={{
                    gap:8,alignItems:'flex-start',cursor: showResult ? 'default' : 'pointer',
                    padding:'7px 10px',borderRadius:6,background:bg,border:`1px solid ${bd}`}}>
                    <input type="radio" name={`${v.id}-${qi}`}
                      checked={isPicked}
                      disabled={showResult}
                      onChange={()=>setAnswers(a=>({ ...a, [q.q]: oi }))}
                      style={{marginTop:2}}/>
                    <span className="small">{opt}</span>
                  </label>
                );
              })}
            </div>
          </div>
        );
      })}
      <div className="row" style={{gap:8,justifyContent:'flex-end',alignItems:'center'}}>
        {showResult ? (
          <>
            <span className="small" style={{
              fontWeight:600,
              color: state.quizPassed ? 'var(--good)' : 'var(--bad)',
            }}>
              {state.quizPassed ? `${tr('Passed')} — ${state.quizScore}%` : `${tr('Not cleared')} — ${state.quizScore}%`}
            </span>
            <button className="btn btn-sm" onClick={retake}>{tr('Retake')}</button>
          </>
        ) : (
          <button className="btn btn-primary btn-sm" disabled={!allAnswered} onClick={submit}>
            {tr('Submit')} ({Object.keys(answers).length}/{v.quiz.length})
          </button>
        )}
      </div>
    </div>
  );
}

window.StudentLearn = StudentLearn;
