// ─── HOMEWORK TAB — quizzes (Porter/Tate/Criteria), story, scores, manifesto ──

const { useState: useHWState } = React;

function HomeworkTab({ homework, setHomework, onJumpToSchool }) {
  const [view, setView] = useHWState("overview");

  const update = (path, value) => {
    setHomework(h => {
      const next = JSON.parse(JSON.stringify(h || {}));
      let cur = next;
      for (let i = 0; i < path.length - 1; i++) {
        cur[path[i]] = cur[path[i]] || {};
        cur = cur[path[i]];
      }
      cur[path[path.length - 1]] = value;
      return next;
    });
  };

  const VIEWS = [
    { id:"overview", label:"Overview" },
    { id:"porter",   label:"About Porter" },
    { id:"tate",     label:"About Tate" },
    { id:"criteria", label:"Our criteria" },
    { id:"story",    label:"Story prompts" },
    { id:"scores",   label:"School scores" },
    { id:"profile",  label:"Our profile" },
  ];

  return (
    <div>
      <div style={{ background:"var(--forest-deep)", color:"var(--cream)", padding:"36px 20px 32px" }}>
        <Eyebrow tone="cream">Homework · for both of you</Eyebrow>
        <h2 className="serif" style={{
          fontSize: 32, fontWeight: 400, lineHeight: 1.1,
          margin: "10px 0 14px", color: "var(--cream)", letterSpacing: "-0.015em",
        }}>
          The decision is <em style={{ fontStyle:"italic" }}>not the school</em>.<br/>
          It's the <em style={{ fontStyle:"italic" }}>conversation</em> getting there.
        </h2>
        <p style={{
          fontSize: 13.5, lineHeight: 1.7, color:"rgba(245,239,230,0.78)",
          margin: 0, maxWidth: 540,
        }}>
          Each of you takes the quizzes alone first — no peeking. Then you compare.
          The system reweights the schools based on what you both said matters.
        </p>
      </div>

      <div style={{
        display:"flex", gap:0, borderBottom:"1px solid var(--line)",
        overflowX:"auto", scrollbarWidth:"none",
        background:"var(--cream)",
      }}>
        {VIEWS.map(v => {
          const active = view === v.id;
          return (
            <button key={v.id}
              onClick={() => setView(v.id)}
              style={{
                flex:"0 0 auto",
                background:"transparent", border:"none",
                padding:"16px 16px 14px",
                cursor:"pointer",
                fontFamily:"var(--sans)", fontSize:10, fontWeight:500,
                letterSpacing:"0.16em", textTransform:"uppercase",
                color: active ? "var(--forest)" : "var(--ink-3)",
                borderBottom:`1px solid ${active ? "var(--forest)" : "transparent"}`,
                marginBottom:-1, whiteSpace:"nowrap",
              }}>{v.label}</button>
          );
        })}
      </div>

      <div style={{ padding: "28px 20px 60px" }}>
        {view === "overview" && <HWOverview homework={homework} setView={setView} />}
        {view === "porter"   && <KidQuiz kidId="porter" homework={homework} update={update} />}
        {view === "tate"     && <KidQuiz kidId="tate"   homework={homework} update={update} />}
        {view === "criteria" && <CriteriaQuiz homework={homework} update={update} />}
        {view === "story"    && <StoryQuiz homework={homework} update={update} />}
        {view === "scores"   && <ScoresView homework={homework} update={update} onJumpToSchool={onJumpToSchool} />}
        {view === "profile"  && <ProfileView homework={homework} setView={setView} onJumpToSchool={onJumpToSchool} />}
      </div>
    </div>
  );
}

// ─── Overview ────────────────────────────────────────
function HWOverview({ homework, setView }) {
  const h = homework || {};
  const cards = [
    { id:"porter",   eyebrow:"01 · Porter",   title:"About Porter", body:"Six prompts. Jamie, Tom, then Together.", progress: kidProgress(h, "porter") },
    { id:"tate",     eyebrow:"02 · Tate",     title:"About Tate",   body:"Same six prompts, for our second.",      progress: kidProgress(h, "tate") },
    { id:"criteria", eyebrow:"03 · Criteria", title:"Our criteria", body:"Rate ten dimensions 1–10 separately. Weights drive the ranking.", progress: critProgress(h) },
    { id:"story",    eyebrow:"04 · Story",    title:"Story prompts", body:"Five reflective prompts. Voice or type.", progress: storyProgress(h) },
    { id:"scores",   eyebrow:"05 · Scores",   title:"Score schools after each tour", body:"Tom + Jamie rate each school out of 10 on the criteria.", progress: scoresProgress(h) },
    { id:"profile",  eyebrow:"06 · Output",   title:"Our profile",  body:"A weighted ranking + priorities manifesto, written for you.", progress: null },
  ];
  return (
    <div>
      <Eyebrow tone="gold">The six modules</Eyebrow>
      <h3 className="serif" style={{
        fontSize:26, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 22px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Work through these between now and the first round of tours.</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:0 }}>
        {cards.map((c, i) => (
          <button key={c.id}
            onClick={() => setView(c.id)}
            style={{
              background:"transparent", border:"none",
              borderTop: i===0 ? "1px solid var(--line)" : "none",
              borderBottom:"1px solid var(--line)",
              padding:"20px 0", cursor:"pointer", textAlign:"left",
              display:"flex", gap:18, alignItems:"flex-start",
            }}>
            <div className="serif" style={{
              flex:"0 0 36px", fontSize:30, fontWeight:300,
              color:"var(--gold)", lineHeight:1, marginTop:2,
            }}>{String(i+1).padStart(2,"0")}</div>
            <div style={{ flex:1 }}>
              <Eyebrow tone="default" style={{ marginBottom:5 }}>{c.eyebrow.split(" · ")[1]}</Eyebrow>
              <div className="serif" style={{
                fontSize:20, fontWeight:500, color:"var(--forest-deep)",
                letterSpacing:"-0.005em", lineHeight:1.2, marginBottom:5,
              }}>{c.title}</div>
              <p style={{ margin:0, fontSize:13, lineHeight:1.55, color:"var(--ink-2)" }}>{c.body}</p>
              {c.progress && (
                <div style={{
                  marginTop:8, fontFamily:"var(--sans)", fontSize:10, fontWeight:500,
                  letterSpacing:"0.14em", textTransform:"uppercase",
                  color: c.progress.complete ? "var(--moss)" : "var(--gold)",
                }}>{c.progress.label}</div>
              )}
            </div>
            <div style={{ flex:"0 0 auto", paddingTop:8, color:"var(--ink-3)", fontSize:18 }}>›</div>
          </button>
        ))}
      </div>
    </div>
  );
}

function kidProgress(h, kidId) {
  const k = (h.kidQuiz || {})[kidId] || {};
  const j = PORTER_PROMPTS.filter(p => (k.jamie || {})[p.id]?.trim?.()).length;
  const t = PORTER_PROMPTS.filter(p => (k.tom || {})[p.id]?.trim?.()).length;
  const tg = PORTER_PROMPTS.filter(p => (k.together || {})[p.id]?.trim?.()).length;
  if (j===0 && t===0 && tg===0) return { label:"Not started", complete:false };
  const total = PORTER_PROMPTS.length;
  return { label:`J ${j}/${total} · T ${t}/${total} · Together ${tg}/${total}`, complete: j===total && t===total };
}
function critProgress(h) {
  const j = Object.keys((h.criteria||{}).jamie || {}).length;
  const t = Object.keys((h.criteria||{}).tom || {}).length;
  if (j===0 && t===0) return { label:"Not started", complete:false };
  return { label:`J ${j}/${CRITERIA.length} · T ${t}/${CRITERIA.length}`, complete: j===CRITERIA.length && t===CRITERIA.length };
}
function storyProgress(h) {
  const j = STORY_PROMPTS.filter(p => ((h.story||{}).jamie || {})[p.id]?.trim?.()).length;
  const t = STORY_PROMPTS.filter(p => ((h.story||{}).tom || {})[p.id]?.trim?.()).length;
  if (j===0 && t===0) return { label:"Not started", complete:false };
  return { label:`J ${j}/${STORY_PROMPTS.length} · T ${t}/${STORY_PROMPTS.length}`, complete: j===STORY_PROMPTS.length && t===STORY_PROMPTS.length };
}
function scoresProgress(h) {
  const scored = SHORTLIST.filter(s => {
    const sc = (h.scores || {})[s.name] || {};
    return CRITERIA.some(c => sc[c.id]?.jamie != null || sc[c.id]?.tom != null);
  }).length;
  if (scored === 0) return { label:"Not started", complete:false };
  return { label:`${scored}/${SHORTLIST.length} schools`, complete: scored === SHORTLIST.length };
}

// ─── Kid quiz (Porter or Tate) ────────────────────────
function KidQuiz({ kidId, homework, update }) {
  const [pass, setPass] = useHWState("jamie");
  const kid = KIDS.find(k => k.id === kidId) || KIDS[0];
  const passes = [
    { id:"jamie",    label:"Jamie alone", color:"var(--forest)" },
    { id:"tom",      label:"Tom alone",   color:"var(--gold)"   },
    { id:"together", label:"Together",    color:"var(--forest-deep)" },
  ];
  const data = ((homework?.kidQuiz || {})[kidId] || {})[pass] || {};
  const set = (id, v) => update(["kidQuiz", kidId, pass, id], v);

  return (
    <div>
      <Eyebrow tone="gold">About {kid.name}</Eyebrow>
      <h3 className="serif" style={{
        fontSize:26, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 8px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Who is he, really?</h3>
      <p style={{ fontSize:13.5, lineHeight:1.65, color:"var(--ink-2)", margin:"0 0 22px", maxWidth:540 }}>
        Each of you answers alone first. The 'together' pass is the conversation.
      </p>

      <div style={{ display:"flex", gap:6, marginBottom:24, padding:4, background:"var(--cream-warm)", borderRadius:2 }}>
        {passes.map(p => {
          const active = pass === p.id;
          return (
            <button key={p.id} onClick={() => setPass(p.id)} style={{
              flex:1, padding:"10px 8px",
              background: active ? "var(--cream)" : "transparent",
              border:"none", borderRadius:2, cursor:"pointer",
              fontFamily:"var(--sans)", fontSize:11, fontWeight:500,
              letterSpacing:"0.1em", textTransform:"uppercase",
              color: active ? p.color : "var(--ink-3)",
            }}>{p.label}</button>
          );
        })}
      </div>

      <div style={{ display:"flex", flexDirection:"column", gap:22 }}>
        {PORTER_PROMPTS.map((p, i) => (
          <div key={p.id}>
            <div style={{ display:"flex", alignItems:"baseline", gap:10, marginBottom:10 }}>
              <span className="serif" style={{ fontSize:13, fontStyle:"italic", color:"var(--gold)", width:18 }}>{String(i+1).padStart(2,"0")}</span>
              <label className="serif" style={{
                fontSize:17, fontWeight:500, lineHeight:1.3, color:"var(--forest-deep)", flex:1,
              }}>{p.label.replace(/Porter/g, kid.name)}</label>
            </div>
            <div style={{ paddingLeft:28 }}>
              <VoiceField value={data[p.id] || ""} onChange={v => set(p.id, v)} placeholder={p.placeholder} rows={3} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Criteria sliders ─────────────────────────────────
function CriteriaQuiz({ homework, update }) {
  const [who, setWho] = useHWState("jamie");
  const data = (homework?.criteria || {})[who] || {};
  const set = (id, v) => update(["criteria", who, id], v);
  return (
    <div>
      <Eyebrow tone="gold">Our criteria</Eyebrow>
      <h3 className="serif" style={{
        fontSize:26, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 8px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Set the weight, 1–10. Don't average — go honest.</h3>
      <p style={{ fontSize:13.5, lineHeight:1.65, color:"var(--ink-2)", margin:"0 0 22px" }}>
        These weights drive the ranking. Pick separately, then compare.
      </p>

      <ParentToggle who={who} setWho={setWho} />

      {who === "compare" ? (
        <div style={{ marginTop:18 }}>
          <CompareHeader />
          {CRITERIA.map(c => (
            <CompareRow key={c.id} label={c.label}
              jamie={(homework?.criteria?.jamie || {})[c.id]}
              tom={(homework?.criteria?.tom || {})[c.id]} />
          ))}
        </div>
      ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:14, marginTop:18 }}>
          {CRITERIA.map(c => (
            <div key={c.id} style={{ padding:"14px 0", borderBottom:"1px solid var(--line-2)" }}>
              <div className="serif" style={{ fontSize:17, fontWeight:500, color:"var(--forest-deep)", marginBottom:4 }}>{c.label}</div>
              <p style={{ margin:"0 0 10px", fontSize:12, lineHeight:1.5, color:"var(--ink-3)" }}>{c.desc}</p>
              <Slider value={data[c.id]} onChange={v => set(c.id, v)} accent={who==="jamie"?"var(--forest)":"var(--gold)"} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Story prompts ────────────────────────────────────
function StoryQuiz({ homework, update }) {
  const [who, setWho] = useHWState("jamie");
  const data = (homework?.story || {})[who] || {};
  const set = (id, v) => update(["story", who, id], v);
  return (
    <div>
      <Eyebrow tone="gold">Story prompts</Eyebrow>
      <h3 className="serif" style={{
        fontSize:26, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 8px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Reflective, not analytical. Use the mic.</h3>
      <ParentToggle who={who} setWho={setWho} />
      {who === "compare" ? (
        <div style={{ marginTop: 18, display:"flex", flexDirection:"column", gap:18 }}>
          {STORY_PROMPTS.map(p => {
            const j = ((homework?.story || {}).jamie || {})[p.id];
            const t = ((homework?.story || {}).tom || {})[p.id];
            if (!j?.trim() && !t?.trim()) return null;
            return (
              <div key={p.id}>
                <div className="serif" style={{ fontSize:14, fontStyle:"italic", color:"var(--forest-mid)", marginBottom:8 }}>{p.label}</div>
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
                  <CompareCell label="Jamie" color="var(--forest)" text={j} />
                  <CompareCell label="Tom"   color="var(--gold)"   text={t} />
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div style={{ display:"flex", flexDirection:"column", gap:18, marginTop:18 }}>
          {STORY_PROMPTS.map(p => (
            <div key={p.id}>
              <label className="serif" style={{
                display:"block", marginBottom:8, fontSize:16, fontWeight:500, color:"var(--forest-deep)",
              }}>{p.label}</label>
              <VoiceField value={data[p.id] || ""} onChange={v => set(p.id, v)} placeholder={p.placeholder} rows={4} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── School scores ────────────────────────────────────
function ScoresView({ homework, update, onJumpToSchool }) {
  const [school, setSchool] = useHWState(SHORTLIST[0].name);
  const sc = ((homework?.scores || {})[school]) || {};
  const setScore = (critId, who, v) => update(["scores", school, critId, who], v);
  const setNote = (who, v) => update(["scores", school, "_notes", who], v);

  return (
    <div>
      <Eyebrow tone="gold">School scores</Eyebrow>
      <h3 className="serif" style={{
        fontSize:26, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 8px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Score after each tour. Out of ten. Both of you.</h3>
      <p style={{ fontSize:13.5, lineHeight:1.65, color:"var(--ink-2)", margin:"0 0 22px" }}>
        Walk out of the tour, sit in the car, score before you talk. Then talk.
      </p>

      {/* School picker */}
      <div style={{ display:"flex", gap:6, flexWrap:"wrap", marginBottom:24 }}>
        {SHORTLIST.map(s => {
          const active = school === s.name;
          return (
            <button key={s.name} onClick={() => setSchool(s.name)} style={{
              padding:"7px 12px",
              background: active ? "var(--forest)" : "transparent",
              border: `1px solid ${active ? "var(--forest)" : "var(--line)"}`,
              color: active ? "var(--cream)" : "var(--ink-2)",
              borderRadius:999, cursor:"pointer",
              fontFamily:"var(--sans)", fontSize:11, fontWeight:500,
            }}>{s.name.split(" ")[0]}</button>
          );
        })}
      </div>

      {/* Per-criterion scoring */}
      <div style={{ display:"flex", flexDirection:"column", gap:0 }}>
        {CRITERIA.map(c => (
          <div key={c.id} style={{ padding:"16px 0", borderBottom:"1px solid var(--line-2)" }}>
            <div className="serif" style={{ fontSize:16, fontWeight:500, color:"var(--forest-deep)", marginBottom:10 }}>{c.label}</div>
            <div style={{ display:"flex", gap:10, alignItems:"center", marginBottom:10 }}>
              <span style={{ width:50, fontFamily:"var(--sans)", fontSize:9, fontWeight:500, letterSpacing:"0.16em", textTransform:"uppercase", color:"var(--forest)" }}>Jamie</span>
              <ScorePicker value={(sc[c.id]||{}).jamie} onChange={v => setScore(c.id, "jamie", v)} accent="var(--forest)" />
            </div>
            <div style={{ display:"flex", gap:10, alignItems:"center" }}>
              <span style={{ width:50, fontFamily:"var(--sans)", fontSize:9, fontWeight:500, letterSpacing:"0.16em", textTransform:"uppercase", color:"var(--gold)" }}>Tom</span>
              <ScorePicker value={(sc[c.id]||{}).tom} onChange={v => setScore(c.id, "tom", v)} accent="var(--gold)" />
            </div>
          </div>
        ))}
      </div>

      {/* Tour notes */}
      <SectionRule label="Notes from the day" />
      <div style={{ display:"flex", flexDirection:"column", gap:14 }}>
        <div>
          <Eyebrow tone="default" style={{ color:"var(--forest)", marginBottom:6 }}>Jamie's notes</Eyebrow>
          <VoiceField value={(sc._notes||{}).jamie || ""} onChange={v => setNote("jamie", v)} placeholder="What stood out. Use the mic." rows={3} />
        </div>
        <div>
          <Eyebrow tone="default" style={{ color:"var(--gold)", marginBottom:6 }}>Tom's notes</Eyebrow>
          <VoiceField value={(sc._notes||{}).tom || ""} onChange={v => setNote("tom", v)} placeholder="What stood out. Use the mic." rows={3} />
        </div>
      </div>
    </div>
  );
}

// ─── Profile output: weighted ranking + manifesto ─────
function ProfileView({ homework, setView, onJumpToSchool }) {
  const ranked = computeRanking(homework);
  const haveScores = ranked.length > 0 && ranked[0].score > 0;
  const j = (homework?.criteria || {}).jamie || {};
  const t = (homework?.criteria || {}).tom || {};
  const topCriteria = CRITERIA
    .map(c => ({ ...c, weight: ((j[c.id]||0) + (t[c.id]||0)) / 2 }))
    .filter(c => c.weight > 0)
    .sort((a,b) => b.weight - a.weight)
    .slice(0, 5);

  return (
    <div>
      <Eyebrow tone="gold">Our profile</Eyebrow>
      <h3 className="serif" style={{
        fontSize:28, fontWeight:400, lineHeight:1.15,
        margin:"10px 0 8px", color:"var(--forest-deep)", letterSpacing:"-0.01em",
      }}>Here's what you said matters — and how the schools rank for it.</h3>
      <p style={{ fontSize:13.5, lineHeight:1.65, color:"var(--ink-2)", margin:"0 0 28px" }}>
        Updates live as you score schools. Honest in, honest out.
      </p>

      {/* Top criteria */}
      {topCriteria.length > 0 ? (
        <div style={{ marginBottom:32 }}>
          <Eyebrow tone="default">What you both weight highest</Eyebrow>
          <div style={{ display:"flex", flexDirection:"column", gap:10, marginTop:12 }}>
            {topCriteria.map((c, i) => (
              <div key={c.id} style={{
                display:"grid", gridTemplateColumns:"24px 1fr 60px", alignItems:"center", gap:14,
                paddingBottom:10, borderBottom:"1px solid var(--line-2)",
              }}>
                <span className="serif" style={{ fontSize:18, fontStyle:"italic", color:"var(--gold)" }}>0{i+1}</span>
                <span className="serif" style={{ fontSize:17, color:"var(--forest-deep)" }}>{c.label}</span>
                <span style={{ textAlign:"right", fontFamily:"var(--sans)", fontSize:11, color:"var(--ink-2)" }}>weight {c.weight.toFixed(1)}</span>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <CalloutEmpty msg="Complete the criteria quiz to see your weighted profile." cta="Go to criteria" onClick={() => setView("criteria")} />
      )}

      {/* Ranking */}
      <Eyebrow tone="default">Weighted school ranking</Eyebrow>
      {haveScores ? (
        <div style={{ display:"flex", flexDirection:"column", gap:0, marginTop:14 }}>
          {ranked.map((r, i) => (
            <button key={r.name} onClick={() => onJumpToSchool && onJumpToSchool(r.name)} style={{
              background:"transparent", border:"none",
              borderTop: i===0 ? "1px solid var(--line)" : "none",
              borderBottom: "1px solid var(--line-2)",
              padding:"16px 0", textAlign:"left", cursor:"pointer",
              display:"grid", gridTemplateColumns:"40px 1fr 80px", gap:14, alignItems:"center",
            }}>
              <span className="serif" style={{ fontSize: 30, fontWeight:300, color:"var(--gold)" }}>{String(i+1).padStart(2,"0")}</span>
              <div>
                <div className="serif" style={{ fontSize:18, fontWeight:500, color:"var(--forest-deep)" }}>{r.name}</div>
                <div style={{ fontSize:11.5, color:"var(--ink-3)", marginTop:3 }}>
                  {r.scoredCount}/{CRITERIA.length} criteria scored
                </div>
              </div>
              <div style={{ textAlign:"right" }}>
                <div className="serif" style={{ fontSize:24, color:"var(--forest)" }}>{r.score.toFixed(1)}</div>
                <div style={{ fontFamily:"var(--sans)", fontSize:9, fontWeight:500, letterSpacing:"0.14em", textTransform:"uppercase", color:"var(--ink-3)" }}>weighted</div>
              </div>
            </button>
          ))}
        </div>
      ) : (
        <CalloutEmpty msg="Score at least one school to see the ranking." cta="Go to scores" onClick={() => setView("scores")} />
      )}

      {/* Manifesto */}
      <SectionRule label="Priorities manifesto" />
      <Manifesto homework={homework} topCriteria={topCriteria} />
    </div>
  );
}

function computeRanking(h) {
  if (!h) return [];
  const j = (h.criteria||{}).jamie || {};
  const t = (h.criteria||{}).tom || {};
  return SHORTLIST.map(s => {
    const sc = (h.scores||{})[s.name] || {};
    let total = 0, totalW = 0, scoredCount = 0;
    CRITERIA.forEach(c => {
      const sj = sc[c.id]?.jamie, st = sc[c.id]?.tom;
      const wj = j[c.id], wt = t[c.id];
      if (sj == null && st == null) return;
      scoredCount++;
      const avgScore = (sj!=null && st!=null) ? (sj+st)/2 : (sj!=null ? sj : st);
      const avgWeight = (wj!=null && wt!=null) ? (wj+wt)/2 : (wj!=null ? wj : (wt!=null ? wt : 5));
      total += avgScore * avgWeight;
      totalW += avgWeight;
    });
    const score = totalW > 0 ? total / totalW : 0;
    return { name: s.name, score, scoredCount };
  }).filter(r => r.scoredCount > 0).sort((a,b) => b.score - a.score);
}

function Manifesto({ homework, topCriteria }) {
  const lines = [];
  if (topCriteria.length >= 1) lines.push(`What we want most: ${topCriteria.slice(0,3).map(c => c.label.toLowerCase()).join(", ")}.`);
  const stories = STORY_PROMPTS.map(p => {
    const j = ((homework?.story||{}).jamie || {})[p.id];
    const t = ((homework?.story||{}).tom || {})[p.id];
    return { label:p.label, j, t };
  }).filter(s => s.j?.trim() || s.t?.trim());
  if (!lines.length && !stories.length) {
    return <p style={{ fontSize:13, color:"var(--ink-3)", fontStyle:"italic" }}>Your manifesto appears once you've answered the criteria and story prompts.</p>;
  }
  return (
    <div style={{
      background:"var(--cream-warm)", padding:"24px 22px",
      margin:"4px -8px 0",
      borderLeft:"2px solid var(--gold)",
    }}>
      {lines.map((l, i) => (
        <p key={i} className="serif" style={{
          margin: i===0 ? "0 0 14px" : "0 0 14px",
          fontSize:18, lineHeight:1.45, color:"var(--forest-deep)", fontStyle:"italic",
        }}>{l}</p>
      ))}
      {stories.length > 0 && (
        <div style={{ display:"flex", flexDirection:"column", gap:14, marginTop:8 }}>
          {stories.slice(0,3).map((s, i) => (
            <div key={i}>
              <div style={{ fontFamily:"var(--sans)", fontSize:9, fontWeight:500, letterSpacing:"0.14em", textTransform:"uppercase", color:"var(--ink-3)", marginBottom:5 }}>{s.label}</div>
              {s.j?.trim() && <p style={{ margin:"0 0 6px", fontSize:13, lineHeight:1.55, color:"var(--ink-2)" }}><em style={{ color:"var(--forest)" }}>Jamie —</em> {s.j}</p>}
              {s.t?.trim() && <p style={{ margin:0, fontSize:13, lineHeight:1.55, color:"var(--ink-2)" }}><em style={{ color:"var(--gold)" }}>Tom —</em> {s.t}</p>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function CalloutEmpty({ msg, cta, onClick }) {
  return (
    <div style={{
      background:"var(--cream-soft)", border:"1px dashed var(--line)", borderRadius:2,
      padding:"22px 18px", textAlign:"center", margin:"12px 0 28px",
    }}>
      <p style={{ margin:"0 0 10px", fontSize:13.5, color:"var(--ink-2)" }}>{msg}</p>
      {cta && <button onClick={onClick} style={{
        background:"transparent", border:"none", padding:0, cursor:"pointer",
        fontFamily:"var(--sans)", fontSize:11, fontWeight:500, letterSpacing:"0.16em", textTransform:"uppercase",
        color:"var(--forest)",
      }}>{cta} →</button>}
    </div>
  );
}

function ParentToggle({ who, setWho }) {
  const opts = [
    { id:"jamie", label:"Jamie", color:"var(--forest)" },
    { id:"tom",   label:"Tom",   color:"var(--gold)" },
    { id:"compare", label:"Compare", color:"var(--forest-deep)" },
  ];
  return (
    <div style={{ display:"flex", gap:6, padding:4, background:"var(--cream-warm)", borderRadius:2 }}>
      {opts.map(o => {
        const active = who === o.id;
        return (
          <button key={o.id} onClick={() => setWho(o.id)} style={{
            flex:1, padding:"10px 8px",
            background: active ? "var(--cream)" : "transparent",
            border:"none", borderRadius:2, cursor:"pointer",
            fontFamily:"var(--sans)", fontSize:11, fontWeight:500,
            letterSpacing:"0.1em", textTransform:"uppercase",
            color: active ? o.color : "var(--ink-3)",
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

window.HomeworkTab = HomeworkTab;
