// Student multi-step wizard.
// 7 steps with rubric-style prompts. Lives on its own; uses local state.
(function () {
const { useState, useMemo, useRef, useEffect } = React;

const WIZARD_STEPS = [
  { id: "context", label: "The letter", num: "01" },
  { id: "goal", label: "Your goal", num: "02" },
  { id: "history", label: "Our shared history", num: "03" },
  { id: "skills", label: "Skills to highlight", num: "04" },
  { id: "moments", label: "Specific moments", num: "05" },
  { id: "growth", label: "Growth", num: "06" },
  { id: "review", label: "Review & send", num: "07" },
];

const BLANK_PACKET = {
  recommender: "Prof. Amelia Hart", letterType: null, otherDescription: "", schools: "", deadline: "",
  goalStatement: "", whyPhd: "", longTerm: "",
  courses: [{ name: "", semester: "", grade: "", note: "" }],
  interactions: "", selectedSkills: [], skillEvidence: {},
  moment: "", failure: "", growth: "", needsGrowth: "", extras: "", resume: null,
};

function StudentWizard({ session }) {
  const store = window.useLAStore();
  const name = (session && session.name) || "Student";
  const draftKey = "la-wizard-" + name;
  const mine = store.submissions().filter((s) => s.student === name);
  const [composing, setComposing] = useState(false);
  const [step, setStep] = useState(0);
  const [confirmLate, setConfirmLate] = useState(false);
  const [data, setData] = useState(() => {
    try { const d = JSON.parse(localStorage.getItem(draftKey)); if (d) return { ...BLANK_PACKET, ...d }; } catch {}
    return BLANK_PACKET;
  });
  useEffect(() => { try { localStorage.setItem(draftKey, JSON.stringify(data)); } catch {} }, [data]);

  const pol = store.policy;
  const late = !!data.deadline && window.LAStore.isLate(data.deadline);

  const submit = () => {
    const ev = { goals: [], courses: [], projects: [], skills: [], anecdotes: [], growth: [], extras: [] };
    if (data.goalStatement) ev.goals.push({ id: "g1", label: "Stated goal", text: data.goalStatement });
    if (data.whyPhd) ev.goals.push({ id: "g2", label: "Why this path", text: data.whyPhd });
    if (data.longTerm) ev.goals.push({ id: "g3", label: "Long-term ambition", text: data.longTerm });
    data.courses.filter((c) => c.name).forEach((c, i) => ev.courses.push({ id: "c" + (i + 1), label: c.name, text: ((c.semester || "") + (c.grade ? " (" + c.grade + ")" : "") + ". " + (c.note || "")).trim() }));
    if (data.interactions) ev.courses.push({ id: "c-x", label: "Other interactions", text: data.interactions });
    data.selectedSkills.forEach((s, i) => { const t = data.skillEvidence[s]; if (t) ev.skills.push({ id: "s" + (i + 1), label: s, text: t, rubric: "How I evidence " + s.toLowerCase() }); });
    if (data.moment) ev.anecdotes.push({ id: "a1", label: "A moment that mattered", text: data.moment });
    if (data.failure) ev.anecdotes.push({ id: "a2", label: "A failure I'm proud of", text: data.failure });
    if (data.growth) ev.growth.push({ id: "gr1", label: "How I've changed", text: data.growth });
    if (data.needsGrowth) ev.growth.push({ id: "gr2", label: "Where I still need to grow", text: data.needsGrowth });
    if (data.extras) ev.extras.push({ id: "x1", label: "Anything else", text: data.extras });
    const lt = window.LETTER_TYPES.find((t) => t.id === data.letterType);
    const purpose = data.letterType === "other" ? (data.otherDescription || "Other request") : (lt ? lt.label : "Letter request");
    const fmt = (iso) => { const d = new Date(iso + "T12:00:00"); return isNaN(d) ? (iso || "—") : d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); };
    const initials = name.split(/\s+/).filter(Boolean).map((w) => w[0]).slice(0, 2).join("").toUpperCase() || "?";
    window.LAStore.addSubmission({
      id: "sub-" + Date.now(),
      student: name, pronouns: "", headshot: initials,
      purpose, otherDescription: data.letterType === "other" ? data.otherDescription : undefined,
      targets: data.schools.split("\n").map((s) => s.trim()).filter(Boolean),
      deadline: data.deadline ? fmt(data.deadline) : "—", deadlineISO: data.deadline || null,
      submitted: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }),
      status: "new", late,
      relationship: data.interactions,
      attachments: data.resume ? [{ id: "att-1", kind: "resume", ...data.resume }] : [],
      evidence: ev,
    });
    try { localStorage.removeItem(draftKey); } catch {}
    setData(BLANK_PACKET); setStep(0); setConfirmLate(false); setComposing(false);
  };

  const update = (patch) => setData((d) => ({ ...d, ...patch }));
  const stepId = WIZARD_STEPS[step].id;

  const completion = useMemo(() => {
    // rough completion calc
    let filled = 0, total = 7;
    if (data.recommender && data.letterType) filled++;
    if (data.goalStatement && data.whyPhd) filled++;
    if (data.courses.length) filled++;
    if (data.selectedSkills.length >= 3) filled++;
    if (data.moment) filled++;
    if (data.growth) filled++;
    if (data.extras !== undefined) filled++;
    return Math.round((filled / total) * 100);
  }, [data]);

  if (mine.length && !composing) return <StatusTracker subs={mine} onNew={() => setComposing(true)} />;

  return (
    <div className="page-wrap wizard-grid">
      {/* Stepper */}
      <aside className="wizard-stepper-sticky">
        {mine.length > 0 && <button className="btn btn-ghost btn-sm" onClick={() => setComposing(false)} style={{ marginBottom: 10, marginLeft: -10 }}>← My requests</button>}
        <div className="eyebrow" style={{ marginBottom: 14 }}>Recommendation packet</div>
        <h2 style={{ fontSize: 22, lineHeight: 1.15, marginBottom: 6 }}>For Prof. Hart</h2>
        <div style={{ color: "var(--muted)", fontSize: 12.5, marginBottom: 18 }}>{data.deadline ? "Due " + data.deadline + " · " : ""}7 sections</div>

        <div style={{ height: 4, background: "var(--line-soft)", borderRadius: 4, overflow: "hidden", marginBottom: 18 }}>
          <div style={{ height: "100%", width: `${completion}%`, background: "var(--accent)", transition: "width 0.3s" }} />
        </div>

        <ol className="wizard-step-list">
          {WIZARD_STEPS.map((s, i) => (
            <li key={s.id}>
              <button
                onClick={() => setStep(i)}
                style={{
                  width: "100%", textAlign: "left",
                  display: "flex", alignItems: "baseline", gap: 12,
                  padding: "10px 12px",
                  border: 0, background: i === step ? "var(--accent-tint)" : "transparent",
                  borderLeft: i === step ? "2px solid var(--accent)" : "2px solid transparent",
                  cursor: "pointer", borderRadius: 0,
                  color: i === step ? "var(--accent)" : i < step ? "var(--ink)" : "var(--muted)",
                  fontFamily: "var(--sans)", fontSize: 13.5,
                  fontWeight: i === step ? 500 : 400,
                }}
              >
                <span className="mono" style={{ fontSize: 10.5, opacity: 0.7 }}>{s.num}</span>
                <span>{s.label}</span>
                {i < step && <span style={{ marginLeft: "auto", color: "var(--good)", fontSize: 11 }}>✓</span>}
              </button>
            </li>
          ))}
        </ol>
      </aside>

      {/* Form panel */}
      <section>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 24 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Step {WIZARD_STEPS[step].num} of 07</div>
            <h1 style={{ fontSize: 34, lineHeight: 1.1, letterSpacing: "-0.015em" }}>
              {stepHeading(stepId)}
            </h1>
            <p style={{ color: "var(--ink-3)", fontSize: 15, maxWidth: 620, marginTop: 10, lineHeight: 1.55 }}>
              {stepSubhead(stepId)}
            </p>
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 28, maxWidth: 720 }}>
          {stepId === "context" && <ContextStep data={data} update={update} late={late} pol={pol} />}
          {stepId === "goal" && <GoalStep data={data} update={update} />}
          {stepId === "history" && <HistoryStep data={data} update={update} />}
          {stepId === "skills" && <SkillsStep data={data} update={update} />}
          {stepId === "moments" && <MomentsStep data={data} update={update} />}
          {stepId === "growth" && <GrowthStep data={data} update={update} />}
          {stepId === "review" && <ReviewStep data={data} />}
        </div>

        {step === WIZARD_STEPS.length - 1 && late && (
          <div style={{ marginTop: 24, padding: "10px 14px", background: "#FFFBEB", border: "1px solid #FDE68A", borderRadius: "var(--r)", fontSize: 13, color: "#92400E" }}>
            {confirmLate
              ? "This request will arrive flagged as late — Prof. Hart decides whether to accept it."
              : `Heads up: your deadline is inside Prof. Hart's ${pol.amount}-${pol.unit.replace(/s$/, "")} submission window. You can still send, but she may decline.`}
          </div>
        )}
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: late && step === WIZARD_STEPS.length - 1 ? 16 : 40, paddingTop: 20, borderTop: "1px solid var(--line-soft)" }}>
          <button className="btn btn-ghost" onClick={() => setStep(Math.max(0, step - 1))} disabled={step === 0}>← Back</button>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <span style={{ color: "var(--muted)", fontSize: 12.5 }}>Auto-saved · just now</span>
            {step < WIZARD_STEPS.length - 1 ? (
              <button className="btn btn-primary" onClick={() => setStep(step + 1)}>Continue →</button>
            ) : late && !confirmLate ? (
              <button className="btn btn-accent" onClick={() => setConfirmLate(true)}>Send to Prof. Hart →</button>
            ) : (
              <button className="btn btn-accent" onClick={submit}>{late ? "Send anyway →" : "Send to Prof. Hart →"}</button>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}

function stepHeading(id) {
  return {
    context: "What's the letter for?",
    goal: "What do you want to do, and why?",
    history: "How does Prof. Hart know you?",
    skills: "Which qualities should the letter make the case for?",
    moments: "Tell me a story.",
    growth: "How have you changed?",
    review: "Review what Prof. Hart will see",
  }[id];
}
function stepSubhead(id) {
  return {
    context: "We'll send Prof. Hart a single, organized packet. Start with the basics.",
    goal: "A recommendation letter is most useful when the writer knows exactly what you're asking the reader to believe about your future.",
    history: "List every course, project, or interaction. We'll let Prof. Hart pick what to emphasize.",
    skills: "Pick three to five qualities you most want highlighted. For each one, give a concrete piece of evidence — a specific situation, not an adjective.",
    moments: "The strongest letters contain one or two specific scenes. Describe a moment Prof. Hart was there for. A disagreement, a turning point, a failure.",
    growth: "Selection committees read for trajectory. Where have you grown? Where do you still need to?",
    review: "This is what gets sent. Prof. Hart can also see who else you're asking and what schools you're applying to.",
  }[id];
}

// ---------- Step components ----------
function ContextStep({ data, update, late, pol }) {
  return (
    <>
      <div>
        <label className="label">Recommender</label>
        <input className="input" value={data.recommender} onChange={(e) => update({ recommender: e.target.value })} />
      </div>
      <div>
        <label className="label">What's the letter for?</label>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
          {window.LETTER_TYPES.map((t) => (
            <button
              key={t.id}
              onClick={() => update({ letterType: t.id })}
              style={{
                textAlign: "left", padding: "12px 14px",
                border: `1px solid ${data.letterType === t.id ? "var(--accent)" : "var(--line)"}`,
                background: data.letterType === t.id ? "var(--accent-tint)" : "var(--surface-3)",
                borderRadius: "var(--r)", cursor: "pointer",
                display: "flex", alignItems: "center", gap: 12,
                fontFamily: "var(--sans)",
              }}
            >
              <span style={{ fontSize: 18, fontFamily: "var(--serif)", color: "var(--accent)", width: 20 }}>{t.icon}</span>
              <div>
                <div style={{ fontWeight: 500, fontSize: 13.5 }}>{t.label}</div>
                <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 2 }}>{t.blurb}</div>
              </div>
            </button>
          ))}
        </div>
        {data.letterType === "other" && (
          <div style={{ marginTop: 10 }}>
            <textarea className="textarea" rows={3} autoFocus placeholder="Briefly describe what this letter is for — the program or opportunity, who it goes to, and anything unusual about the format." value={data.otherDescription || ""} onChange={(e) => update({ otherDescription: e.target.value })}></textarea>
            <div className="help">Prof. Hart sees this exactly as written, so be specific.</div>
          </div>
        )}
      </div>
      <div>
        <label className="label">Where are you applying?</label>
        <textarea className="textarea" rows={4} value={data.schools} onChange={(e) => update({ schools: e.target.value })} />
        <div className="help">One per line. Prof. Hart sees this so she can tailor the letter or flag conflicts.</div>
      </div>
      <div>
        <label className="label">Earliest deadline</label>
        <input className="input" type="date" value={data.deadline} onChange={(e) => update({ deadline: e.target.value })} style={{ maxWidth: 220 }} />
        {late && (
          <div style={{ marginTop: 8, padding: "8px 12px", background: "#FFFBEB", border: "1px solid #FDE68A", borderRadius: "var(--r)", fontSize: 12.5, color: "#92400E", lineHeight: 1.5 }}>
            Prof. Hart asks for packets at least {pol.amount} {pol.unit} before your earliest deadline. This deadline is inside that window — you can still send, but the request arrives flagged as late and she may decline.
          </div>
        )}
      </div>
      <div>
        <label className="label">Attach your résumé or CV</label>
        <div className="help" style={{ marginTop: 0, marginBottom: 8 }}>
          Prof. Hart sees this alongside everything else in your packet. PDF or .docx, up to 10 MB. One file.
        </div>
        <ResumeUpload resume={data.resume} onChange={(r) => update({ resume: r })} />
      </div>
    </>
  );
}

function ResumeUpload({ resume, onChange }) {
  const inputRef = useRef(null);
  const [dragging, setDragging] = useState(false);

  const handleFiles = (files) => {
    if (!files || !files.length) return;
    const f = files[0];
    // Mock: estimate pages by size (~80 KB per page).
    const pages = Math.max(1, Math.round(f.size / 80000));
    const now = new Date();
    const time = now.toLocaleString("en-US", { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
    onChange({ name: f.name, size: f.size, pages, uploadedAt: time });
  };

  if (resume) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 16px", background: "var(--surface-3)", border: "1px solid var(--line)", borderRadius: "var(--r-md)" }}>
        <div style={{ width: 38, height: 48, borderRadius: 3, background: "var(--accent-tint)", border: "1px solid var(--accent-tint-border)", display: "grid", placeItems: "center", fontFamily: "var(--serif)", fontSize: 11, fontWeight: 500, color: "var(--accent)", letterSpacing: "0.05em", flexShrink: 0 }}>
          PDF
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 14.5, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{resume.name}</div>
          <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 3 }}>
            {resume.pages} {resume.pages === 1 ? "page" : "pages"} · {fmtSize(resume.size)} · uploaded {resume.uploadedAt}
          </div>
        </div>
        <button className="btn btn-sm" onClick={() => inputRef.current?.click()}>Replace</button>
        <button className="btn btn-ghost btn-sm" onClick={() => onChange(null)} style={{ color: "var(--muted)" }}>Remove</button>
        <input
          ref={inputRef}
          type="file"
          accept=".pdf,.doc,.docx,application/pdf"
          style={{ display: "none" }}
          onChange={(e) => handleFiles(e.target.files)}
        />
      </div>
    );
  }

  return (
    <label
      onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
      onDragLeave={() => setDragging(false)}
      onDrop={(e) => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files); }}
      style={{
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        gap: 6, padding: "28px 20px", cursor: "pointer",
        border: `1.5px dashed ${dragging ? "var(--accent)" : "var(--line-strong)"}`,
        background: dragging ? "var(--accent-tint)" : "var(--surface-3)",
        borderRadius: "var(--r-md)", textAlign: "center",
        transition: "background 0.12s, border-color 0.12s",
      }}
    >
      <div style={{ fontFamily: "var(--serif)", fontSize: 24, color: "var(--accent)", lineHeight: 1 }}>↑</div>
      <div style={{ fontFamily: "var(--serif)", fontSize: 15, color: "var(--ink)" }}>Drop your résumé here, or click to browse</div>
      <div style={{ fontSize: 12, color: "var(--muted)" }}>PDF or .docx · max 10 MB</div>
      <input
        type="file"
        accept=".pdf,.doc,.docx,application/pdf"
        style={{ display: "none" }}
        onChange={(e) => handleFiles(e.target.files)}
      />
    </label>
  );
}

function fmtSize(bytes) {
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
  return (bytes / (1024 * 1024)).toFixed(1) + " MB";
}

function GoalStep({ data, update }) {
  return (
    <>
      <RubricPrompt
        label="What you want to do (the elevator pitch)"
        hint="Two or three sentences a non-specialist could read. Be specific about the question, not just the field."
        value={data.goalStatement}
        onChange={(v) => update({ goalStatement: v })}
        rows={4}
      />
      <RubricPrompt
        label="Why this path, specifically"
        hint="If a reader asked 'why not the industry version of this?' — what would you say?"
        value={data.whyPhd}
        onChange={(v) => update({ whyPhd: v })}
        rows={3}
      />
      <RubricPrompt
        label="Where you'd like to be in ten years"
        hint="Selection committees use this to calibrate the letter's claims. Aspirational is fine; vague is not."
        value={data.longTerm}
        onChange={(v) => update({ longTerm: v })}
        rows={3}
      />
    </>
  );
}

function HistoryStep({ data, update }) {
  const setCourse = (i, patch) => {
    const next = [...data.courses];
    next[i] = { ...next[i], ...patch };
    update({ courses: next });
  };
  const addCourse = () => update({ courses: [...data.courses, { name: "", semester: "", grade: "", note: "" }] });
  const removeCourse = (i) => update({ courses: data.courses.filter((_, j) => j !== i) });

  return (
    <>
      <div>
        <label className="label">Courses, labs, or projects with this recommender</label>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {data.courses.map((c, i) => (
            <div key={i} style={{ border: "1px solid var(--line)", background: "var(--surface-3)", borderRadius: "var(--r-md)", padding: 14 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 80px 32px", gap: 8, alignItems: "end" }}>
                <input className="input" placeholder="Course or project name" value={c.name} onChange={(e) => setCourse(i, { name: e.target.value })} />
                <input className="input" placeholder="Term" value={c.semester} onChange={(e) => setCourse(i, { semester: e.target.value })} />
                <input className="input" placeholder="Grade" value={c.grade} onChange={(e) => setCourse(i, { grade: e.target.value })} />
                <button className="btn btn-ghost btn-icon" onClick={() => removeCourse(i)} title="Remove">×</button>
              </div>
              <textarea
                className="textarea"
                rows={2}
                placeholder="What did you do or learn here that the recommender witnessed?"
                value={c.note}
                onChange={(e) => setCourse(i, { note: e.target.value })}
                style={{ marginTop: 10 }}
              />
            </div>
          ))}
          <button className="btn btn-sm" onClick={addCourse} style={{ alignSelf: "flex-start" }}>+ Add another</button>
        </div>
      </div>

      <RubricPrompt
        label="Other interactions worth mentioning"
        hint="Office hours, hallway conversations, advising — anything outside the formal coursework."
        value={data.interactions}
        onChange={(v) => update({ interactions: v })}
        rows={4}
      />
    </>
  );
}

function SkillsStep({ data, update }) {
  const toggle = (skill) => {
    const has = data.selectedSkills.includes(skill);
    update({ selectedSkills: has ? data.selectedSkills.filter((s) => s !== skill) : [...data.selectedSkills, skill] });
  };
  const setEvidence = (skill, text) => {
    update({ skillEvidence: { ...data.skillEvidence, [skill]: text } });
  };
  return (
    <>
      <div>
        <label className="label">Choose three to five qualities</label>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
          {window.RUBRIC_SKILLS.map((s) => (
            <span key={s} className={"chip" + (data.selectedSkills.includes(s) ? " active" : "")} onClick={() => toggle(s)}>
              {data.selectedSkills.includes(s) && <span style={{ fontSize: 10 }}>✓</span>}
              {s}
            </span>
          ))}
        </div>
        <div className="help">{data.selectedSkills.length} selected · 3–5 recommended</div>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        {data.selectedSkills.map((s) => (
          <div key={s} style={{ border: "1px solid var(--line)", background: "var(--surface-3)", borderRadius: "var(--r-md)", padding: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
              <div style={{ fontFamily: "var(--serif)", fontSize: 17 }}>{s}</div>
              <span className="eyebrow">Evidence</span>
            </div>
            <p style={{ fontSize: 12.5, color: "var(--muted)", margin: "0 0 10px 0" }}>
              Describe one specific situation, not a general claim. What happened? What did you do? What did Prof. Hart see?
            </p>
            <textarea
              className="textarea"
              rows={3}
              value={data.skillEvidence[s] || ""}
              onChange={(e) => setEvidence(s, e.target.value)}
              placeholder={`How would Prof. Hart witness your ${s.toLowerCase()}?`}
            />
          </div>
        ))}
      </div>
    </>
  );
}

function MomentsStep({ data, update }) {
  return (
    <>
      <RubricPrompt
        label="A moment when something changed"
        hint="A disagreement, a result that surprised you, a conversation that shifted your thinking. Put us in the room — when, where, what was said."
        value={data.moment}
        onChange={(v) => update({ moment: v })}
        rows={5}
      />
      <RubricPrompt
        label="A failure you're proud of"
        hint="Something that didn't work, what you learned, and what you do differently now. Don't sand off the failure."
        value={data.failure}
        onChange={(v) => update({ failure: v })}
        rows={5}
      />
    </>
  );
}

function GrowthStep({ data, update }) {
  return (
    <>
      <RubricPrompt
        label="How you've changed since Prof. Hart first met you"
        hint="A belief you used to hold, an instinct you've outgrown, or a skill you've developed."
        value={data.growth}
        onChange={(v) => update({ growth: v })}
        rows={4}
      />
      <RubricPrompt
        label="Where you still need to grow"
        hint="Selection committees trust applicants who can name their own limits. Be honest, be specific."
        value={data.needsGrowth}
        onChange={(v) => update({ needsGrowth: v })}
        rows={4}
      />
      <RubricPrompt
        label="Anything else Prof. Hart should know"
        hint="Context you'd want her to have. She decides whether to use it."
        value={data.extras}
        onChange={(v) => update({ extras: v })}
        rows={4}
      />
    </>
  );
}

function ReviewStep({ data }) {
  const Row = ({ k, v }) => (
    <div style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 24, padding: "14px 0", borderBottom: "1px solid var(--line-soft)" }}>
      <div className="eyebrow" style={{ paddingTop: 2 }}>{k}</div>
      <div style={{ fontSize: 14, color: "var(--ink-2)", whiteSpace: "pre-wrap", lineHeight: 1.55 }}>{v || <span style={{ color: "var(--subtle)" }}>—</span>}</div>
    </div>
  );
  return (
    <div style={{ background: "var(--surface-3)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: "8px 24px" }}>
      <Row k="Recommender" v={data.recommender} />
      <Row k="Letter type" v={window.LETTER_TYPES.find((t) => t.id === data.letterType)?.label} />
      <Row k="Applying to" v={data.schools} />
      <Row k="Résumé" v={data.resume ? `${data.resume.name} · ${data.resume.pages} pages` : "Not attached"} />
      <Row k="Goal" v={data.goalStatement} />
      <Row k="Why this path" v={data.whyPhd} />
      <Row k="Courses" v={data.courses.map((c) => `· ${c.name} (${c.semester}, ${c.grade}) — ${c.note}`).join("\n")} />
      <Row k="Skills + evidence" v={data.selectedSkills.map((s) => `· ${s}: ${data.skillEvidence[s] || "—"}`).join("\n\n")} />
      <Row k="A moment" v={data.moment} />
      <Row k="A failure" v={data.failure} />
      <Row k="Growth" v={data.growth} />
      <Row k="Where I need to grow" v={data.needsGrowth} />
      <Row k="Extras" v={data.extras} />
    </div>
  );
}

function RubricPrompt({ label, hint, value, onChange, rows = 4 }) {
  return (
    <div>
      <label className="label">{label}</label>
      <div className="help" style={{ marginTop: 0, marginBottom: 8 }}>{hint}</div>
      <textarea className="textarea" rows={rows} value={value} onChange={(e) => onChange(e.target.value)} />
    </div>
  );
}

function StatusTracker({ subs, onNew }) {
  const statusLabel = { new: "Received", drafting: "In progress", sent: "Sent ✓", declined: "Declined" };
  const statusColor = { new: "var(--accent)", drafting: "var(--warn)", sent: "var(--good)", declined: "var(--muted)" };
  return (
    <div className="page-wrap" style={{ maxWidth: 760 }}>
      <div className="eyebrow" style={{ marginBottom: 8 }}>Your requests</div>
      <h1 style={{ fontSize: 32, letterSpacing: "-0.015em", marginBottom: 6 }}>Letters from Prof. Hart</h1>
      <p style={{ color: "var(--ink-3)", fontSize: 14.5, marginBottom: 24 }}>She sees your packet the moment you send it; the status updates here as she works.</p>
      <div className="card" style={{ overflow: "hidden", marginBottom: 20 }}>
        {subs.map((s, i) => (
          <div key={s.id} style={{ display: "grid", gridTemplateColumns: "1fr auto auto", gap: 16, alignItems: "center", padding: "16px 20px", borderBottom: i < subs.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
            <div>
              <div style={{ fontFamily: "var(--serif)", fontSize: 15.5 }}>{s.purpose}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 3 }}>Sent {s.submitted} · deadline {s.deadline}{s.late ? " · arrived inside the window" : ""}</div>
            </div>
            {s.late && s.status === "new" ? <span className="tag-late">awaiting her decision</span> : <span></span>}
            <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--ink-2)" }}>
              <span style={{ width: 7, height: 7, borderRadius: "50%", background: statusColor[s.status] || "var(--muted)" }}></span>
              {statusLabel[s.status] || s.status}
            </span>
          </div>
        ))}
      </div>
      <button className="btn btn-primary" onClick={onNew}>+ New request</button>
    </div>
  );
}

window.StudentWizard = StudentWizard;
})();
