// ReflectionScreen.jsx — post-score self-rating.
// Gemini auto-scored already; student picks crisp/blurry/blank and
// optionally explains. POST /api/reflect writes the signal.

function ReflectionScreen({ submission, onAdvance, onBack }) {
  const [stage, setStage] = React.useState("prompt");
  const [response, setResponse] = React.useState("");
  const [verdict, setVerdict] = React.useState(null);
  const [probeAnswer, setProbeAnswer] = React.useState("");
  const [saving, setSaving] = React.useState(false);

  const s = submission || {};
  const autoPct = Math.round((s.auto_score ?? 0) * 100);
  const autoVerdict =
    (s.auto_score ?? 0) >= 0.7 ? "crisp" :
    (s.auto_score ?? 0) >= 0.4 ? "blurry" : "blank";

  // Pick verdict from the student's text. Hedges mark blurry.
  const classify = (text) => {
    const t = text.trim().toLowerCase();
    if (t.length < 10) return "blank";
    if (/kind of|basically|sort of|i think|maybe|somehow/.test(t)) return "blurry";
    return "crisp";
  };

  const submit = () => {
    const v = classify(response);
    setVerdict(v);
    if (v === "blurry") setStage("probe");
    else finalize(v);
  };

  const finalize = async (finalVerdict, probe = "") => {
    setVerdict(finalVerdict);
    if (!s.item_id) {
      setStage("resolved");
      return;
    }
    setSaving(true);
    try {
      await window.API.postReflect({
        item_id: s.item_id,
        auto_score: s.auto_score ?? 0,
        self_rating: finalVerdict,
        probe_answer: probe || probeAnswer || "",
      });
    } catch (e) {
      console.warn("reflect failed:", e);
    }
    setSaving(false);
    setStage("resolved");
  };

  const title = s.title || "Reflection";

  return (
    <section className="reflect">
      <div className="reflect-topbar">
        <button className="back-btn" onClick={onBack}>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M15 6l-6 6 6 6"/></svg>
          {title} · reflection
        </button>
        <div className="reflect-step">
          <span className="d-meta">
            Auto-score {autoPct}% · {autoVerdict}
          </span>
        </div>
      </div>

      {stage === "prompt" && (
        <div className="reflect-card">
          <div className="reflect-eyebrow">Before you advance</div>
          <div className="reflect-serif">Explain why your derivation works.</div>
          <div className="reflect-body">
            {s.feedback || "Explain the step out loud, as if teaching someone who's blurry on it. Specific beats short."}
          </div>
          <textarea
            className="reflect-input"
            placeholder="Because the product rule applies to d(PV), so…"
            value={response}
            onChange={e => setResponse(e.target.value)}
            rows={6}
            autoFocus
          />
          <div className="reflect-meter">
            <span className="chip chip-crisp">crisp</span>
            <span className="chip chip-blurry">blurry</span>
            <span className="chip chip-blank">blank</span>
          </div>
          <div className="reflect-actions">
            <button className="btn-ghost" onClick={() => finalize("blank")} disabled={saving}>I'm blank</button>
            <button className="btn-primary" onClick={submit} disabled={saving || !response.trim()}>Submit</button>
          </div>
        </div>
      )}

      {stage === "probe" && (
        <div className="reflect-card reflect-probe">
          <div className="reflect-eyebrow reflect-eyebrow-probe">Probing · hand-waving detected</div>
          <div className="reflect-serif">Specifically — what's the mechanism?</div>
          <div className="reflect-body">Your answer used the right words without the mechanism. The system would rather know the edge of what you actually know.</div>
          <blockquote className="reflect-quote">
            "{response}"
            <span className="quote-meta">classified <b>blurry</b> · one hedge detected</span>
          </blockquote>
          <textarea
            className="reflect-input"
            placeholder="The mechanism is…"
            value={probeAnswer}
            onChange={e => setProbeAnswer(e.target.value)}
            rows={5}
            autoFocus
          />
          <div className="reflect-actions">
            <button className="btn-ghost" onClick={() => finalize("blank", probeAnswer)} disabled={saving}>I don't know</button>
            <button className="btn-primary" onClick={() => finalize("crisp", probeAnswer)} disabled={saving}>That's clearer</button>
          </div>
        </div>
      )}

      {stage === "resolved" && (
        <div className="reflect-card reflect-resolved">
          <div className={"verdict verdict-" + verdict}>
            <div className="verdict-label">{verdict}</div>
            <div className="verdict-serif">
              {verdict === "crisp" && "Clean. You connected it without prompting."}
              {verdict === "blurry" && "Your explanation stayed hedged. Marked as blurry — we'll revisit this."}
              {verdict === "blank" && "Solid ground. We'll walk back to the prerequisite, then build up."}
            </div>
            {s.gaps && s.gaps.length > 0 && (
              <div className="verdict-notes">
                <div className="notes-label">Gaps flagged</div>
                <div className="notes-body">{s.gaps.join(" · ")}</div>
              </div>
            )}
          </div>
          <div className="reflect-actions">
            <button className="btn-primary" onClick={onAdvance}>Continue</button>
          </div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { ReflectionScreen });
