// irikos — Trainer page. Implements the Claude Design "Trainer.html" handoff:
// a hub (Practice sets · Focused drills · Review · Live) and a shared setup
// picker (choose task types · run length · go). Built on the app's real classes
// (.card / .cat-card / .cat-list / .mistakes-card / .segmented / .switch /
// .cta-primary / .qcard …) plus the .t-* connective tissue in trainer.css.
//
// NOTE: the Irregular-Verbs question cards (Complete the form / Spelling / Open
// the brackets) + the 60-verb dataset + per-stream mastery land in a follow-up.
// Hub facts are pulled live from stats; the family/stream rows are the design
// structure with mastery wired to stats.perCategory next.

const { useState: trUseState, useEffect: trUseEffect } = React;

const TR_LVL = { ok: "var(--accent)", warn: "var(--warn)", no: "var(--no)", new: "var(--ink-4)" };
function trMasteryLevel(pct) { return pct == null ? "new" : pct >= 80 ? "ok" : pct >= 50 ? "warn" : "no"; }
// Real per-family mastery from the user's stats (null = not practised yet).
function trFamilyMastery(stats) {
  const pc = (stats && stats.perCategory) || {};
  const CM = (typeof window !== "undefined" && window.CATEGORY_META) || {};
  const agg = {};
  for (const cat in pc) {
    const fam = CM[cat] && CM[cat].family;
    if (!fam) continue;
    if (!agg[fam]) agg[fam] = { seen: 0, correct: 0 };
    agg[fam].seen += pc[cat].seen || 0; agg[fam].correct += pc[cat].correct || 0;
  }
  const pct = (fam) => (agg[fam] && agg[fam].seen) ? Math.round(agg[fam].correct / agg[fam].seen * 100) : null;
  return { wf: pct("word-formation"), gr: pct("grammar"), mc: pct("multiple-choice"), ir: pct("irregular") };
}
// Per-stream verb mastery (categories "irregular-verbs:<stream>"); null = new.
function trVerbStreamMastery(stats) {
  const pc = (stats && stats.perCategory) || {};
  const pct = (k) => { const c = pc["irregular-verbs:" + k]; return (c && c.seen) ? Math.round(c.correct / c.seen * 100) : null; };
  return { complete: pct("complete"), spelling: pct("spelling"), brackets: pct("brackets") };
}
const TR_RUN_LENGTHS = ["5", "10", "20", "Endless"];

// local desktop hook (mirrors the app's 761px breakpoint; no global dependency)
function trUseDesktop() {
  const [d, setD] = trUseState(() => typeof matchMedia !== "undefined" && matchMedia("(min-width: 761px)").matches);
  trUseEffect(() => {
    if (typeof matchMedia === "undefined") return;
    const mq = matchMedia("(min-width: 761px)");
    const on = () => setD(mq.matches);
    mq.addEventListener ? mq.addEventListener("change", on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", on) : mq.removeListener(on); };
  }, []);
  return d;
}

// day streak — same logic as HomeScreen (consecutive active days back from today)
function trDayStreak(stats) {
  const h = (stats && stats.dailyHistory) || {};
  let n = 0; const d = new Date();
  while (true) {
    const k = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    if (h[k] && h[k].answered > 0) { n++; d.setDate(d.getDate() - 1); } else break;
  }
  return n;
}

// Mixed-practice families + the Irregular-Verbs streams. Structure is real;
// `mastery`/`items` get wired to stats.perCategory + the verb dataset next.
const TR_FAMILIES = [
  { id: "wf", fam: "word-formation", name: "Word Formation", desc: "Transform the word to fit the sentence.", items: 666, mastery: 77, unit: "items" },
  { id: "gr", fam: "grammar", name: "Grammar", desc: "Rewrite the cue word into the required form.", items: 528, mastery: 60, unit: "items" },
  { id: "mc", fam: "multiple-choice", name: "Multiple Choice", desc: "Pick the option that fits the blank.", items: 334, mastery: 78, unit: "items" },
];
// Families per exam: OGE has no multiple-choice (EGE-only) — OGE students get
// their own Word Formation + Grammar; both exams get the Irregular-Verbs drill.
function trFamiliesForExam(examMode) {
  return examMode === "oge" ? TR_FAMILIES.filter((f) => f.fam !== "multiple-choice") : TR_FAMILIES;
}
const TR_VERB_STREAMS = [
  { id: "complete", name: "Complete the form", desc: "Give the past simple and past participle.", eg: "begin → began · begun", items: 60, mastery: 47, unit: "verbs" },
  { id: "spelling", name: "Spelling", desc: "Two forms shown — type the missing one.", eg: "throw · threw · —", items: 60, mastery: 41, unit: "verbs" },
  { id: "brackets", name: "Open the brackets", desc: "Put the verb in brackets in the right tense.", eg: "had just ___ (leave)", items: 60, mastery: 39, unit: "verbs" },
];
const trAvg = (arr) => { const v = arr.map((x) => x.mastery).filter((m) => m != null); return v.length ? Math.round(v.reduce((s, x) => s + x, 0) / v.length) : null; };

function TrChev({ s = 18 }) {
  return <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M9 5l7 7-7 7" /></svg>;
}
function TrArrow() { return <span className="cta-arrow">→</span>; }
function TrLiveIcon() {
  return <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="2.4" /><path d="M7.5 7.5a6 6 0 0 0 0 9M16.5 7.5a6 6 0 0 1 0 9M4.7 4.7a10 10 0 0 0 0 14.6M19.3 4.7a10 10 0 0 1 0 14.6" /></svg>;
}

function TrMasteryList({ rows }) {
  return (
    <ul className="cat-list">
      {rows.map((r) => {
        const c = TR_LVL[trMasteryLevel(r.mastery)];
        return (
          <li className="cat-row" key={r.id}>
            <span className="status-dot" style={{ background: c }} />
            <span className="cat-name">{r.name}</span>
            <span className="cat-bar"><span className="cat-bar-fill" style={{ width: `${r.mastery || 0}%`, background: c }} /></span>
            <span className="cat-pct">{r.mastery == null ? "new" : r.mastery + "%"}</span>
          </li>
        );
      })}
    </ul>
  );
}

// entry card — desktop shows an inline CTA; mobile makes the whole card tappable.
function TrEntryCard({ dot, title, meta, cta, rows, isDesktop, onOpen }) {
  const head = (
    <div className="t-trainer-head">
      <span className="dot" style={{ background: dot }} />
      <div className="h"><h3>{title}</h3>{meta ? <div className="meta">{meta}</div> : null}</div>
      {isDesktop
        ? <button className="cta-primary" onClick={onOpen}><span>{cta}</span><TrArrow /></button>
        : <span className="t-chev"><TrChev /></span>}
    </div>
  );
  if (isDesktop) return <div className="card t-trainer">{head}<TrMasteryList rows={rows} /></div>;
  return <button className="card t-trainer" onClick={onOpen}>{head}<TrMasteryList rows={rows} /></button>;
}

// shared setup picker (Practice sets + Irregular Verbs)
function TrTaskPicker({ title, facts, items, startWord, defLen, isDesktop, onBack, onStart, defaultOn, note }) {
  const [on, setOn] = trUseState(() => {
    const init = Object.fromEntries(items.map((i) => [i.id, defaultOn ? !!defaultOn[i.id] : true]));
    return Object.values(init).some(Boolean) ? init : Object.fromEntries(items.map((i) => [i.id, true]));
  });
  const [len, setLen] = trUseState(defLen);
  const count = Object.values(on).filter(Boolean).length;
  const toggle = (id) => setOn((s) => {
    const next = { ...s, [id]: !s[id] };
    return Object.values(next).some(Boolean) ? next : s; // at least one stays on
  });
  const startLabel = len === "Endless" ? `Start endless ${startWord}` : `Start ${len}-question ${startWord}`;
  const fire = () => onStart(items.filter((i) => on[i.id]).map((i) => i.id), len);
  const summary = count === items.length ? `all ${items.length} task types` : `${count} task type${count > 1 ? "s" : ""}`;

  const grid = (
    <div className="t-pickgrid">
      {items.map((it) => {
        const c = TR_LVL[trMasteryLevel(it.mastery)], isOn = on[it.id];
        return (
          <button key={it.id} className={`cat-card ${isOn ? "is-on" : ""}`} onClick={() => toggle(it.id)}>
            <div className="cat-card-head">
              <span className="cat-card-title">{it.name}</span>
              <span className={`switch ${isOn ? "is-on" : ""}`}><span /></span>
            </div>
            <div className="cat-card-blurb">{it.desc}</div>
            {it.eg && <div className="cat-card-eg">{it.eg}</div>}
            <div className="cat-bar"><span className="cat-bar-fill" style={{ width: `${it.mastery || 0}%`, background: c }} /></div>
            <div className="cat-card-foot is-split"><span>{it.items} {it.unit}</span><span className="cat-card-mastery" style={{ color: c }}>{it.mastery == null ? "new" : it.mastery + "% mastery"}</span></div>
          </button>
        );
      })}
    </div>
  );

  return (
    <div className="trainer-page">
      <div className="t-shell">
        <button className="t-back" onClick={onBack}>← Trainer</button>
        <h1 className="t-page-title">{title}</h1>
        <p className="t-facts">{facts}</p>

        <section className="t-block">
          <div className="t-head"><h2>Choose task types</h2><span className="sub">{count} of {items.length} on · at least one stays on</span></div>
          {grid}
          {note && <p className="t-facts" style={{ marginTop: 12 }}>{note}</p>}
        </section>

        <section className="t-block">
          <div className="t-head"><h2>Run length</h2></div>
          {isDesktop ? (
            <div className="t-launch">
              <div className="segmented" role="radiogroup">
                {TR_RUN_LENGTHS.map((v) => <button key={v} className={`segmented-btn ${len === v ? "is-on" : ""}`} onClick={() => setLen(v)}>{v}</button>)}
              </div>
              <button className="cta-primary" onClick={fire}><span>{startLabel}</span><TrArrow /></button>
              <span className="sub">{summary}</span>
            </div>
          ) : (
            <>
              <div className="segmented t-block-seg" role="radiogroup">
                {TR_RUN_LENGTHS.map((v) => <button key={v} className={`segmented-btn ${len === v ? "is-on" : ""}`} onClick={() => setLen(v)}>{v}</button>)}
              </div>
              <button className="cta-primary" style={{ width: "100%", justifyContent: "space-between", marginTop: 16 }} onClick={fire}>
                <span>{startLabel}</span><TrArrow />
              </button>
              <p className="t-facts" style={{ textAlign: "center", marginTop: 10 }}>{summary}</p>
            </>
          )}
        </section>
      </div>
    </div>
  );
}

function TrainerScreen({ stats, settings, examMode, onOpenMistakes, onOpenLive, onStartMixed, onStartVerbs }) {
  const isDesktop = trUseDesktop();
  const [view, setView] = trUseState("hub");
  const tasksLabel = examMode === "oge" ? "OGE tasks" : "EGE tasks";

  const families = trFamiliesForExam(examMode);
  const fm = trFamilyMastery(stats);
  const famRows = families.map((f) => ({ ...f, mastery: fm[f.id] }));
  // Preselect the task types the student already has enabled in Tests/Settings.
  const CM = (typeof window !== "undefined" && window.CATEGORY_META) || {};
  const enabledFams = new Set(((settings && settings.categories) || []).map((c) => CM[c] && CM[c].family).filter(Boolean));
  const setsDefaultOn = Object.fromEntries(families.map((f) => [f.id, enabledFams.size ? enabledFams.has(f.fam) : true]));
  const vm = trVerbStreamMastery(stats);
  const verbRows = TR_VERB_STREAMS.map((s) => ({ ...s, mastery: vm[s.id] }));

  const answered = (stats && stats.totalAnswered) || 0;
  const acc = answered ? Math.round(((stats.totalCorrect || 0) / answered) * 100) : 0;
  const streak = trDayStreak(stats);
  const facts = <><b>{streak}</b>-day streak · <b>{answered}</b> answered · <b>{acc}%</b> lifetime accuracy</>;

  if (view === "sets") {
    return <TrTaskPicker title={tasksLabel} facts="Mixed practice · choose the task types"
      items={famRows} startWord="set" defLen="10" isDesktop={isDesktop}
      defaultOn={setsDefaultOn} note="Preselected from your Tests settings — change them any time in Settings."
      onBack={() => setView("hub")} onStart={(types, len) => onStartMixed && onStartMixed(types, len)} />;
  }
  if (view === "verbs") {
    return <TrTaskPicker title="Irregular Verbs" facts="Three task types · choose what to include"
      items={verbRows} startWord="run" defLen="20" isDesktop={isDesktop}
      onBack={() => setView("hub")} onStart={(types, len) => onStartVerbs && onStartVerbs(types, len)} />;
  }

  return (
    <div className="trainer-page">
      <div className="t-shell">
        <header className="t-block">
          <h1 className="t-page-title">Trainer</h1>
          <p className="t-facts">{facts}</p>
        </header>

        <section className="t-block">
          <div className="t-head"><h2>{tasksLabel}</h2></div>
          <TrEntryCard dot={TR_LVL[trMasteryLevel(trAvg(famRows))]} title="Mixed practice"
            cta="Practice" rows={famRows} isDesktop={isDesktop} onOpen={() => setView("sets")} />
        </section>

        <section className="t-block">
          <div className="t-head"><h2>Focused drills</h2></div>
          <TrEntryCard dot={TR_LVL.new} title="Irregular Verbs"
            cta="Train" rows={verbRows} isDesktop={isDesktop} onOpen={() => setView("verbs")} />
        </section>

        <section className="t-block">
          <div className="t-head"><h2>Review</h2></div>
          <div className="card mistakes-card">
            <div>
              <div className="card-eyebrow">Mistakes</div>
              <div className="mistakes-title">Review your mistakes</div>
              <div className="mistakes-sub">Everything you've missed, gathered in one place. Get one right enough times and it leaves the list.</div>
            </div>
            <button className="cta-primary mistakes-cta" onClick={onOpenMistakes}><span>Review</span><TrArrow /></button>
          </div>
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { TrainerScreen });
