/* =========================================================================
   TAXR — Daily Review (spaced repetition)
   Resurfaces the questions & flashcards a learner has missed, scheduled by a
   Leitner box system. Quiz misses come back as questions; flashcard misses as
   cards. Getting one right moves it up a box (longer until it returns); missing
   it again resets it to tomorrow.
   ========================================================================= */
function Review({ nav, account, progress, recordReview }) {
  const reviewMap = progress.review || {};
  const now = Date.now();

  // snapshot the due queue ONCE so it doesn't reshuffle as we record results
  const [queue] = useState(() =>
    Object.entries(reviewMap)
      .filter(([, r]) => r && r.due <= now)
      .sort((a, b) => (a[1].box - b[1].box) || (a[1].due - b[1].due))
      .map(([id, r]) => ({ id, ...r }))
  );

  const [pos, setPos] = useState(0);
  const [picked, setPicked] = useState(null);
  const [submitted, setSubmitted] = useState(false);
  const [flipped, setFlipped] = useState(false);
  const [tally, setTally] = useState({ right: 0, wrong: 0 });
  const [doneStage, setDoneStage] = useState(false);

  // ---- empty state (nothing due) ----
  if (queue.length === 0 || doneStage) {
    const total = Object.keys(reviewMap).length;
    const upcoming = Object.values(reviewMap)
      .filter((r) => r && r.due > now)
      .sort((a, b) => a.due - b.due)[0];
    const nextWhen = upcoming ? humanDue(upcoming.due - now) : null;
    const mastered = doneStage ? tally.right : 0;
    return (
      <div className="wrap col center" style={{ padding: "70px 32px", minHeight: "72vh" }}>
        <div className="card grid-lines" style={{ maxWidth: 540, width: "100%", padding: 40, textAlign: "center" }}>
          <span style={{ fontSize: 50 }}>🐧</span>
          <h1 className="display" style={{ fontSize: 36, marginTop: 10 }}>{doneStage ? <>Review <span className="it">done.</span></> : <>All <span className="it">caught up.</span></>}</h1>
          {doneStage ? (
            <p className="fs-16 t-muted lh-rel" style={{ margin: "16px auto 6px", maxWidth: 400 }}>
              You reviewed {tally.right + tally.wrong} item{tally.right + tally.wrong === 1 ? "" : "s"} — {tally.right} solid, {tally.wrong} coming back sooner. {nextWhen ? "Next batch is due " + nextWhen + "." : "Nothing else is scheduled."}
            </p>
          ) : (
            <p className="fs-16 t-muted lh-rel" style={{ margin: "16px auto 6px", maxWidth: 400 }}>
              {total === 0
                ? "Nothing to review yet. As you take module tests and drill flashcards, anything you miss lands here — and Pip brings it back right before you'd forget it."
                : "No items are due right now. " + (nextWhen ? "Your next review is " + nextWhen + "." : "")}
            </p>
          )}
          <div className="row center gap-12" style={{ marginTop: 26 }}>
            <Button arrow onClick={() => nav("dashboard")}>Back to track</Button>
          </div>
        </div>
      </div>
    );
  }

  const item = queue[pos];
  const isCard = item.type === "card";
  const p = item.payload || {};

  function recordAndNext(correct) {
    recordReview({ id: item.id, type: item.type, correct, payload: p });
    setTally((t) => ({ right: t.right + (correct ? 1 : 0), wrong: t.wrong + (correct ? 0 : 1) }));
    if (pos === queue.length - 1) { setDoneStage(true); return; }
    setPos(pos + 1); setPicked(null); setSubmitted(false); setFlipped(false);
  }

  function submitQ() {
    if (picked === null) return;
    setSubmitted(true);
  }

  return (
    <div className="wrap" style={{ padding: "26px 32px 80px", maxWidth: 720, margin: "0 auto" }}>
      {/* top bar */}
      <div className="row spread" style={{ marginBottom: 12 }}>
        <button className="row gap-8 fs-14 t-dim" onClick={() => nav("dashboard")}><Icon name="x" size={16} /> End review</button>
        <Badge kind="amber"><Icon name="spark" size={13} style={{ marginRight: 2 }} /> Spaced review</Badge>
      </div>
      <div className="row gap-16" style={{ marginBottom: 26, alignItems: "center" }}>
        <Progress value={(pos / queue.length) * 100} />
        <span className="mono fs-13 t-dim" style={{ flex: "none" }}>{pos + 1} / {queue.length}</span>
      </div>

      {/* meta row */}
      <div className="row gap-12" style={{ marginBottom: 18, alignItems: "center" }}>
        <Badge kind={isCard ? "blue" : item.last === "wrong" ? "amber" : "blue"}>{isCard ? "Flashcard" : "Question"}</Badge>
        <span className="mono fs-13 t-dim">Module {p.moduleNum || "?"} · box {item.box}</span>
        <span className="mono fs-13 t-dim" style={{ marginLeft: "auto" }}>{boxLabel(item.box)}</span>
      </div>

      {/* ---------------- flashcard item ---------------- */}
      {isCard ? (
        <div className="col" style={{ alignItems: "stretch" }}>
          <div style={{ perspective: 1600, margin: "6px 0 22px" }}>
            <button onClick={() => setFlipped((f) => !f)} style={{ width: "100%", height: 280, position: "relative", transformStyle: "preserve-3d", transition: "transform .5s cubic-bezier(.2,.7,.3,1)", transform: flipped ? "rotateY(180deg)" : "none" }}>
              <div className="card grid-lines" style={{ position: "absolute", inset: 0, backfaceVisibility: "hidden", display: "grid", placeItems: "center", padding: 36 }}>
                <div className="col center">
                  <span className="mono fs-13 t-blue upper" style={{ marginBottom: 16 }}>Term</span>
                  <span className="display" style={{ fontSize: 32, textAlign: "center", lineHeight: 1.1 }}>{p.f}</span>
                  <span className="mono fs-13 t-dim" style={{ marginTop: 22 }}>tap to flip</span>
                </div>
              </div>
              <div className="card" style={{ position: "absolute", inset: 0, backfaceVisibility: "hidden", transform: "rotateY(180deg)", display: "grid", placeItems: "center", padding: 36, background: "var(--surface-2)" }}>
                <div className="col center">
                  <span className="mono fs-13 t-green upper" style={{ marginBottom: 14 }}>Definition</span>
                  <span className="fs-17 lh-rel" style={{ textAlign: "center", color: "var(--ink)" }}>{p.b}</span>
                </div>
              </div>
            </button>
          </div>
          <div className="row spread" style={{ alignItems: "center" }}>
            <span className="fs-14 t-dim">{flipped ? "How did you do?" : "Flip it, then grade yourself"}</span>
            <div className="row gap-12">
              <Button variant="ghost" onClick={() => recordAndNext(false)}><Icon name="back" size={15} /> Missed it</Button>
              <Button variant="green" disabled={!flipped} onClick={() => recordAndNext(true)}><Icon name="check" size={16} /> Knew it</Button>
            </div>
          </div>
        </div>
      ) : (
        /* ---------------- question item ---------------- */
        <div>
          <h1 className="serif" style={{ fontSize: 26, lineHeight: 1.28, marginBottom: 24 }}>{p.q}</h1>
          <div className="col gap-12">
            {p.a.map((opt, idx) => {
              const isPick = picked === idx;
              const isCorrect = idx === p.correct;
              let bd = "var(--line)", bg = "var(--surface)", ic = null, tc = "var(--text)";
              if (submitted) {
                if (isCorrect) { bd = "rgba(70,214,164,0.5)"; bg = "var(--green-soft)"; ic = <Icon name="check" size={18} style={{ color: "var(--green)" }} />; }
                else if (isPick) { bd = "rgba(240,132,106,0.5)"; bg = "var(--wrong-soft)"; ic = <Icon name="x" size={18} style={{ color: "var(--wrong)" }} />; }
                else tc = "var(--muted)";
              } else if (isPick) { bd = "var(--blue)"; bg = "var(--blue-soft)"; }
              return (
                <button key={idx} onClick={() => !submitted && setPicked(idx)} disabled={submitted}
                  className="row gap-16" style={{ textAlign: "left", padding: "15px 18px", borderRadius: 13, border: "1px solid " + bd, background: bg, alignItems: "center", cursor: submitted ? "default" : "pointer" }}>
                  <span style={{ width: 26, height: 26, borderRadius: 8, flex: "none", display: "grid", placeItems: "center", border: "1px solid " + (isPick && !submitted ? "var(--blue)" : "var(--line-2)"), fontFamily: "var(--mono)", fontSize: 13, color: isPick && !submitted ? "var(--blue-bright)" : "var(--dim)" }}>{String.fromCharCode(65 + idx)}</span>
                  <span className="fs-16" style={{ flex: 1, color: tc }}>{opt}</span>
                  {ic}
                </button>
              );
            })}
          </div>

          {submitted && (
            <div className="pop" style={{ marginTop: 18, padding: "16px 18px", borderRadius: 14, background: picked === p.correct ? "var(--green-soft)" : "var(--wrong-soft)", border: "1px solid " + (picked === p.correct ? "rgba(70,214,164,0.3)" : "rgba(240,132,106,0.3)") }}>
              <span className="mono fs-13 upper" style={{ color: picked === p.correct ? "var(--green)" : "var(--wrong)" }}>{picked === p.correct ? "Still got it" : "Back in the deck"}</span>
              <p className="fs-15 lh-rel" style={{ color: "var(--ink)", marginTop: 6 }}>{p.why}</p>
            </div>
          )}

          <div className="row spread" style={{ marginTop: 24 }}>
            <span />
            {!submitted
              ? <Button arrow disabled={picked === null} onClick={submitQ}>Check</Button>
              : <Button arrow onClick={() => recordAndNext(picked === p.correct)}>{pos === queue.length - 1 ? "Finish review" : "Next"}</Button>}
          </div>
        </div>
      )}
    </div>
  );
}

/* readable "due in" label */
function humanDue(ms) {
  if (ms <= 0) return "now";
  const d = Math.round(ms / 86400000);
  if (d >= 1) return "in " + d + " day" + (d === 1 ? "" : "s");
  const h = Math.round(ms / 3600000);
  if (h >= 1) return "in " + h + " hr" + (h === 1 ? "" : "s");
  return "shortly";
}
function boxLabel(box) {
  return ["", "learning", "learning", "familiar", "strong", "almost mastered"][box] || "learning";
}

Object.assign(window, { Review });
