// ============================================
// Coach / Instructor Portal
// ============================================

function CoachPortal({ subroute, setSubroute, toast }) {
  if (subroute === "classes") return <CoachClasses setSubroute={setSubroute}/>;
  if (subroute === "roster") return <CoachRoster setSubroute={setSubroute}/>;
  if (subroute === "assess") return <AssessmentTool setSubroute={setSubroute} toast={toast}/>;
  if (subroute === "workouts") return <CoachWorkouts setSubroute={setSubroute} toast={toast}/>;
  if (subroute === "messages") return <CoachMessages/>;
  if (subroute === "availability") return <CoachAvailability/>;
  if (subroute === "student") return <StudentProfileView setSubroute={setSubroute}/>;
  if (subroute === "live") return <LiveMeetPage setSubroute={setSubroute}/>;
  return <CoachHome setSubroute={setSubroute}/>;
}

function CoachHome({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Good morning, Coach Maria" sub="3 classes today · 28 students to track"/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
        <StatCard label="Classes today" value="3" sub="Next: 11:00 Stingrays" accent="var(--teal)" icon="calendar"/>
        <StatCard label="Students to assess" value="4" sub="Ready for level-up" accent="var(--mint)" icon="ladder"/>
        <StatCard label="Avg attendance" value="92%" sub="+3% week-on-week" trend="up" accent="var(--aqua)" icon="check"/>
        <StatCard label="Unread messages" value="6" sub="From 4 parents" accent="var(--c-recreation)" icon="msg"/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="between" style={{ marginBottom: 14 }}>
            <div className="t-h2">Today's classes</div>
            <button onClick={() => setSubroute("classes")} className="btn btn-ghost btn-sm">All classes<Icon name="chev-right" size={14}/></button>
          </div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { time: "07:00–07:45", name: "Adult Masters", lane: "Lanes 1–2", roster: 12, status: "Done", color: "var(--c-competitive)" },
              { time: "11:00–11:45", name: "Stingrays L3", lane: "Lanes 3–4", roster: 7, status: "Up next", color: "var(--aqua)" },
              { time: "16:30–17:30", name: "Sharks Pre-Comp", lane: "Lanes 1–3", roster: 6, status: "Later", color: "var(--c-competitive)" },
            ].map((c, i) => (
              <button key={i} onClick={() => setSubroute("classes")} className="row" style={{ padding: 14, background: c.status === "Up next" ? "var(--aqua-50)" : "var(--gray-50)", borderRadius: 10, gap: 12, width: "100%", textAlign: "left", borderLeft: `4px solid ${c.color}` }}>
                <div className="t-mono-sm" style={{ fontWeight: 700, minWidth: 90 }}>{c.time}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600 }}>{c.name}</div>
                  <div className="t-caption">{c.lane} · {c.roster} students</div>
                </div>
                <Pill tone={c.status === "Done" ? "mint" : c.status === "Up next" ? "aqua" : "default"}>{c.status}</Pill>
                <Icon name="chev-right" size={16} color="var(--gray-400)"/>
              </button>
            ))}
          </div>
        </Card>

        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Student alerts</div>
          <div className="col" style={{ gap: 10 }}>
            {[
              { name: "Mia Tanaka", body: "Ready for Level 4 assessment", tone: "mint", icon: "star" },
              { name: "Liam Ortiz", body: "Missed 3 classes — follow up", tone: "amber", icon: "alert" },
              { name: "Sophie Chen", body: "Completed all Level 7 skills", tone: "mint", icon: "trophy" },
              { name: "Noah Patel", body: "Parent requested progress note", tone: "default", icon: "msg" },
            ].map((a, i) => (
              <div key={i} className="row" style={{ gap: 10, padding: 10, borderRadius: 10, background: "var(--gray-50)", alignItems: "flex-start" }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: a.tone === "mint" ? "var(--mint-50)" : a.tone === "amber" ? "var(--amber-50)" : "white", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  <Icon name={a.icon} size={14} color={a.tone === "mint" ? "var(--mint)" : a.tone === "amber" ? "var(--amber)" : "var(--gray-600)"}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13 }}>{a.name}</div>
                  <div style={{ fontSize: 12, color: "var(--gray-600)" }}>{a.body}</div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function CoachClasses({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="My classes" sub="Tap a class to take attendance, view roster or assess"/>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
        {[
          { name: "Stingrays L3", time: "Mon · Wed · Fri 11:00", roster: 7, cap: 10, color: "var(--aqua)" },
          { name: "Sharks Pre-Comp", time: "Daily 16:30", roster: 6, cap: 8, color: "var(--c-competitive)" },
          { name: "Adult Masters", time: "Mon · Wed · Fri 07:00", roster: 12, cap: 16, color: "var(--c-competitive)" },
        ].map((c, i) => (
          <Card key={i} style={{ borderLeft: `4px solid ${c.color}` }}>
            <div className="t-h2">{c.name}</div>
            <div className="muted" style={{ marginTop: 4 }}>{c.time}</div>
            <div className="row" style={{ marginTop: 14, gap: 10 }}>
              <div style={{ flex: 1 }}>
                <div className="t-caption">Enrolled</div>
                <div className="t-mono-stat" style={{ fontSize: 22 }}>{c.roster}/{c.cap}</div>
              </div>
              <ProgressRing pct={(c.roster / c.cap) * 100} size={56} color={c.color}/>
            </div>
            <div className="row" style={{ marginTop: 14, gap: 6 }}>
              <Button variant="primary" size="sm" icon="check">Attendance</Button>
              <Button variant="secondary" size="sm">Roster</Button>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function CoachRoster({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="My students" sub="28 students across 3 classes"
        actions={<LiveMeetTicker onClick={() => setSubroute("live")}/>}/>
      <Card>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead>
            <tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}>
              <th style={{ padding: 10 }}>Student</th><th>Level</th><th>Attendance</th><th>Highest standard</th><th>Status</th><th/>
            </tr>
          </thead>
          <tbody>
            {STUDENTS.map((s, i) => {
              const tiers = ["B", "BB", "A", "AA", "AAA", "AAAA"];
              const tier = tiers[Math.min(5, Math.floor(s.level / 1.5))] || null;
              return (
                <tr key={s.id} onClick={() => setSubroute("student")} style={{ borderTop: "1px solid var(--gray-100)", cursor: "pointer" }}>
                  <td style={{ padding: 12 }}>
                    <div className="row"><Avatar name={s.name} color={s.color} size="sm"/><div><div style={{ fontWeight: 600 }}>{s.name}</div><div className="t-caption">Age {s.age}</div></div></div>
                  </td>
                  <td><Pill tone="aqua">L{s.level}</Pill></td>
                  <td><div className="row"><div style={{ width: 60 }}><ProgressBar pct={s.attendance}/></div><span className="t-mono-sm" style={{ fontWeight: 600 }}>{s.attendance}%</span></div></td>
                  <td>{s.age >= 9 ? <StandardBadge tier={tier} size="sm"/> : <Pill>Not yet competing</Pill>}</td>
                  <td>{s.attendance >= 90 ? <Pill tone="mint">On track</Pill> : <Pill tone="amber">Watch</Pill>}</td>
                  <td><Icon name="chev-right" size={16} color="var(--gray-400)"/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function CoachWorkouts({ setSubroute, toast }) {
  const [items, setItems] = useState([
    { id: 1, name: "Warm-up · 400m easy", dist: "400m" },
    { id: 2, name: "8 × 100m Free on 1:45", dist: "800m" },
    { id: 3, name: "4 × 50m kick", dist: "200m" },
  ]);
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Workout plans" sub="Build and assign workouts to your students"
        actions={<Button variant="primary" icon="plus">New plan</Button>}/>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div className="t-h2">Build a workout</div>
          <Pill>Draft</Pill>
        </div>
        <div className="col" style={{ gap: 12 }}>
          <div className="field"><label>Plan name</label><input className="input" defaultValue="Stingrays Wed — Endurance"/></div>
          <div className="row" style={{ gap: 12 }}>
            <div className="field" style={{ flex: 1 }}><label>Assign to</label><select className="select"><option>Stingrays L3 (whole class)</option><option>Mia Tanaka only</option><option>Sharks Pre-Comp</option></select></div>
            <div className="field" style={{ flex: 1 }}><label>Due date</label><input className="input" type="date" defaultValue="2026-05-15"/></div>
          </div>
        </div>

        <div style={{ marginTop: 18 }}>
          <div className="t-caption" style={{ marginBottom: 8 }}>Sets · {items.reduce((a, b) => a + parseInt(b.dist), 0)}m total</div>
          <div className="col" style={{ gap: 6 }}>
            {items.map((s, i) => (
              <div key={s.id} className="row" style={{ padding: 12, background: "var(--gray-50)", borderRadius: 10 }}>
                <Icon name="menu" size={16} color="var(--gray-400)"/>
                <div style={{ flex: 1 }}><div style={{ fontWeight: 600 }}>{s.name}</div></div>
                <Pill>{s.dist}</Pill>
                <button className="btn-icon" onClick={() => setItems(items.filter(x => x.id !== s.id))}><Icon name="trash" size={14}/></button>
              </div>
            ))}
            <Button variant="ghost" full icon="plus" onClick={() => setItems([...items, { id: Date.now(), name: "New set", dist: "200m" }])}>Add set</Button>
          </div>
        </div>

        <div className="row" style={{ marginTop: 18, justifyContent: "flex-end", gap: 8 }}>
          <Button variant="ghost">Save draft</Button>
          <Button variant="primary" onClick={() => toast({ message: "Plan assigned · 7 students notified" })}>Assign plan</Button>
        </div>
      </Card>
    </div>
  );
}

function CoachMessages() {
  const threads = [
    { name: "Sofia Ortiz", body: "Liam will miss Friday — family trip", time: "2m", unread: 2, avatar: "SO", color: "#7C3AED" },
    { name: "James Chen", body: "Thank you for the great session today!", time: "1h", unread: 0, avatar: "JC", color: "#00C9A7" },
    { name: "Admin · Sarah", body: "Can you cover the 2 PM class?", time: "3h", unread: 1, avatar: "S", color: "#0099CC" },
    { name: "Hiroshi Tanaka", body: "Mia is so excited for her assessment!", time: "1d", unread: 0, avatar: "HT", color: "#F97316" },
  ];
  const [active, setActive] = useState(0);
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Messages"/>
      <Card style={{ padding: 0, height: "70vh", overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "280px 1fr", height: "100%" }}>
          <div style={{ borderRight: "1px solid var(--gray-200)", overflowY: "auto" }}>
            {threads.map((t, i) => (
              <button key={i} onClick={() => setActive(i)} className="row" style={{ padding: 14, gap: 12, width: "100%", textAlign: "left", background: active === i ? "var(--aqua-50)" : "transparent", borderBottom: "1px solid var(--gray-100)" }}>
                <Avatar name={t.name} color={t.color}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="between"><span style={{ fontWeight: 600, fontSize: 13 }}>{t.name}</span><span className="t-caption">{t.time}</span></div>
                  <div style={{ fontSize: 12, color: "var(--gray-600)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.body}</div>
                </div>
                {t.unread > 0 && <div style={{ width: 18, height: 18, borderRadius: "50%", background: "var(--aqua)", color: "white", fontSize: 10, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{t.unread}</div>}
              </button>
            ))}
          </div>
          <div className="col" style={{ height: "100%" }}>
            <div className="row between" style={{ padding: 14, borderBottom: "1px solid var(--gray-200)" }}>
              <div className="row"><Avatar name={threads[active].name} color={threads[active].color}/><div><div style={{ fontWeight: 600 }}>{threads[active].name}</div><div className="t-caption">Online</div></div></div>
            </div>
            <div style={{ flex: 1, padding: 16, background: "var(--gray-50)", overflowY: "auto" }}>
              <div className="col" style={{ gap: 8 }}>
                <div style={{ alignSelf: "flex-start", background: "white", padding: "10px 14px", borderRadius: 16, maxWidth: "70%", fontSize: 14 }}>Hi Coach! Quick note — {threads[active].body}</div>
                <div style={{ alignSelf: "flex-end", background: "var(--navy)", color: "white", padding: "10px 14px", borderRadius: 16, maxWidth: "70%", fontSize: 14 }}>Thanks for letting me know — I'll plan accordingly.</div>
                <div style={{ alignSelf: "flex-start", background: "white", padding: "10px 14px", borderRadius: 16, maxWidth: "70%", fontSize: 14 }}>Appreciate it 🙏</div>
              </div>
            </div>
            <div className="row" style={{ padding: 12, borderTop: "1px solid var(--gray-200)", gap: 8 }}>
              <input className="input" placeholder="Type a message…" style={{ flex: 1 }}/>
              <Button variant="primary" icon="msg">Send</Button>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

function CoachAvailability() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Availability" sub="Set when you can teach, request time off"
        actions={<Button variant="primary" icon="plus">Request time off</Button>}/>
      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>This week</div>
        <div style={{ display: "grid", gridTemplateColumns: "60px repeat(7, 1fr)", gap: 4 }}>
          <div/>
          {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => <div key={d} style={{ textAlign: "center", fontSize: 11, fontWeight: 700, color: "var(--gray-600)" }}>{d}</div>)}
          {Array.from({ length: 12 }).map((_, h) => (
            <React.Fragment key={h}>
              <div style={{ fontSize: 11, color: "var(--gray-500)", padding: 4, textAlign: "right" }}>{6 + h}:00</div>
              {[0,1,2,3,4,5,6].map(d => {
                const r = Math.random();
                const state = r > 0.7 ? "class" : r > 0.4 ? "avail" : "off";
                return <div key={d} style={{ height: 26, background: state === "class" ? "var(--aqua)" : state === "avail" ? "var(--mint-50)" : "var(--gray-100)", borderRadius: 4 }}/>;
              })}
            </React.Fragment>
          ))}
        </div>
        <div className="row" style={{ marginTop: 12, gap: 14, fontSize: 12 }}>
          <div className="row"><div style={{ width: 14, height: 14, background: "var(--aqua)", borderRadius: 3 }}/><span>Class scheduled</span></div>
          <div className="row"><div style={{ width: 14, height: 14, background: "var(--mint-50)", borderRadius: 3 }}/><span>Available</span></div>
          <div className="row"><div style={{ width: 14, height: 14, background: "var(--gray-100)", borderRadius: 3 }}/><span>Off</span></div>
        </div>
      </Card>
    </div>
  );
}

// ============================================
// Student Portal
// ============================================
function StudentPortal({ subroute, setSubroute, toast }) {
  if (subroute === "classes") return <StudentClasses/>;
  if (subroute === "progress") return <StudentProgress/>;
  if (subroute === "workouts") return <StudentWorkouts/>;
  if (subroute === "achievements") return <StudentAchievements/>;
  return <StudentHome setSubroute={setSubroute}/>;
}

function StudentHome({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <Card style={{ background: "linear-gradient(135deg, var(--aqua), var(--c-openwater))", color: "white", padding: 28, position: "relative", overflow: "hidden" }}>
        <Icon name="star" size={220} color="rgba(255,255,255,0.1)" style={{ position: "absolute", top: -40, right: -40 }}/>
        <div style={{ position: "relative" }}>
          <div style={{ fontSize: 14, color: "rgba(255,255,255,0.85)" }}>Hi Mia! 👋</div>
          <div className="t-h1" style={{ color: "white", marginTop: 4 }}>You're so close to Level 4!</div>
          <div className="row" style={{ marginTop: 16, gap: 14, flexWrap: "wrap" }}>
            <ProgressRing pct={60} size={84} stroke={8} color="white" label="60%"/>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ color: "rgba(255,255,255,0.85)", fontSize: 13 }}>4 of 8 Level 3 skills mastered</div>
              <Button variant="mint" style={{ marginTop: 12 }} onClick={() => setSubroute("progress")}>See progress<Icon name="chev-right" size={14}/></Button>
            </div>
          </div>
        </div>
      </Card>

      <Card style={{ borderLeft: "4px solid var(--aqua)" }}>
        <div className="row between">
          <div>
            <div className="t-caption">Next class</div>
            <div className="t-h2">Stingrays L3 with Coach Maria</div>
            <div className="muted">Today · 11:00 · Lanes 3–4</div>
          </div>
          <div style={{ textAlign: "center" }}>
            <div className="t-mono-stat" style={{ color: "var(--aqua)" }}>2:18</div>
            <div className="t-caption">until class</div>
          </div>
        </div>
        <Button variant="secondary" size="sm" style={{ marginTop: 12 }} icon="calendar">Add to calendar</Button>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Recent badges 🏆</div>
          <div className="row" style={{ gap: 12 }}>
            {[
              { name: "First Length", color: "var(--mint)", icon: "wave" },
              { name: "10 Sessions", color: "var(--c-recreation)", icon: "flame" },
            ].map((b, i) => (
              <div key={i} style={{ background: "var(--navy)", color: "white", borderRadius: 12, padding: 16, textAlign: "center", flex: 1 }}>
                <Icon name={b.icon} size={36} color={b.color}/>
                <div style={{ fontSize: 12, fontWeight: 600, marginTop: 6 }}>{b.name}</div>
              </div>
            ))}
          </div>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>From Coach Maria</div>
          <div style={{ background: "var(--aqua-50)", padding: 14, borderRadius: 10, borderLeft: "3px solid var(--aqua)" }}>
            <div style={{ fontSize: 13, lineHeight: 1.5 }}>"Backstroke arm recovery much cleaner today, Mia! Ready to attempt independent length next session 💪"</div>
            <div className="t-caption" style={{ marginTop: 8 }}>May 12, 2026</div>
          </div>
        </Card>
      </div>
    </div>
  );
}

function StudentClasses() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="My classes" sub="Schedule and attendance"/>
      <div className="col" style={{ gap: 10 }}>
        {[
          { day: "Mon", date: "May 13", name: "Stingrays L3", time: "11:00", state: "done" },
          { day: "Wed", date: "May 15", name: "Stingrays L3", time: "11:00", state: "next" },
          { day: "Fri", date: "May 17", name: "Stingrays L3", time: "11:00", state: "upcoming" },
          { day: "Mon", date: "May 20", name: "Stingrays L3", time: "11:00", state: "upcoming" },
        ].map((c, i) => (
          <Card key={i} style={{ borderLeft: `4px solid ${c.state === "done" ? "var(--mint)" : c.state === "next" ? "var(--aqua)" : "var(--gray-300)"}` }}>
            <div className="row" style={{ gap: 16, flexWrap: "wrap" }}>
              <div style={{ textAlign: "center", width: 60 }}>
                <div className="t-caption">{c.day}</div>
                <div className="t-h2">{c.date.split(" ")[1]}</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700 }}>{c.name}</div>
                <div className="muted">{c.time} · Coach Maria · Lanes 3–4</div>
              </div>
              {c.state === "done" && <Pill tone="mint" icon="check">Attended</Pill>}
              {c.state === "next" && <Pill tone="aqua">Next class</Pill>}
              {c.state === "upcoming" && <Pill>Upcoming</Pill>}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function StudentProgress() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="My progress"/>
      <Card>
        <div className="t-h2" style={{ marginBottom: 16 }}>Progress map</div>
        <SwimmerProgressMap level={3} progress={0.6}/>
      </Card>
    </div>
  );
}

function StudentWorkouts() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="My workouts" sub="Assigned by Coach Maria"/>
      <div className="col" style={{ gap: 10 }}>
        {[
          { name: "Backstroke drills", coach: "Maria", time: "20 min", done: false },
          { name: "Floating practice", coach: "Maria", time: "15 min", done: true },
        ].map((w, i) => (
          <Card key={i}>
            <div className="row between">
              <div className="row">
                <div style={{ width: 40, height: 40, borderRadius: 10, background: w.done ? "var(--mint)" : "var(--aqua)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name={w.done ? "check" : "play"} size={18} color="white"/>
                </div>
                <div><div style={{ fontWeight: 600 }}>{w.name}</div><div className="t-caption">From Coach {w.coach} · {w.time}</div></div>
              </div>
              {w.done ? <Pill tone="mint">Done</Pill> : <Button variant="primary" size="sm">Start</Button>}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function StudentAchievements() { return <RecAchievements/>; }

// ============================================
// Parent Portal
// ============================================
function ParentPortal({ subroute, setSubroute, toast }) {
  if (subroute === "schedule") return <ParentSchedule/>;
  if (subroute === "progress") return <ParentProgress setSubroute={setSubroute} toast={toast}/>;
  if (subroute === "billing") return <ParentBilling toast={toast}/>;
  if (subroute === "messages") return <ParentMessages/>;
  if (subroute === "live") return <LiveMeetPage setSubroute={setSubroute} highlight="Sophie Chen"/>;
  return <ParentHome setSubroute={setSubroute} toast={toast}/>;
}

function ParentHome({ setSubroute, toast }) {
  const [childId, setChildId] = useState("sophie");
  const [view, setView] = useState("family");
  const [transitionFor, setTransitionFor] = useState(null);
  const [addOpen, setAddOpen] = useState(false);
  const [manageFor, setManageFor] = useState(null);
  const child = CHILDREN.find(c => c.id === childId) || CHILDREN[0];

  // Listen for jumps from family cards
  useEffect(() => {
    const h = (e) => { if (e.detail?.route) setSubroute(e.detail.route); };
    window.addEventListener("parent-go", h);
    return () => window.removeEventListener("parent-go", h);
  }, [setSubroute]);

  return (
    <div className="col" style={{ gap: 16 }}>
      {transitionFor && <TransitionFlow child={transitionFor} onClose={() => setTransitionFor(null)} onComplete={() => setTransitionFor(null)} toast={toast}/>}
      {addOpen && <AddChildFlow onClose={() => setAddOpen(false)} onComplete={() => setAddOpen(false)} toast={toast}/>}
      {manageFor && <FamilyManager initialChildId={manageFor === "all" ? null : manageFor} onClose={() => setManageFor(null)} onTransition={() => { const c = CHILDREN.find(x => x.readyToTransition); setManageFor(null); setTransitionFor(c); }} toast={toast}/>}

      {/* View toggle */}
      <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
        <Tabs tabs={[{ id: "family", label: `Family (${CHILDREN.length})` }, { id: "single", label: child.name.split(" ")[0] }]} value={view} onChange={setView}/>
        <div className="row" style={{ gap: 8 }}>
          {view === "family" && <Button variant="secondary" icon="plus" onClick={() => setAddOpen(true)}>Add swimmer</Button>}
          <Button variant="ghost" icon="settings" onClick={() => setManageFor("all")}>Manage</Button>
        </div>
      </div>

      {view === "family" ? (
        <FamilyOverview
          onPickChild={(id) => { setChildId(id); setView("single"); }}
          onManage={(id) => setManageFor(id || "all")}
          onLive={() => setSubroute("live")}
          onAddChild={() => setAddOpen(true)}
        />
      ) : (
        <SingleChildHome child={child} setSubroute={setSubroute} onTransition={() => setTransitionFor(child)} onManage={() => setManageFor(child.id)}/>
      )}
    </div>
  );
}

function SingleChildHome({ child, setSubroute, onTransition, onManage }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      {/* Active child header */}
      <Card>
        <div className="row" style={{ gap: 16, flexWrap: "wrap" }}>
          <Avatar name={child.name} color={child.color} size="lg"/>
          <div style={{ flex: 1 }}>
            <div className="row" style={{ gap: 8, alignItems: "center" }}>
              <div className="t-h1">{child.name}</div>
              <ChildAgeBadge child={child}/>
            </div>
            <div className="muted">{child.program} · {child.club} · {child.coach}</div>
          </div>
          <Button variant="secondary" icon="settings" onClick={onManage}>Settings</Button>
        </div>
      </Card>

      {/* Age-13 transition banner */}
      {child.readyToTransition && (
        <Card style={{ background: "linear-gradient(135deg, var(--amber-50), white)", borderLeft: "4px solid var(--amber)", padding: 18 }}>
          <div className="row" style={{ gap: 16, flexWrap: "wrap" }}>
            <div style={{ width: 48, height: 48, borderRadius: 14, background: "var(--amber)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name="star" size={24} color="white"/>
            </div>
            <div style={{ flex: 1, minWidth: 240 }}>
              <Pill tone="amber">Account transition</Pill>
              <div className="t-h2" style={{ marginTop: 6 }}>{child.name} just turned 13 — time for an independent account</div>
              <div className="muted" style={{ marginTop: 4, fontSize: 13 }}>Every PB, badge and class history transfers. You stay linked for visibility and billing. The handoff takes about 2 minutes.</div>
            </div>
            <div className="row" style={{ gap: 8 }}>
              <Button variant="ghost">Remind me later</Button>
              <Button variant="primary" onClick={onTransition}>Start transition<Icon name="chev-right" size={14}/></Button>
            </div>
          </div>
        </Card>
      )}

      {/* Live meet card — when child is racing */}
      {child.competing && (
        <LiveNowCard swimmerName={child.name === "Sophie Chen" ? "Sophie Chen" : null} onView={() => setSubroute("live")}/>
      )}

      <Card style={{ borderLeft: "4px solid var(--amber)", background: "var(--amber-50)" }}>
        <div className="between">
          <div className="row">
            <Icon name="alert" size={20} color="var(--amber)"/>
            <div>
              <div style={{ fontWeight: 700 }}>{child.name.split(" ")[0]}'s monthly tuition: ${child.monthly}</div>
              <div style={{ fontSize: 12, color: "#92590a" }}>Due in 3 days — auto-pay is on for this account</div>
            </div>
          </div>
          <Button variant="primary" onClick={() => setSubroute("billing")}>View billing</Button>
        </div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card style={{ borderLeft: "4px solid var(--aqua)" }}>
          <div className="t-caption">Next session</div>
          <div className="t-h2">{child.nextClass}</div>
          <div className="muted">{child.coach}</div>
          <div className="row" style={{ marginTop: 12, gap: 6 }}>
            <Button variant="secondary" size="sm" icon="calendar">Add to phone</Button>
            <Button variant="ghost" size="sm">Class details</Button>
          </div>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 12 }}>{child.name.split(" ")[0]}'s progress</div>
          <div className="row" style={{ gap: 14 }}>
            <ProgressRing pct={child.age >= 13 ? 85 : 60} size={80} color="var(--aqua)" label={child.age >= 13 ? "85%" : "60%"}/>
            <div style={{ flex: 1 }}>
              <Pill tone="aqua">Level {child.level}</Pill>
              <div style={{ marginTop: 8, fontSize: 13, color: "var(--gray-700)" }}>
                {child.competing
                  ? `Competing at age-group level. ${child.name.split(" ")[0]} earned ${Object.values(child.badges).reduce((a, b) => a + b, 0)} USA Swimming time-standard badges this season.`
                  : `${child.level === 7 ? 6 : 4} of 8 skills mastered. ${child.coach} says they're progressing well!`}
              </div>
              <Button variant="ghost" size="sm" style={{ marginTop: 8 }} onClick={() => setSubroute("progress")}>Full report<Icon name="chev-right" size={14}/></Button>
            </div>
          </div>
        </Card>
      </div>

      {/* USA Swimming time-standard badges */}
      {child.age >= 11 && (
        <Card>
          <div className="between" style={{ marginBottom: 14 }}>
            <div>
              <div className="t-h2">{child.name.split(" ")[0]}'s time-standard badges</div>
              <div className="t-caption">USA Swimming motivational standards · highest tier earned per event</div>
            </div>
            <Button variant="ghost" size="sm" onClick={() => setSubroute("progress")}>See all<Icon name="chev-right" size={14}/></Button>
          </div>
          <div style={{ marginBottom: 14 }}>
            <BadgeSummary counts={child.badges}/>
          </div>
          <BadgeCollection swimmer={child.age >= 13 ? [
            { event: "100m Free",  time: "1:00.42", sec: 60.42, std: "F-13-14-100FR-SCY", date: "Mar 14, 2026", pb: true },
            { event: "50m Free",   time: "0:27.42", sec: 27.42, std: "F-13-14-50FR-SCY",  date: "Feb 22, 2026" },
            { event: "200m IM",    time: "2:24.18", sec: 144.18, std: "F-13-14-200IM-SCY", date: "Apr 10, 2026" },
          ] : child.competing ? [
            { event: "100m Free",  time: "1:08.21", sec: 68.21, std: "M-13-14-100FR-SCY", date: "May 5, 2026", pb: true },
          ] : [
            { event: "50m Fly",    time: "0:32.41", sec: 32.41, std: "F-11-12-50FL-SCY",   date: "Apr 18, 2026", pb: true },
            { event: "100m Free",  time: "1:08.20", sec: 68.20, std: "F-11-12-100FR-SCY",  date: "Mar 14, 2026" },
          ]}/>
        </Card>
      )}
    </div>
  );
}

function ParentSchedule() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Schedule" sub="Mia's classes"
        actions={<><Tabs tabs={[{ id: "d", label: "Day" }, { id: "w", label: "Week" }, { id: "m", label: "Month" }]} value="w" onChange={() => {}}/><Button variant="secondary" icon="upload">Add to phone</Button></>}/>
      <Card>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 6 }}>
          {["Mon 13", "Tue 14", "Wed 15", "Thu 16", "Fri 17", "Sat 18", "Sun 19"].map((d, i) => (
            <div key={d} style={{ background: i === 1 ? "var(--aqua-50)" : "var(--gray-50)", borderRadius: 10, padding: 12, minHeight: 150 }}>
              <div className="t-caption" style={{ fontWeight: 600 }}>{d}</div>
              {[0, 2, 4].includes(i) && (
                <div style={{ marginTop: 8, padding: 8, background: "var(--aqua)", color: "white", borderRadius: 6 }}>
                  <div style={{ fontSize: 11, fontWeight: 700 }}>11:00</div>
                  <div style={{ fontSize: 11 }}>Stingrays L3</div>
                </div>
              )}
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function ParentProgress({ setSubroute }) {
  const [childId, setChildId] = useState("sophie");
  const child = CHILDREN.find(c => c.id === childId) || CHILDREN[0];

  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Swimmer progress" sub="Per-child training map and competition tier"
        actions={<Button variant="secondary" icon="download">Print report</Button>}/>

      <div className="row" style={{ gap: 6, overflowX: "auto", paddingBottom: 4 }}>
        {CHILDREN.map(c => {
          const active = childId === c.id;
          return (
            <button key={c.id} onClick={() => setChildId(c.id)} className="row" style={{
              padding: "8px 14px 8px 8px", borderRadius: 999, gap: 8, whiteSpace: "nowrap",
              background: active ? "var(--navy)" : "var(--gray-100)",
              color: active ? "white" : "var(--gray-700)",
              fontWeight: 600,
            }}>
              <Avatar name={c.name} color={c.color} size="sm"/>
              <span>{c.name.split(" ")[0]}</span>
              <span style={{ fontSize: 11, opacity: 0.7 }}>· {child.competing ? "Comp" : "L2S"}</span>
            </button>
          );
        })}
      </div>

      <Card>
        <div className="row between" style={{ marginBottom: 14, flexWrap: "wrap", gap: 8 }}>
          <div>
            <div className="t-h2">{child.name} — {child.competing ? "Competitive progression" : "Learn-to-Swim ladder"}</div>
            <div className="t-caption">{child.program} · Level {child.level} · {child.coach}</div>
          </div>
          {child.competing && <Pill tone="aqua" icon="trophy">USA Swimming registered</Pill>}
        </div>

        <SwimmerProgressMap
          swimmer={child}
          level={child.level}
          competitive={child.competing}
          progress={child.attendance / 100}
          tier={child.age >= 13 ? "senior" : child.competing ? "regional" : null}
        />
      </Card>

      {child.competing && (
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>USA Swimming time-standard badges</div>
          <div style={{ marginBottom: 14 }}><BadgeSummary counts={child.badges}/></div>
          <BadgeCollection swimmer={child.age >= 13 ? [
            { event: "100m Free",  time: "1:00.42", sec: 60.42, std: "F-13-14-100FR-SCY", date: "Mar 14, 2026", pb: true },
            { event: "50m Free",   time: "0:27.42", sec: 27.42, std: "F-13-14-50FR-SCY",  date: "Feb 22, 2026" },
            { event: "200m IM",    time: "2:24.18", sec: 144.18, std: "F-13-14-200IM-SCY", date: "Apr 10, 2026" },
          ] : [
            { event: "100m Free",  time: "1:08.21", sec: 68.21, std: "M-13-14-100FR-SCY", date: "May 5, 2026", pb: true },
          ]}/>
        </Card>
      )}
    </div>
  );
}

function ParentBilling({ toast }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Billing & payments"/>

      <Card style={{ background: "var(--navy)", color: "white" }}>
        <div className="between">
          <div>
            <div className="t-caption" style={{ color: "rgba(255,255,255,0.6)" }}>Balance due</div>
            <div className="t-mono-stat" style={{ color: "white", fontSize: 38 }}>$185.00</div>
            <div style={{ color: "rgba(255,255,255,0.7)", fontSize: 13 }}>May tuition · Due in 3 days</div>
          </div>
          <Button variant="mint" size="lg" onClick={() => toast({ message: "Payment processed · receipt emailed" })}>Pay now</Button>
        </div>
      </Card>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div className="t-h2">Payment methods</div>
          <Button variant="ghost" size="sm" icon="plus">Add</Button>
        </div>
        <div className="row between" style={{ padding: 14, background: "var(--gray-50)", borderRadius: 10 }}>
          <div className="row" style={{ gap: 12 }}>
            <div style={{ width: 48, height: 32, background: "var(--navy)", borderRadius: 6, display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontSize: 9, fontWeight: 700 }}>VISA</div>
            <div><div style={{ fontWeight: 600 }}>•••• 4242</div><div className="t-caption">Expires 03/28</div></div>
          </div>
          <Pill tone="aqua">Default</Pill>
        </div>
      </Card>

      <Card>
        <div className="between" style={{ padding: "10px 0", borderBottom: "1px solid var(--gray-100)" }}>
          <div><div style={{ fontWeight: 600 }}>Auto-pay</div><div className="t-caption">Auto-charge monthly tuition on the 1st</div></div>
          <Toggle on={true} onChange={() => {}}/>
        </div>
      </Card>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Invoice history</div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 10 }}>Date</th><th>Description</th><th>Amount</th><th>Status</th><th/></tr></thead>
          <tbody>
            {[
              { date: "May 1", desc: "May tuition", amt: 185, paid: false },
              { date: "Apr 1", desc: "April tuition", amt: 185, paid: true },
              { date: "Mar 1", desc: "March tuition", amt: 185, paid: true },
              { date: "Feb 1", desc: "February tuition", amt: 185, paid: true },
            ].map((r, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12 }}>{r.date}</td>
                <td>{r.desc}</td>
                <td className="t-mono-sm">${r.amt}.00</td>
                <td>{r.paid ? <Pill tone="mint">Paid</Pill> : <Pill tone="amber">Due</Pill>}</td>
                <td><Button variant="ghost" size="sm" icon="download">Receipt</Button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function ParentMessages() {
  const [tab, setTab] = useState("coaches");
  const [activeThread, setActiveThread] = useState(null);
  const [composing, setComposing] = useState(null);

  const CLASS_PARENTS = {
    mia: {
      className: "Stingrays L3",
      time: "Mon · Wed · Fri 11:00",
      coach: "Coach Maria",
      parents: [
        { id: "p1", name: "Sofia Ortiz",   child: "Liam Ortiz",    color: "#7C3AED", online: true },
        { id: "p2", name: "James Chen",    child: "Sophie Chen",   color: "#00C9A7", online: false },
        { id: "p3", name: "Rachel Park",   child: "Ethan Park",    color: "#1A7C6E", online: true },
        { id: "p4", name: "Daniel Adams",  child: "Ruby Adams",    color: "#F97316", online: false },
        { id: "p5", name: "Mei Khan",      child: "Zoe Khan",      color: "#0099CC", online: true },
        { id: "p6", name: "Carlos Costa",  child: "Diego Costa",   color: "#003366", online: false },
      ],
    },
    kai: {
      className: "Sharks Pre-Comp",
      time: "Daily 16:30",
      coach: "Coach Maria",
      parents: [
        { id: "p7", name: "Anna Robinson", child: "Ava Robinson",  color: "#D4A017", online: true },
        { id: "p8", name: "Carlos Costa",  child: "Diego Costa",   color: "#003366", online: false },
        { id: "p9", name: "Mei Khan",      child: "Zoe Khan",      color: "#0099CC", online: true },
        { id: "p10", name: "Yuki Sato",    child: "Hiro Sato",     color: "#7C3AED", online: false },
      ],
    },
    sophie: {
      className: "Senior Squad",
      time: "Daily 06:00 + 16:30",
      coach: "Coach Maria",
      parents: [
        { id: "p11", name: "Marco Lim",    child: "Hannah Lim",    color: "#00C9A7", online: true },
        { id: "p12", name: "Anna Robinson",child: "Ava Robinson",  color: "#D4A017", online: true },
        { id: "p13", name: "Yuki Sato",    child: "Hiro Sato",     color: "#7C3AED", online: false },
      ],
    },
  };

  const COACH_THREADS = [
    { id: "c1", name: "Coach Maria",   role: "Coach · Stingrays L3", lastBody: "Great session today — Mia's backstroke is really coming along!", time: "12m", unread: 1, color: "#0099CC" },
    { id: "c2", name: "Admin · Sarah", role: "School admin",         lastBody: "Reminder: pool closure on May 27 for maintenance.",              time: "2h", unread: 0, color: "#003366" },
    { id: "c3", name: "Coach Daniel",  role: "Coach · former Mia",   lastBody: "Thanks for the kind note — she was a delight to teach.",          time: "3d", unread: 0, color: "#F97316" },
  ];

  if (activeThread) return <ThreadView thread={activeThread} onBack={() => setActiveThread(null)}/>;

  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Messages" sub="Coaches, admin and other parents in your kids' classes"
        actions={<Button variant="primary" icon="edit" onClick={() => setComposing({ kind: "new" })}>New message</Button>}/>

      <Tabs tabs={[
        { id: "coaches", label: "Coaches & Admin" },
        { id: "parents", label: "Class parents" },
      ]} value={tab} onChange={setTab}/>

      {tab === "coaches" && (
        <Card style={{ padding: 0, overflow: "hidden" }}>
          {COACH_THREADS.map(t => (
            <button key={t.id} onClick={() => setActiveThread({ kind: "dm", name: t.name, role: t.role, color: t.color })} className="row" style={{ width: "100%", padding: 14, gap: 12, textAlign: "left", borderBottom: "1px solid var(--gray-100)" }}>
              <Avatar name={t.name} color={t.color}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="between"><div><span style={{ fontWeight: 700, fontSize: 14 }}>{t.name}</span> <span className="t-caption">· {t.role}</span></div><div className="t-caption">{t.time}</div></div>
                <div style={{ fontSize: 13, color: "var(--gray-600)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", marginTop: 2 }}>{t.lastBody}</div>
              </div>
              {t.unread > 0 && <div style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--aqua)", color: "white", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{t.unread}</div>}
            </button>
          ))}
        </Card>
      )}

      {tab === "parents" && (
        <div className="col" style={{ gap: 16 }}>
          {CHILDREN.map(child => {
            const klass = CLASS_PARENTS[child.id];
            if (!klass) return null;
            return (
              <Card key={child.id} style={{ padding: 0, overflow: "hidden", borderTop: `4px solid ${child.color}` }}>
                <div style={{ padding: 18, background: `linear-gradient(135deg, ${child.color}11, white)` }}>
                  <div className="between" style={{ flexWrap: "wrap", gap: 12 }}>
                    <div className="row" style={{ gap: 12, minWidth: 0 }}>
                      <Avatar name={child.name} color={child.color}/>
                      <div>
                        <div className="t-caption">{child.name}'s class</div>
                        <div className="t-h2">{klass.className}</div>
                        <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{klass.time} · {klass.coach} · {klass.parents.length} other families</div>
                      </div>
                    </div>
                    <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                      <Button variant="secondary" icon="msg" onClick={() => setActiveThread({
                        kind: "group", name: `${klass.className} parents`, role: `${klass.parents.length + 1} families`, color: child.color, members: klass.parents,
                      })}>Class group chat</Button>
                      <Button variant="primary" icon="edit" onClick={() => setComposing({ kind: "group", classId: child.id, klass })}>Announce</Button>
                    </div>
                  </div>
                </div>

                <div style={{ padding: "8px 12px 14px" }}>
                  <div className="t-label" style={{ padding: "8px 6px", color: "var(--gray-500)" }}>Other parents in this class</div>
                  <div className="col" style={{ gap: 4 }}>
                    {klass.parents.map(p => (
                      <button key={p.id} onClick={() => setActiveThread({ kind: "dm", name: p.name, role: `Parent of ${p.child}`, color: p.color })} className="row" style={{
                        width: "100%", padding: 10, borderRadius: 10, gap: 12, textAlign: "left", background: "transparent", transition: "background 120ms",
                      }} onMouseEnter={e => e.currentTarget.style.background = "var(--gray-50)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                        <div style={{ position: "relative" }}>
                          <Avatar name={p.name} color={p.color}/>
                          {p.online && <div style={{ position: "absolute", bottom: 0, right: 0, width: 10, height: 10, borderRadius: "50%", background: "var(--mint)", border: "2px solid white" }}/>}
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontWeight: 600, fontSize: 14 }}>{p.name}</div>
                          <div className="t-caption">Parent of {p.child}{p.online && <span style={{ color: "var(--mint)" }}> · online</span>}</div>
                        </div>
                        <Button variant="ghost" size="sm" icon="msg">Message</Button>
                      </button>
                    ))}
                  </div>
                </div>

                <div style={{ padding: "10px 18px", background: "var(--gray-50)", borderTop: "1px solid var(--gray-100)", fontSize: 11, color: "var(--gray-600)", display: "flex", gap: 8, alignItems: "center" }}>
                  <Icon name="lock" size={12}/>
                  <span>Only parents in the same class can message each other. Contact details stay private. SafeSport policy applies.</span>
                </div>
              </Card>
            );
          })}
        </div>
      )}

      {composing && <ComposeMessage mode={composing} kids={CHILDREN} classMap={CLASS_PARENTS} onClose={() => setComposing(null)} onSend={() => setComposing(null)}/>}
    </div>
  );
}

function ThreadView({ thread, onBack }) {
  const [draft, setDraft] = useState("");
  const isGroup = thread.kind === "group";
  return (
    <Card style={{ padding: 0, overflow: "hidden", height: "75vh", display: "flex", flexDirection: "column" }}>
      <div className="row between" style={{ padding: 14, borderBottom: "1px solid var(--gray-200)" }}>
        <div className="row">
          <button className="btn-icon" onClick={onBack}><Icon name="chev-left" size={18}/></button>
          <Avatar name={thread.name} color={thread.color}/>
          <div><div style={{ fontWeight: 700 }}>{thread.name}</div><div className="t-caption">{thread.role}</div></div>
        </div>
        <div className="row">
          {isGroup && <Pill tone="aqua" icon="users">{thread.members.length + 1} members</Pill>}
          <button className="btn-icon"><Icon name="more" size={16}/></button>
        </div>
      </div>

      {isGroup && (
        <div style={{ padding: 12, background: "var(--gray-50)", borderBottom: "1px solid var(--gray-200)", display: "flex", gap: 6, overflowX: "auto" }}>
          <div className="row" style={{ gap: 6, padding: "4px 10px", background: "white", borderRadius: 999, border: "1px solid var(--gray-200)", whiteSpace: "nowrap" }}>
            <Avatar name="You" size="sm"/><span style={{ fontSize: 12, fontWeight: 600 }}>You</span>
          </div>
          {thread.members.map(m => (
            <div key={m.id} className="row" style={{ gap: 6, padding: "4px 10px", background: "white", borderRadius: 999, border: "1px solid var(--gray-200)", whiteSpace: "nowrap" }}>
              <Avatar name={m.name} color={m.color} size="sm"/>
              <span style={{ fontSize: 12, fontWeight: 600 }}>{m.name.split(" ")[0]}</span>
            </div>
          ))}
        </div>
      )}

      <div style={{ flex: 1, padding: 16, background: "var(--gray-50)", overflowY: "auto" }}>
        <div className="col" style={{ gap: 12 }}>
          <div className="t-caption" style={{ textAlign: "center" }}>— Today 2:14 PM —</div>
          {isGroup ? (
            <>
              <GroupMsg from="Sofia Ortiz" color="#7C3AED" body="Hi everyone! Anyone planning to carpool to the Saturday meet?"/>
              <GroupMsg from="Rachel Park" color="#1A7C6E" body="Yes — we have space for 2 more in our SUV. Leaving 6:30 AM."/>
              <GroupMsg me body="That works for us. Sophie + Mia would be 2 kids + me. Thanks Rachel!"/>
              <GroupMsg from="Mei Khan" color="#0099CC" body="Could we share a cooler for snacks too?"/>
            </>
          ) : (
            <>
              <GroupMsg from={thread.name} color={thread.color} body="Hi! Just wanted to check in about Saturday's practice — is your kid coming?"/>
              <GroupMsg me body="Yes, we'll be there at 11. Thanks for the heads up!"/>
            </>
          )}
        </div>
      </div>

      <div style={{ padding: 12, borderTop: "1px solid var(--gray-200)", display: "flex", gap: 8 }}>
        <button className="btn-icon"><Icon name="plus" size={18}/></button>
        <input className="input" placeholder={isGroup ? "Message the group…" : "Type a message…"} value={draft} onChange={e => setDraft(e.target.value)} style={{ flex: 1 }}/>
        <Button variant="primary" icon="msg" onClick={() => setDraft("")}>Send</Button>
      </div>
    </Card>
  );
}

function GroupMsg({ from, color, body, me }) {
  return (
    <div className="row" style={{ alignItems: "flex-start", justifyContent: me ? "flex-end" : "flex-start", gap: 8 }}>
      {!me && <Avatar name={from} color={color} size="sm"/>}
      <div style={{ maxWidth: "72%" }}>
        {!me && <div className="t-caption" style={{ marginBottom: 2, marginLeft: 4 }}>{from}</div>}
        <div style={{
          background: me ? "var(--navy)" : "white", color: me ? "white" : "var(--gray-900)",
          padding: "10px 14px", borderRadius: me ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
          fontSize: 14, lineHeight: 1.4, boxShadow: "var(--sh-2)",
        }}>{body}</div>
      </div>
    </div>
  );
}

function ComposeMessage({ mode, kids, classMap, onClose, onSend }) {
  const [classId, setClassId] = useState(mode.classId || kids[0].id);
  const [audience, setAudience] = useState(mode.kind === "group" ? "group" : "group");
  const [picked, setPicked] = useState(null);
  const [subject, setSubject] = useState("");
  const [body, setBody] = useState("");
  const klassParents = (classMap[classId] || { parents: [] }).parents;

  return (
    <Sheet open={true} onClose={onClose} title="New message" large>
      <div className="col" style={{ gap: 16 }}>
        <div className="field">
          <label>About whose class?</label>
          <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
            {kids.map(c => {
              const active = classId === c.id;
              return (
                <button key={c.id} onClick={() => { setClassId(c.id); setPicked(null); }} className="row" style={{
                  padding: "8px 14px 8px 8px", borderRadius: 999, gap: 8,
                  background: active ? "var(--navy)" : "var(--gray-100)",
                  color: active ? "white" : "var(--gray-700)", fontWeight: 600, fontSize: 13,
                }}>
                  <Avatar name={c.name} color={c.color} size="sm"/>
                  <span>{c.name.split(" ")[0]} · {classMap[c.id]?.className}</span>
                </button>
              );
            })}
          </div>
        </div>

        <div className="field">
          <label>Send to</label>
          <div className="row" style={{ gap: 8 }}>
            <button onClick={() => setAudience("group")} className="card" style={{ flex: 1, padding: 14, textAlign: "left", borderLeft: `3px solid ${audience === "group" ? "var(--aqua)" : "transparent"}`, background: audience === "group" ? "var(--aqua-50)" : "var(--gray-50)", boxShadow: "none" }}>
              <div className="row" style={{ gap: 8 }}><Icon name="users" size={16} color="var(--aqua)"/><span style={{ fontWeight: 700, fontSize: 13 }}>Whole class group</span></div>
              <div className="t-caption" style={{ marginTop: 4 }}>All {klassParents.length} parents in this class</div>
            </button>
            <button onClick={() => setAudience("parent")} className="card" style={{ flex: 1, padding: 14, textAlign: "left", borderLeft: `3px solid ${audience === "parent" ? "var(--aqua)" : "transparent"}`, background: audience === "parent" ? "var(--aqua-50)" : "var(--gray-50)", boxShadow: "none" }}>
              <div className="row" style={{ gap: 8 }}><Icon name="users" size={16} color="var(--c-parent)"/><span style={{ fontWeight: 700, fontSize: 13 }}>One parent</span></div>
              <div className="t-caption" style={{ marginTop: 4 }}>Pick a specific parent below</div>
            </button>
          </div>
        </div>

        {audience === "parent" && (
          <div className="field">
            <label>Pick a parent</label>
            <div className="col" style={{ gap: 4, maxHeight: 240, overflowY: "auto" }}>
              {klassParents.map(p => (
                <button key={p.id} onClick={() => setPicked(p.id)} className="row" style={{ padding: 10, borderRadius: 10, gap: 12, background: picked === p.id ? "var(--aqua-50)" : "var(--gray-50)", textAlign: "left", border: picked === p.id ? "1.5px solid var(--aqua)" : "1.5px solid transparent" }}>
                  <Avatar name={p.name} color={p.color} size="sm"/>
                  <span style={{ fontWeight: 600, flex: 1 }}>{p.name} <span style={{ color: "var(--gray-500)", fontWeight: 400, fontSize: 12 }}>· parent of {p.child}</span></span>
                  {picked === p.id && <Icon name="check" size={14} color="var(--aqua)"/>}
                </button>
              ))}
            </div>
          </div>
        )}

        {audience === "group" && (
          <div className="field">
            <label>Subject (optional)</label>
            <input className="input" value={subject} onChange={e => setSubject(e.target.value)} placeholder="e.g. Carpool to Saturday meet?"/>
          </div>
        )}

        <div className="field">
          <label>Message</label>
          <textarea className="textarea" rows="5" value={body} onChange={e => setBody(e.target.value)} placeholder={audience === "group" ? "Send a note to the class…" : "Write your message…"}/>
        </div>

        <div style={{ background: "var(--gray-50)", padding: 12, borderRadius: 10, fontSize: 12, color: "var(--gray-600)", display: "flex", gap: 8, alignItems: "flex-start" }}>
          <Icon name="info" size={14} color="var(--gray-500)" style={{ marginTop: 2, flexShrink: 0 }}/>
          <span>All class messages are visible to {audience === "group" ? "every parent in the class and copied to the coach" : "you, the recipient, and the coach (SafeSport)"}. Contact details remain private.</span>
        </div>
      </div>

      <div className="row" style={{ marginTop: 18, justifyContent: "flex-end", gap: 8 }}>
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon="msg" onClick={onSend}>Send {audience === "group" ? `to ${klassParents.length} parents` : "message"}</Button>
      </div>
    </Sheet>
  );
}

// ============================================
// Club Management Portal
// ============================================
function ClubPortal({ subroute, setSubroute, toast }) {
  if (subroute === "roster") return <ClubRoster/>;
  if (subroute === "teams") return <ClubTeams/>;
  if (subroute === "meets") return <ClubMeets setSubroute={setSubroute}/>;
  if (subroute === "billing") return <ClubBilling/>;
  if (subroute === "analytics") return <ClubAnalytics/>;
  if (subroute === "meet-detail") return <MeetDetail setSubroute={setSubroute}/>;
  if (subroute === "live") return <LiveMeetPage setSubroute={setSubroute}/>;
  if (subroute === "announcement") return <ClubAnnouncement toast={toast}/>;
  return <ClubDashboard setSubroute={setSubroute}/>;
}

function ClubDashboard({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Marina Bay Aquatics Club" sub="248 members · 4 teams · 3 upcoming meets"
        actions={<>
          <LiveMeetTicker onClick={() => setSubroute("live")}/>
          <Button variant="secondary" icon="msg" onClick={() => setSubroute("announcement")}>Announce</Button>
          <Button variant="primary" icon="plus">Add member</Button>
        </>}/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
        <StatCard label="Total members" value="248" sub="+12 this month" trend="up" accent="var(--navy)" icon="users"/>
        <StatCard label="Active teams" value="4" sub="Across 3 age groups" accent="var(--aqua)" icon="shield"/>
        <StatCard label="Upcoming meets" value="3" sub="Next: Jun 14" accent="var(--c-competitive)" icon="trophy"/>
        <StatCard label="Outstanding dues" value="$8,420" sub="18 members" accent="var(--amber)" icon="credit-card"/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="between" style={{ marginBottom: 14 }}>
            <div className="t-h2">Upcoming meets</div>
            <button onClick={() => setSubroute("meets")} className="btn btn-ghost btn-sm">All meets<Icon name="chev-right" size={14}/></button>
          </div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { date: "Jun 14", name: "Friendly vs. Eastside SC", loc: "Aqua Center", entered: 28, type: "Friendly", color: "var(--mint)" },
              { date: "Jul 22", name: "Regional Championships", loc: "National Stadium", entered: 14, type: "Competition", color: "var(--c-competitive)" },
              { date: "Aug 30", name: "Summer Invitational", loc: "Sentosa", entered: 0, type: "Invitational", color: "var(--aqua)" },
            ].map((m, i) => (
              <button key={i} onClick={() => setSubroute("meet-detail")} className="row between" style={{ padding: 14, background: "var(--gray-50)", borderRadius: 10, textAlign: "left", width: "100%" }}>
                <div className="row">
                  <div style={{ width: 56, textAlign: "center", padding: 6, background: "white", borderRadius: 8, border: `2px solid ${m.color}` }}>
                    <div style={{ fontSize: 10, color: "var(--gray-500)", fontWeight: 700 }}>{m.date.split(" ")[0]}</div>
                    <div className="t-h2" style={{ color: m.color, fontSize: 22 }}>{m.date.split(" ")[1]}</div>
                  </div>
                  <div>
                    <Pill tone={m.type === "Competition" ? "amber" : m.type === "Friendly" ? "mint" : "aqua"}>{m.type}</Pill>
                    <div style={{ fontWeight: 600, marginTop: 4 }}>{m.name}</div>
                    <div className="t-caption">{m.loc} · {m.entered} entries</div>
                  </div>
                </div>
                <Icon name="chev-right" size={16} color="var(--gray-400)"/>
              </button>
            ))}
          </div>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Top performers</div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { name: "Diego Costa", evt: "100m Free", time: "0:54.8", pb: true },
              { name: "Sophie Chen", evt: "200m IM", time: "2:18.4" },
              { name: "Ethan Park", evt: "50m Fly", time: "0:27.1", pb: true },
              { name: "Zoe Khan", evt: "100m Back", time: "1:08.2" },
            ].map((p, i) => (
              <div key={i} className="row between" style={{ padding: 10, background: i === 0 ? "var(--amber-50)" : "var(--gray-50)", borderRadius: 8 }}>
                <div className="row">
                  <div style={{ width: 24, height: 24, borderRadius: "50%", background: i === 0 ? "var(--gold)" : i === 1 ? "var(--gray-400)" : i === 2 ? "#cd7f32" : "var(--gray-300)", color: "white", fontSize: 12, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{i + 1}</div>
                  <div><div style={{ fontWeight: 600, fontSize: 13 }}>{p.name}</div><div className="t-caption">{p.evt}</div></div>
                </div>
                <div className="row">
                  <span className="t-mono-sm" style={{ fontWeight: 700 }}>{p.time}</span>
                  {p.pb && <Pill tone="amber">PB</Pill>}
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Membership growth (12 months)</div>
        <LineChart values={[185, 192, 198, 205, 210, 218, 224, 228, 232, 236, 240, 248]} labels={["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"]} color="var(--navy)" height={180}/>
      </Card>
    </div>
  );
}

function ClubRoster() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Club roster" sub="248 active members"
        actions={<><Button variant="secondary" icon="upload">Import CSV</Button><Button variant="secondary" icon="download">Export</Button><Button variant="primary" icon="plus">Add member</Button></>}/>
      <Card>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 12 }}><input type="checkbox"/></th><th>Member</th><th>Age</th><th>Team</th><th>Status</th><th>Dues</th><th>Joined</th></tr></thead>
          <tbody>
            {STUDENTS.map(s => (
              <tr key={s.id} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12 }}><input type="checkbox"/></td>
                <td><div className="row"><Avatar name={s.name} color={s.color} size="sm"/><div style={{ fontWeight: 600 }}>{s.name}</div></div></td>
                <td>{s.age}</td>
                <td><Pill tone="aqua">{s.classes[0].split(" ")[0]}</Pill></td>
                <td>{s.attendance >= 90 ? <Pill tone="mint">Active</Pill> : <Pill tone="amber">Watch</Pill>}</td>
                <td>{s.id % 3 === 0 ? <Pill tone="red">Overdue</Pill> : <Pill tone="mint">Paid</Pill>}</td>
                <td className="t-caption">Aug 2024</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function ClubTeams() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Teams" actions={<Button variant="primary" icon="plus">Create team</Button>}/>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
        {[
          { name: "Minnows", age: "4–7", coach: "Daniel", roster: 38, cap: 50, color: "var(--c-recreation)" },
          { name: "Stingrays", age: "7–10", coach: "Maria", roster: 64, cap: 70, color: "var(--aqua)" },
          { name: "Dolphins", age: "10–13", coach: "Sam", roster: 72, cap: 80, color: "var(--mint)" },
          { name: "Sharks (Pre-Comp)", age: "12+", coach: "Maria", roster: 24, cap: 30, color: "var(--c-competitive)" },
        ].map((t, i) => (
          <Card key={i} style={{ borderTop: `4px solid ${t.color}`, paddingTop: 16 }}>
            <div className="t-h2">{t.name}</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>Ages {t.age} · Coach {t.coach}</div>
            <div className="row" style={{ marginTop: 14, gap: 16 }}>
              <div><div className="t-caption">Members</div><div className="t-mono-stat" style={{ fontSize: 22 }}>{t.roster}</div></div>
              <div style={{ flex: 1 }}>
                <div className="t-caption">Capacity</div>
                <ProgressBar pct={(t.roster / t.cap) * 100} color={t.color}/>
                <div className="t-caption" style={{ marginTop: 4 }}>{t.roster}/{t.cap}</div>
              </div>
            </div>
            <div className="row" style={{ marginTop: 12, gap: 6 }}><Button variant="secondary" size="sm">Manage</Button><Button variant="ghost" size="sm">Roster</Button></div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function ClubMeets({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Meets & events" actions={<Button variant="primary" icon="plus">Create meet</Button>}/>

      {/* Featured live meet */}
      <Card onClick={() => setSubroute("live")} style={{ cursor: "pointer", background: "linear-gradient(135deg, var(--navy-900), var(--c-competitive))", color: "white", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: 14, right: 14 }}>
          <div className="row" style={{ gap: 6, background: "rgba(220, 38, 38, 0.95)", padding: "6px 12px", borderRadius: 999 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: "white", animation: "pulse-ring 1.2s infinite" }}/>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.5 }}>LIVE NOW</span>
          </div>
        </div>
        <Pill tone="navy" style={{ background: "rgba(255,255,255,0.2)", color: "white" }}>Day 1 of 3</Pill>
        <div className="t-h1" style={{ color: "white", marginTop: 10 }}>Regional Championships</div>
        <div style={{ color: "rgba(255,255,255,0.75)" }}>National Stadium · Day 1 of 3 · 14 club entries swimming</div>
        <div className="row" style={{ gap: 24, marginTop: 18, flexWrap: "wrap" }}>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Events done</div><div className="t-mono-stat" style={{ color: "white" }}>14 / 26</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Club PBs today</div><div className="t-mono-stat" style={{ color: "var(--mint)" }}>+12</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Standards earned</div><div className="t-mono-stat" style={{ color: "var(--gold)" }}>+8</div></div>
          <div style={{ flex: 1 }}/>
          <Button variant="mint" iconRight="chev-right">Open live results</Button>
        </div>
      </Card>

      <div className="col" style={{ gap: 10 }}>
        {[
          { date: "Jun 14, 2026", name: "Friendly vs. Eastside SC", loc: "Aqua Center · Singapore", entered: 28, type: "Friendly" },
          { date: "Jul 22, 2026", name: "Regional Championships", loc: "National Stadium", entered: 14, type: "Competition", featured: true },
          { date: "Aug 30, 2026", name: "Summer Invitational", loc: "Sentosa Pool", entered: 0, type: "Invitational" },
          { date: "Apr 18, 2026", name: "Spring Sprint Series", loc: "Aqua Center", results: true, type: "Friendly" },
        ].map((m, i) => (
          <Card key={i} onClick={() => setSubroute("meet-detail")} style={{ cursor: "pointer", borderLeft: m.featured ? "4px solid var(--c-competitive)" : "none" }}>
            <div className="between" style={{ flexWrap: "wrap", gap: 12 }}>
              <div className="row">
                <div style={{ textAlign: "center", padding: "8px 12px", background: "var(--navy)", color: "white", borderRadius: 8 }}>
                  <div style={{ fontSize: 10, fontWeight: 700, opacity: 0.7 }}>{m.date.split(" ")[0].toUpperCase()}</div>
                  <div className="t-h2" style={{ color: "white" }}>{m.date.split(" ")[1].replace(",","")}</div>
                </div>
                <div>
                  <Pill tone={m.type === "Competition" ? "amber" : "aqua"}>{m.type}</Pill>
                  <div className="t-h2" style={{ marginTop: 4 }}>{m.name}</div>
                  <div className="t-caption">{m.loc} · {m.results ? "Completed" : `${m.entered} entries`}</div>
                </div>
              </div>
              <div className="row" style={{ gap: 6 }}>
                {m.results ? <Button variant="secondary" size="sm">View results</Button> : <><Button variant="secondary" size="sm">Manage entries</Button><Button variant="ghost" size="sm">Edit</Button></>}
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

function MeetDetail({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="row" style={{ gap: 8 }}>
        <button className="btn-icon" onClick={() => setSubroute("meets")}><Icon name="chev-left" size={18}/></button>
        <div className="t-caption">Meets</div><div className="t-caption">/</div><div className="t-caption" style={{ color: "var(--gray-900)", fontWeight: 600 }}>Regional Championships</div>
      </div>
      <Card style={{ background: "linear-gradient(135deg, var(--navy-900), var(--navy))", color: "white" }}>
        <Pill tone="navy" style={{ background: "rgba(255,255,255,0.2)", color: "white" }}>Competition</Pill>
        <div className="t-h1" style={{ color: "white", marginTop: 10 }}>Regional Championships</div>
        <div style={{ color: "rgba(255,255,255,0.7)" }}>Jul 22–24, 2026 · National Stadium</div>
        <div className="row" style={{ gap: 24, marginTop: 18, flexWrap: "wrap" }}>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Days to go</div><div className="t-mono-stat" style={{ color: "var(--gold)" }}>68</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Entries</div><div className="t-mono-stat" style={{ color: "white" }}>14</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Events</div><div className="t-mono-stat" style={{ color: "white" }}>26</div></div>
        </div>
      </Card>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div className="t-h2">Entries by event</div>
          <Button variant="secondary" icon="plus" size="sm">Add entry</Button>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 10 }}>Swimmer</th><th>Event</th><th>Seed time</th><th>Qual time</th><th>Status</th></tr></thead>
          <tbody>
            {[
              ["Diego Costa", "100m Free", "0:54.8", "0:55.0", "Qualified"],
              ["Diego Costa", "200m Free", "2:02.4", "2:05.0", "Qualified"],
              ["Sophie Chen", "100m Back", "1:08.2", "1:10.0", "Qualified"],
              ["Sophie Chen", "200m IM", "2:18.4", "2:20.0", "Qualified"],
              ["Ethan Park", "50m Fly", "0:27.1", "0:28.0", "Qualified"],
              ["Zoe Khan", "100m Free", "0:58.2", "0:57.0", "Below"],
            ].map((r, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12 }}>{r[0]}</td>
                <td>{r[1]}</td>
                <td className="t-mono-sm">{r[2]}</td>
                <td className="t-mono-sm">{r[3]}</td>
                <td>{r[4] === "Qualified" ? <Pill tone="mint">Qualified</Pill> : <Pill tone="amber">Below cut</Pill>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function ClubBilling() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Billing & dues"/>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
        <StatCard label="MTD revenue" value="$48,210" sub="92% collection" trend="up" accent="var(--mint)"/>
        <StatCard label="Outstanding" value="$8,420" sub="18 members" accent="var(--amber)"/>
        <StatCard label="Overdue 30+" value="$1,240" sub="3 members" accent="var(--red)"/>
      </div>
      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Outstanding invoices</div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 10 }}>Member</th><th>Amount</th><th>Due</th><th>Status</th><th/></tr></thead>
          <tbody>
            {[
              ["Sofia Ortiz", 185, "May 1", "Due 3d"],
              ["Diego Costa Family", 320, "Apr 1", "Overdue 30d"],
              ["Ava Robinson", 185, "May 1", "Due 3d"],
            ].map((r, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12 }}>{r[0]}</td>
                <td className="t-mono-sm">${r[1]}</td>
                <td>{r[2]}</td>
                <td>{r[3].includes("Overdue") ? <Pill tone="red">{r[3]}</Pill> : <Pill tone="amber">{r[3]}</Pill>}</td>
                <td><Button variant="ghost" size="sm">Send reminder</Button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function ClubAnalytics() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Club analytics"/>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
        <StatCard label="Retention" value="91%" trend="up" accent="var(--mint)"/>
        <StatCard label="Avg member tenure" value="2.4 yr" accent="var(--aqua)"/>
        <StatCard label="Revenue / member" value="$195" trend="up" accent="var(--navy)"/>
        <StatCard label="Meet participation" value="68%" sub="Of eligible" accent="var(--c-competitive)"/>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Membership growth</div>
          <LineChart values={[185, 192, 198, 205, 210, 218, 224, 228, 232, 236, 240, 248]} labels={["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"]} color="var(--navy)" height={180}/>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Revenue by team</div>
          <div className="col" style={{ gap: 10 }}>
            {[
              { t: "Minnows", v: 7800, c: "var(--c-recreation)" },
              { t: "Stingrays", v: 14200, c: "var(--aqua)" },
              { t: "Dolphins", v: 18400, c: "var(--mint)" },
              { t: "Sharks", v: 7810, c: "var(--c-competitive)" },
            ].map(d => (
              <div key={d.t} className="col" style={{ gap: 4 }}>
                <div className="between"><span style={{ fontSize: 13, fontWeight: 600 }}>{d.t}</span><span className="t-mono-sm">${d.v.toLocaleString()}</span></div>
                <ProgressBar pct={(d.v / 20000) * 100} color={d.c}/>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function ClubAnnouncement({ toast }) {
  return (
    <div className="col" style={{ gap: 16, maxWidth: 720 }}>
      <PageHeader title="Send announcement"/>
      <Card>
        <div className="col" style={{ gap: 14 }}>
          <div className="field"><label>Subject</label><input className="input" placeholder="e.g. Pool maintenance Friday"/></div>
          <div className="field"><label>Send to</label>
            <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
              {["All members", "Coaches only", "Parents only", "Stingrays team", "Dolphins team"].map((g, i) => (
                <button key={g} className="pill" style={{ background: i === 0 ? "var(--navy)" : "var(--gray-100)", color: i === 0 ? "white" : "var(--gray-700)" }}>{g}</button>
              ))}
            </div>
          </div>
          <div className="field"><label>Message</label><textarea className="textarea" rows="6" placeholder="Type your announcement…" defaultValue="Hi team,&#10;&#10;Pool maintenance is scheduled this Friday from 6 AM–10 AM. Morning classes will be relocated to the secondary pool.&#10;&#10;Thanks!"/></div>
          <div className="field"><label>Delivery</label>
            <div className="row" style={{ gap: 14 }}>
              <label className="row"><input type="checkbox" defaultChecked/><span style={{ marginLeft: 6 }}>In-app</span></label>
              <label className="row"><input type="checkbox" defaultChecked/><span style={{ marginLeft: 6 }}>Push notification</span></label>
              <label className="row"><input type="checkbox"/><span style={{ marginLeft: 6 }}>Email</span></label>
            </div>
          </div>
          <div className="row" style={{ justifyContent: "flex-end", gap: 8 }}>
            <Button variant="ghost">Save draft</Button>
            <Button variant="primary" onClick={() => toast({ message: "Announcement sent to 248 members" })}>Send announcement</Button>
          </div>
        </div>
      </Card>
    </div>
  );
}

// ============================================
// API Developer Portal
// ============================================
function DeveloperPortal({ subroute, setSubroute, toast }) {
  if (subroute === "keys") return <APIKeys toast={toast}/>;
  if (subroute === "docs") return <APIDocs/>;
  if (subroute === "webhooks") return <Webhooks toast={toast}/>;
  if (subroute === "logs") return <RequestLogs/>;
  if (subroute === "analytics") return <APIAnalytics/>;
  return <DevDashboard setSubroute={setSubroute}/>;
}

function DevDashboard({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Developer dashboard" sub="API usage, keys, and webhooks"
        actions={<><Button variant="secondary" icon="book" onClick={() => setSubroute("docs")}>Docs</Button><Button variant="primary" icon="key" onClick={() => setSubroute("keys")}>Generate key</Button></>}/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))", gap: 12 }}>
        <StatCard label="Requests (24h)" value="124,832" sub="+8% vs prior" trend="up" accent="var(--c-api)" icon="code"/>
        <StatCard label="Error rate" value="0.12%" sub="Within SLA" accent="var(--mint)" icon="check"/>
        <StatCard label="Avg latency" value="84ms" sub="P95: 240ms" accent="var(--aqua)" icon="stopwatch"/>
        <StatCard label="Active webhooks" value="6" sub="2 unhealthy" accent="var(--amber)" icon="webhook"/>
      </div>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div className="t-h2">Request volume — last 7 days</div>
          <Tabs tabs={[{ id: "h", label: "1h" }, { id: "d", label: "24h" }, { id: "w", label: "7d" }, { id: "m", label: "30d" }]} value="w" onChange={() => {}}/>
        </div>
        <LineChart values={[82, 91, 88, 102, 118, 124, 124]} labels={["Wed","Thu","Fri","Sat","Sun","Mon","Tue"]} color="var(--c-api)" height={200}/>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Quota usage</div>
          <div className="col" style={{ gap: 14 }}>
            {[
              { label: "Read requests", used: 124832, max: 250000, color: "var(--aqua)" },
              { label: "Write requests", used: 8420, max: 50000, color: "var(--mint)" },
              { label: "Webhooks", used: 6, max: 10, color: "var(--c-api)" },
            ].map(q => (
              <div key={q.label}>
                <div className="between" style={{ marginBottom: 6 }}>
                  <span style={{ fontWeight: 600, fontSize: 13 }}>{q.label}</span>
                  <span className="t-mono-sm">{q.used.toLocaleString()} / {q.max.toLocaleString()}</span>
                </div>
                <ProgressBar pct={(q.used / q.max) * 100} color={q.color}/>
              </div>
            ))}
          </div>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Top endpoints</div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { method: "GET", path: "/v1/sessions", count: 48210, color: "var(--mint)" },
              { method: "GET", path: "/v1/students", count: 32140, color: "var(--mint)" },
              { method: "POST", path: "/v1/sessions", count: 18420, color: "var(--aqua)" },
              { method: "GET", path: "/v1/classes", count: 12080, color: "var(--mint)" },
            ].map((e, i) => (
              <div key={i} className="row between" style={{ padding: 10, background: "var(--gray-50)", borderRadius: 8 }}>
                <div className="row">
                  <Pill tone={e.method === "GET" ? "mint" : "aqua"}>{e.method}</Pill>
                  <span className="t-mono-sm" style={{ fontWeight: 600 }}>{e.path}</span>
                </div>
                <span className="t-mono-sm" style={{ color: "var(--gray-600)" }}>{e.count.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function APIKeys({ toast }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="API keys" sub="Manage authentication tokens"
        actions={<Button variant="primary" icon="plus" onClick={() => toast({ message: "Key created — copied to clipboard" })}>Generate key</Button>}/>
      <Card>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 12 }}>Name</th><th>Key</th><th>Scopes</th><th>Last used</th><th>Created</th><th/></tr></thead>
          <tbody>
            {[
              { name: "Production server", key: "sk_live_•••• 7Hf2", scopes: "read, write", last: "2 min ago", created: "Jan 14, 2026" },
              { name: "Staging", key: "sk_test_•••• kP9x", scopes: "read, write", last: "1 hr ago", created: "Feb 2, 2026" },
              { name: "Analytics worker", key: "sk_live_•••• Mn41", scopes: "read", last: "5 hr ago", created: "Mar 8, 2026" },
              { name: "Old dashboard", key: "sk_live_•••• rT08", scopes: "read", last: "Never", created: "Sep 1, 2025" },
            ].map((k, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12, fontWeight: 600 }}>{k.name}</td>
                <td className="t-mono-sm" style={{ color: "var(--c-api)" }}>{k.key}</td>
                <td><Pill tone="aqua">{k.scopes}</Pill></td>
                <td className="t-caption">{k.last}</td>
                <td className="t-caption">{k.created}</td>
                <td><div className="row"><Button variant="ghost" size="sm">Rotate</Button><Button variant="ghost" size="sm">Revoke</Button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function APIDocs() {
  const [endpoint, setEndpoint] = useState("sessions.list");
  const endpoints = {
    "sessions.list": { method: "GET", path: "/v1/sessions", desc: "List swim sessions for the authenticated swimmer.", params: [["swimmer_id", "string", "Required. The swimmer ID."], ["limit", "int", "Optional. 1–100. Default 25."], ["after", "string", "Pagination cursor."]] },
    "sessions.create": { method: "POST", path: "/v1/sessions", desc: "Log a new swim session.", params: [["distance_m", "int", "Required. Total distance in meters."], ["duration_s", "int", "Required. Total time."], ["stroke", "string", "free|back|breast|fly|im"]] },
    "students.list": { method: "GET", path: "/v1/students", desc: "List students at your swim school.", params: [["level", "int", "Optional. Filter by level."]] },
  };
  const e = endpoints[endpoint];
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="API documentation"/>
      <Card style={{ padding: 0, overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", minHeight: 600 }}>
          <div style={{ background: "var(--gray-50)", borderRight: "1px solid var(--gray-200)", padding: 12, overflowY: "auto" }}>
            {[
              { name: "Sessions", items: ["sessions.list", "sessions.create"] },
              { name: "Students", items: ["students.list"] },
              { name: "Webhooks", items: [] },
            ].map(g => (
              <div key={g.name} style={{ marginBottom: 14 }}>
                <div className="t-label" style={{ padding: "8px 8px 4px", color: "var(--gray-500)" }}>{g.name}</div>
                {g.items.map(it => (
                  <button key={it} onClick={() => setEndpoint(it)} className="row" style={{ width: "100%", padding: "8px 10px", borderRadius: 6, background: endpoint === it ? "white" : "transparent", textAlign: "left", gap: 8 }}>
                    <Pill tone={it.includes("list") ? "mint" : "aqua"} style={{ fontSize: 9 }}>{it.includes("list") ? "GET" : "POST"}</Pill>
                    <span className="t-mono-sm" style={{ fontSize: 12 }}>{it.split(".")[1]}</span>
                  </button>
                ))}
              </div>
            ))}
          </div>
          <div style={{ padding: 24, overflowY: "auto" }}>
            <div className="row" style={{ gap: 10, marginBottom: 8 }}>
              <Pill tone={e.method === "GET" ? "mint" : "aqua"}>{e.method}</Pill>
              <span className="t-mono-sm" style={{ fontSize: 16, fontWeight: 600 }}>{e.path}</span>
            </div>
            <div className="muted" style={{ marginBottom: 18 }}>{e.desc}</div>

            <div className="t-h3" style={{ marginBottom: 8 }}>Parameters</div>
            <div className="col" style={{ gap: 6, marginBottom: 24 }}>
              {e.params.map(p => (
                <div key={p[0]} style={{ padding: 10, background: "var(--gray-50)", borderRadius: 8 }}>
                  <div className="row"><span className="t-mono-sm" style={{ fontWeight: 700, color: "var(--c-api)" }}>{p[0]}</span><Pill>{p[1]}</Pill></div>
                  <div style={{ fontSize: 12, color: "var(--gray-600)", marginTop: 4 }}>{p[2]}</div>
                </div>
              ))}
            </div>

            <div className="t-h3" style={{ marginBottom: 8 }}>Try it</div>
            <div style={{ background: "#0f1a2e", color: "white", padding: 16, borderRadius: 10, fontFamily: "var(--f-mono)", fontSize: 13, lineHeight: 1.5, overflowX: "auto" }}>
              <div style={{ color: "var(--gray-500)", marginBottom: 8 }}># cURL</div>
              <div style={{ whiteSpace: "pre" }}>{`curl -X ${e.method} https://api.aquaflow.app${e.path} \\
  -H "Authorization: Bearer $AQUAFLOW_KEY" \\
  -H "Content-Type: application/json"`}</div>
            </div>

            <Button variant="primary" style={{ marginTop: 12 }} icon="play">Send request</Button>

            <div className="t-h3" style={{ marginTop: 24, marginBottom: 8 }}>Response (200 OK)</div>
            <div style={{ background: "#0f1a2e", color: "var(--mint)", padding: 16, borderRadius: 10, fontFamily: "var(--f-mono)", fontSize: 12, lineHeight: 1.5, overflowX: "auto", whiteSpace: "pre" }}>
{`{
  "object": "list",
  "data": [
    { "id": "ses_2X4f", "distance_m": 3200, "duration_s": 1934, "stroke": "free", "pace_per_100m": "1:00.4" },
    { "id": "ses_2X4e", "distance_m": 4000, "duration_s": 4950, "stroke": "free" }
  ],
  "has_more": true
}`}
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

function Webhooks({ toast }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Webhooks" actions={<Button variant="primary" icon="plus">New webhook</Button>}/>
      <Card>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}><th style={{ padding: 12 }}>Endpoint</th><th>Events</th><th>Health</th><th>Last delivery</th><th/></tr></thead>
          <tbody>
            {[
              { url: "https://api.acmeswim.io/aquaflow/hook", events: "session.*, payment.*", health: "healthy", last: "2 min ago" },
              { url: "https://hooks.fitcoach.app/swim", events: "level.achieved", health: "healthy", last: "1 hr ago" },
              { url: "https://logs.internal/aquaflow", events: "*", health: "warning", last: "12 retries" },
              { url: "https://old.aquasys.com/wh", events: "session.created", health: "failing", last: "4 hr ago" },
            ].map((w, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 12 }} className="t-mono-sm">{w.url}</td>
                <td><Pill tone="aqua">{w.events}</Pill></td>
                <td><Pill tone={w.health === "healthy" ? "mint" : w.health === "warning" ? "amber" : "red"}>● {w.health}</Pill></td>
                <td className="t-caption">{w.last}</td>
                <td><div className="row"><Button variant="ghost" size="sm" onClick={() => toast({ message: "Test event sent" })}>Test</Button><Button variant="ghost" size="sm">Edit</Button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function RequestLogs() {
  const [filter, setFilter] = useState("all");
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Request logs"
        actions={<Tabs tabs={[{ id: "all", label: "All" }, { id: "ok", label: "2xx" }, { id: "warn", label: "4xx" }, { id: "err", label: "5xx" }]} value={filter} onChange={setFilter}/>}/>
      <Card>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, fontFamily: "var(--f-mono)" }}>
          <thead><tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1, fontFamily: "var(--f-body)" }}><th style={{ padding: 10 }}>Time</th><th>Method</th><th>Endpoint</th><th>Status</th><th>Latency</th></tr></thead>
          <tbody>
            {[
              ["14:32:18", "GET", "/v1/sessions?limit=50", 200, "84ms"],
              ["14:32:14", "POST", "/v1/sessions", 201, "142ms"],
              ["14:32:09", "GET", "/v1/students/4f29", 200, "62ms"],
              ["14:32:02", "GET", "/v1/sessions?limit=25", 200, "78ms"],
              ["14:31:58", "POST", "/v1/sessions", 422, "92ms"],
              ["14:31:51", "GET", "/v1/students", 200, "112ms"],
              ["14:31:42", "DELETE", "/v1/keys/abc12", 200, "48ms"],
              ["14:31:38", "GET", "/v1/sessions", 500, "2,140ms"],
              ["14:31:29", "GET", "/v1/students/4f30", 404, "32ms"],
            ].map((r, i) => (
              <tr key={i} style={{ borderTop: "1px solid var(--gray-100)" }}>
                <td style={{ padding: 10, color: "var(--gray-500)" }}>{r[0]}</td>
                <td><Pill tone={r[1] === "GET" ? "mint" : r[1] === "POST" ? "aqua" : "red"}>{r[1]}</Pill></td>
                <td style={{ color: "var(--gray-800)" }}>{r[2]}</td>
                <td style={{ color: r[3] >= 500 ? "var(--red)" : r[3] >= 400 ? "var(--amber)" : "var(--mint)", fontWeight: 700 }}>{r[3]}</td>
                <td>{r[4]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function APIAnalytics() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Usage analytics"/>
      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Daily request volume</div>
        <LineChart values={[82000, 91000, 88000, 102000, 118000, 124000, 124832]} labels={["6d ago", "5d", "4d", "3d", "2d", "Yesterday", "Today"]} color="var(--c-api)" height={200}/>
      </Card>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Error rate</div>
          <BarChart data={[
            { label: "Mon", value: 0.08 }, { label: "Tue", value: 0.12 }, { label: "Wed", value: 0.09 },
            { label: "Thu", value: 0.14 }, { label: "Fri", value: 0.18 }, { label: "Sat", value: 0.12 }, { label: "Sun", value: 0.10 },
          ]} max={0.3} color="var(--red)" height={140}/>
        </Card>
        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Top consumers</div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { name: "AcmeSwim Coach App", requests: 48230 },
              { name: "TriCoach Analytics", requests: 32140 },
              { name: "MarinaBay Club", requests: 18920 },
              { name: "FitTracker Sync", requests: 9410 },
            ].map((c, i) => (
              <div key={i} className="row between" style={{ padding: 10, background: "var(--gray-50)", borderRadius: 8 }}>
                <span style={{ fontWeight: 600, fontSize: 13 }}>{c.name}</span>
                <span className="t-mono-sm">{c.requests.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { CoachPortal, StudentPortal, ParentPortal, ClubPortal, DeveloperPortal });
