// ============================================
// Competitive Lap Tracking Portal
// ============================================

function CompetitivePortal({ subroute, setSubroute, toast }) {
  if (subroute === "presession") return <PreSession setSubroute={setSubroute}/>;
  if (subroute === "active") return <ActiveSession setSubroute={setSubroute} toast={toast}/>;
  if (subroute === "postsession") return <PostSession setSubroute={setSubroute}/>;
  if (subroute === "train") return <TrainHub setSubroute={setSubroute}/>;
  if (subroute === "history") return <TrainingLog setSubroute={setSubroute}/>;
  if (subroute === "records") return <PersonalRecords/>;
  if (subroute === "templates") return <WorkoutTemplates setSubroute={setSubroute}/>;
  if (subroute === "race-sim") return <RaceSimulation setSubroute={setSubroute}/>;
  if (subroute === "goals") return <GoalTracker/>;
  if (subroute === "profile") return <SwimmerProfile/>;
  if (subroute === "live") return <LiveMeetPage setSubroute={setSubroute} highlight="Sophie Chen"/>;
  return <CompetitiveHome setSubroute={setSubroute}/>;
}

function CompetitiveHome({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Welcome back, Alex" sub="3 sessions this week · keep the streak alive"
        actions={<LiveMeetTicker onClick={() => setSubroute("live")}/>}/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12 }}>
        <StatCard label="This week" value="9,400m" sub="78% of 12k goal" trend="up" accent="var(--c-competitive)" icon="wave"/>
        <StatCard label="Avg pace 100m" value="1:09.8" sub="-1.2s vs last week" trend="up" accent="var(--aqua)" icon="stopwatch"/>
        <StatCard label="Sessions" value="3" sub="Out of 4 planned" accent="var(--mint)" icon="check-circle"/>
        <StatCard label="Streak" value="14 days" sub="Personal best 21d" accent="var(--c-recreation)" icon="flame"/>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 16 }} className="dash-grid">
        <Card style={{ background: "linear-gradient(135deg, var(--navy-900), var(--navy))", color: "white", position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", top: -20, right: -30, opacity: 0.1 }}>
            <Icon name="stopwatch" size={180} color="white"/>
          </div>
          <div style={{ position: "relative" }}>
            <Pill tone="navy" style={{ background: "rgba(255,255,255,0.2)" }}>Ready to swim</Pill>
            <div className="t-h1" style={{ color: "white", marginTop: 12, marginBottom: 6 }}>Start training</div>
            <div style={{ color: "rgba(255,255,255,0.7)", fontSize: 14, marginBottom: 18 }}>Tap to set up your pool, stroke and target.</div>
            <Button variant="mint" size="lg" iconRight="chev-right" onClick={() => setSubroute("presession")}>Start session</Button>
          </div>
        </Card>

        <Card>
          <div className="between" style={{ marginBottom: 14 }}>
            <div className="t-h2">Goal progress</div>
            <button className="btn btn-ghost btn-sm" onClick={() => setSubroute("goals")}>All goals<Icon name="chev-right" size={14}/></button>
          </div>
          <div className="row" style={{ gap: 18, justifyContent: "space-around", padding: "12px 0" }}>
            <div style={{ textAlign: "center" }}>
              <ProgressRing pct={78} size={96} color="var(--c-competitive)" label="78%"/>
              <div style={{ fontSize: 11, color: "var(--gray-600)", marginTop: 6, fontWeight: 600 }}>Weekly volume</div>
            </div>
            <div style={{ textAlign: "center" }}>
              <ProgressRing pct={45} size={96} color="var(--aqua)" label="45%"/>
              <div style={{ fontSize: 11, color: "var(--gray-600)", marginTop: 6, fontWeight: 600 }}>Sub-1:05 100m</div>
            </div>
            <div style={{ textAlign: "center" }}>
              <ProgressRing pct={62} size={96} color="var(--mint)" label="62%"/>
              <div style={{ fontSize: 11, color: "var(--gray-600)", marginTop: 6, fontWeight: 600 }}>Speed sets</div>
            </div>
          </div>
        </Card>
      </div>

      <Card>
        <div className="between" style={{ marginBottom: 14 }}>
          <div className="t-h2">Recent sessions</div>
          <button className="btn btn-ghost btn-sm" onClick={() => setSubroute("history")}>Full history<Icon name="chev-right" size={14}/></button>
        </div>
        <div className="col" style={{ gap: 8 }}>
          {[
            { date: "Mon May 12", title: "Speed pyramid", distance: "3,200m", time: "62:14", stroke: "Free", color: "var(--c-competitive)" },
            { date: "Sat May 10", title: "Endurance cruise", distance: "4,000m", time: "82:30", stroke: "Free + Back", color: "var(--aqua)" },
            { date: "Thu May 8",  title: "IM technique", distance: "2,200m", time: "55:08", stroke: "IM", color: "var(--mint)" },
          ].map((s, i) => (
            <button key={i} onClick={() => setSubroute("postsession")} className="row" style={{ padding: 14, background: "var(--gray-50)", borderRadius: 10, gap: 14, width: "100%", textAlign: "left" }}>
              <div style={{ width: 4, height: 40, background: s.color, borderRadius: 999 }}/>
              <div style={{ flex: 1 }}>
                <div className="row" style={{ gap: 8 }}><span style={{ fontWeight: 600 }}>{s.title}</span><Pill>{s.stroke}</Pill></div>
                <div style={{ fontSize: 12, color: "var(--gray-600)" }}>{s.date}</div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div className="t-mono-sm" style={{ fontWeight: 700 }}>{s.distance}</div>
                <div className="t-mono-sm" style={{ color: "var(--gray-600)" }}>{s.time}</div>
              </div>
              <Icon name="chev-right" size={16} color="var(--gray-400)"/>
            </button>
          ))}
        </div>
      </Card>

      <Card>
        <div className="t-h2" style={{ marginBottom: 12 }}>Personal records</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: 10 }}>
          {[
            { d: "50m Free", t: "0:27.42", date: "Mar 22" },
            { d: "100m Free", t: "1:07.42", date: "May 14", new: true },
            { d: "200m Free", t: "2:24.18", date: "Apr 10" },
            { d: "400m Free", t: "5:08.66", date: "Feb 14" },
          ].map((r, i) => (
            <div key={i} style={{ background: "var(--navy)", color: "white", borderRadius: 12, padding: 14, position: "relative" }}>
              {r.new && <Pill tone="mint" style={{ position: "absolute", top: 10, right: 10 }}>NEW</Pill>}
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.6)", fontWeight: 600, letterSpacing: 1, textTransform: "uppercase" }}>{r.d}</div>
              <div className="t-mono-stat" style={{ color: "var(--mint)", fontSize: 26, marginTop: 8 }}>{r.t}</div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", marginTop: 6 }}>Set {r.date}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function PreSession({ setSubroute }) {
  const [pool, setPool] = useState("25m");
  const [stroke, setStroke] = useState("Freestyle");
  const [type, setType] = useState("free");
  const [warmup, setWarmup] = useState(true);

  return (
    <div className="col" style={{ gap: 16, maxWidth: 640 }}>
      <div className="row" style={{ gap: 8 }}>
        <button className="btn-icon" onClick={() => setSubroute("home")}><Icon name="chev-left" size={18}/></button>
        <div className="t-caption">Train</div><div className="t-caption">/</div><div className="t-caption" style={{ color: "var(--gray-900)", fontWeight: 600 }}>Setup</div>
      </div>
      <PageHeader title="Set up your session"/>

      <Card>
        <div className="t-h3" style={{ marginBottom: 12 }}>Pool length</div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          {["25m", "50m", "25y"].map(p => (
            <button key={p} onClick={() => setPool(p)} className="btn" style={{ flex: 1, minWidth: 80, background: pool === p ? "var(--navy)" : "white", color: pool === p ? "white" : "var(--gray-700)", border: `1px solid ${pool === p ? "var(--navy)" : "var(--gray-300)"}` }}>{p}</button>
          ))}
        </div>
      </Card>

      <Card>
        <div className="t-h3" style={{ marginBottom: 12 }}>Primary stroke</div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          {["Freestyle", "Backstroke", "Breaststroke", "Butterfly", "IM", "Mix"].map(s => (
            <button key={s} onClick={() => setStroke(s)} className="btn" style={{ background: stroke === s ? "var(--c-competitive)" : "white", color: stroke === s ? "var(--navy-900)" : "var(--gray-700)", border: `1px solid ${stroke === s ? "var(--c-competitive)" : "var(--gray-300)"}` }}>{s}</button>
          ))}
        </div>
      </Card>

      <Card>
        <div className="t-h3" style={{ marginBottom: 12 }}>Session type</div>
        <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
          {[
            { id: "free", label: "Free swim", icon: "wave" },
            { id: "template", label: "Workout template", icon: "ladder" },
            { id: "race", label: "Race simulation", icon: "trophy" },
          ].map(t => (
            <button key={t.id} onClick={() => setType(t.id)} className="btn" style={{ flex: 1, minWidth: 140, background: type === t.id ? "var(--navy)" : "white", color: type === t.id ? "white" : "var(--gray-700)", border: `1px solid ${type === t.id ? "var(--navy)" : "var(--gray-300)"}`, gap: 6 }}>
              <Icon name={t.icon} size={14}/>{t.label}
            </button>
          ))}
        </div>
        {type === "template" && (
          <div className="col" style={{ gap: 8, marginTop: 14 }}>
            {["Speed pyramid (3,200m)", "Endurance cruise (4,000m)", "Threshold ladder (2,800m)"].map(t => (
              <label key={t} className="row" style={{ padding: 12, background: "var(--gray-50)", borderRadius: 10 }}>
                <input type="radio" name="tmpl" defaultChecked={t.includes("Speed")}/>
                <span style={{ marginLeft: 10, fontWeight: 500 }}>{t}</span>
                <span style={{ marginLeft: "auto", fontSize: 12, color: "var(--gray-500)" }}>~62 min</span>
              </label>
            ))}
          </div>
        )}
      </Card>

      <Card>
        <div className="between">
          <div>
            <div className="t-h3">Warm-up & cool-down</div>
            <div className="muted t-caption">Auto-add 400m warm-up and 200m cool-down</div>
          </div>
          <Toggle on={warmup} onChange={setWarmup}/>
        </div>
      </Card>

      <Button variant="primary" size="lg" full onClick={() => setSubroute("active")} iconRight="play">Start session</Button>
    </div>
  );
}

function ActiveSession({ setSubroute, toast }) {
  const [time, setTime] = useState(0);
  const [paused, setPaused] = useState(false);
  const [laps, setLaps] = useState([]);
  const [lastTap, setLastTap] = useState(0);
  const [holding, setHolding] = useState(0);
  const holdRef = useRef(null);

  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => setTime(t => t + 0.05), 50);
    return () => clearInterval(id);
  }, [paused]);

  const tap = () => {
    const now = Date.now();
    if (now - lastTap < 300) {
      // double tap = pause
      setPaused(p => !p);
      setLastTap(0);
      return;
    }
    setLastTap(now);
    const t = laps.length ? time - laps.reduce((a, b) => a + b.split, 0) : time;
    setLaps([...laps, { split: t, lap: laps.length + 1 }]);
    if (navigator.vibrate) navigator.vibrate(30);
  };

  const startHold = () => {
    holdRef.current = setInterval(() => setHolding(h => h + 5), 50);
  };
  const endHold = () => {
    clearInterval(holdRef.current);
    if (holding >= 100) {
      toast({ message: "Session ended" });
      setSubroute("postsession");
    }
    setHolding(0);
  };

  const fmt = (s) => {
    const m = Math.floor(s / 60);
    const sec = Math.floor(s % 60);
    const ms = Math.floor((s % 1) * 100);
    return `${String(m).padStart(2,"0")}:${String(sec).padStart(2,"0")}.${String(ms).padStart(2,"0")}`;
  };

  const cur = laps.length ? time - laps.reduce((a, b) => a + b.split, 0) : time;
  const distance = laps.length * 25;
  const avgPace = laps.length ? laps.reduce((a, b) => a + b.split, 0) / laps.length : 0;

  return (
    <div style={{ position: "fixed", inset: 0, background: "var(--navy-900)", color: "white", zIndex: 600, display: "flex", flexDirection: "column", touchAction: "manipulation" }}>
      <div className="between" style={{ padding: "20px 24px", paddingTop: "max(20px, env(safe-area-inset-top))", flexShrink: 0 }}>
        <Pill tone="navy" style={{ background: "rgba(255,255,255,0.12)", color: "white" }}>● {paused ? "PAUSED" : "LIVE"}</Pill>
        <div className="row" style={{ gap: 16, fontSize: 13, color: "rgba(255,255,255,0.7)", fontWeight: 600 }}>
          <div className="row" style={{ gap: 4 }}><Icon name="heart" size={14} color="var(--mint)"/><span className="t-mono-sm">142 bpm</span></div>
          <div>25m · Freestyle</div>
        </div>
      </div>

      <div onClick={!paused ? tap : undefined} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", cursor: paused ? "default" : "pointer", position: "relative" }}>
        <div style={{ fontSize: 14, color: "rgba(255,255,255,0.6)", letterSpacing: 2, textTransform: "uppercase", fontWeight: 700, marginBottom: 12 }}>Lap {laps.length + 1}</div>
        <div style={{ fontFamily: "var(--f-mono)", fontWeight: 700, fontSize: "clamp(72px, 18vw, 168px)", letterSpacing: -3, lineHeight: 1, color: "white" }}>{fmt(cur)}</div>
        <div style={{ marginTop: 28, display: "flex", gap: 32 }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Distance</div>
            <div className="t-mono-stat" style={{ color: "var(--aqua)", marginTop: 4 }}>{distance}m</div>
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Total</div>
            <div className="t-mono-stat" style={{ color: "var(--mint)", marginTop: 4 }}>{fmt(time)}</div>
          </div>
          <div style={{ textAlign: "center" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Avg / lap</div>
            <div className="t-mono-stat" style={{ color: "var(--gold)", marginTop: 4 }}>{avgPace ? fmt(avgPace).slice(0, -3) : "—"}</div>
          </div>
        </div>

        {!paused && <div style={{ position: "absolute", bottom: 40, fontSize: 13, color: "rgba(255,255,255,0.5)", letterSpacing: 2, textTransform: "uppercase", fontWeight: 700 }}>Tap anywhere = lap · double-tap = pause</div>}
      </div>

      {/* Recent splits ribbon */}
      <div style={{ padding: "12px 24px", borderTop: "1px solid rgba(255,255,255,0.08)", overflowX: "auto", flexShrink: 0 }}>
        <div style={{ display: "flex", gap: 12, fontFamily: "var(--f-mono)", fontSize: 14, fontWeight: 600 }}>
          {laps.slice(-6).reverse().map((l, i) => {
            const pace = i === 0 && laps.length > 1 ? (l.split < laps[laps.length - 2].split ? "var(--mint)" : "var(--c-competitive)") : "rgba(255,255,255,0.5)";
            return (
              <div key={l.lap} style={{ background: "rgba(255,255,255,0.08)", padding: "8px 14px", borderRadius: 8, color: pace, whiteSpace: "nowrap" }}>
                #{l.lap} <span style={{ color: "white", marginLeft: 4 }}>{fmt(l.split)}</span>
              </div>
            );
          })}
          {laps.length === 0 && <div style={{ color: "rgba(255,255,255,0.4)", fontSize: 13 }}>No splits yet — tap to record your first lap</div>}
        </div>
      </div>

      <div className="row" style={{ padding: 24, paddingBottom: "max(24px, env(safe-area-inset-bottom))", gap: 12, flexShrink: 0 }}>
        <button onClick={() => setPaused(!paused)} style={{ flex: 1, height: 72, borderRadius: 18, background: "rgba(255,255,255,0.1)", color: "white", display: "flex", alignItems: "center", justifyContent: "center", gap: 10, fontSize: 16, fontWeight: 700 }}>
          <Icon name={paused ? "play" : "pause"} size={24} color="white"/>
          {paused ? "Resume" : "Pause"}
        </button>
        <button onMouseDown={startHold} onMouseUp={endHold} onMouseLeave={endHold} onTouchStart={startHold} onTouchEnd={endHold} style={{ flex: 1, height: 72, borderRadius: 18, background: "var(--red)", color: "white", display: "flex", alignItems: "center", justifyContent: "center", gap: 10, fontSize: 16, fontWeight: 700, position: "relative", overflow: "hidden" }}>
          {holding > 0 && <div style={{ position: "absolute", inset: 0, background: "rgba(255,255,255,0.2)", width: `${holding}%` }}/>}
          <span style={{ position: "relative" }}>{holding > 0 ? "Hold to end…" : "Hold to end"}</span>
        </button>
      </div>
    </div>
  );
}

function PostSession({ setSubroute }) {
  const laps = [
    { n: 1, t: 0.42, cum: 0.42, pace: "Z2", color: "var(--mint)" },
    { n: 2, t: 0.45, cum: 0.87, pace: "Z2", color: "var(--mint)" },
    { n: 3, t: 0.41, cum: 1.28, pace: "Z3", color: "var(--mint)" },
    { n: 4, t: 0.43, cum: 1.71, pace: "Z2", color: "var(--mint)" },
    { n: 5, t: 0.40, cum: 2.11, pace: "Z3", color: "var(--mint)", best: true },
    { n: 6, t: 0.48, cum: 2.59, pace: "Z2", color: "var(--amber)" },
    { n: 7, t: 0.51, cum: 3.10, pace: "Z1", color: "var(--red)", worst: true },
    { n: 8, t: 0.42, cum: 3.52, pace: "Z3", color: "var(--mint)" },
  ];
  const fmt = (s) => `0:${String(Math.floor((s % 60) * 60 / 60)).padStart(2,"0")}.${String(Math.floor((s % 1) * 100)).padStart(2,"0")}`;

  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="row" style={{ gap: 8 }}>
        <button className="btn-icon" onClick={() => setSubroute("home")}><Icon name="x" size={18}/></button>
        <div className="t-caption">Session complete</div>
      </div>

      <Card style={{ background: "linear-gradient(135deg, var(--navy-900), var(--navy))", color: "white" }}>
        <Pill tone="mint">PB · 100m</Pill>
        <div className="t-h1" style={{ color: "white", marginTop: 10 }}>Speed pyramid · 25m Free</div>
        <div style={{ color: "rgba(255,255,255,0.7)" }}>Today · 6:38 PM · 32 min</div>
        <div className="row" style={{ marginTop: 18, gap: 24, flexWrap: "wrap" }}>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Distance</div><div className="t-mono-stat" style={{ color: "var(--aqua)" }}>3,200m</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Total time</div><div className="t-mono-stat" style={{ color: "white" }}>32:14</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Laps</div><div className="t-mono-stat" style={{ color: "white" }}>128</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Avg 100m</div><div className="t-mono-stat" style={{ color: "var(--mint)" }}>1:00.4</div></div>
          <div><div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", letterSpacing: 1, textTransform: "uppercase", fontWeight: 700 }}>Best split</div><div className="t-mono-stat" style={{ color: "var(--gold)" }}>0:24.8</div></div>
        </div>
      </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 }}>Pace by lap</div>
          <BarChart data={laps.map(l => ({ label: l.n, value: 0.6 - l.t, color: l.best ? "var(--gold)" : l.worst ? "var(--red)" : l.t > 0.45 ? "var(--amber)" : "var(--mint)" }))} height={140}/>
          <div className="row" style={{ marginTop: 10, gap: 14, fontSize: 11, color: "var(--gray-600)" }}>
            <div className="row" style={{ gap: 4 }}><div style={{ width: 10, height: 10, background: "var(--mint)", borderRadius: 2 }}/>Fast</div>
            <div className="row" style={{ gap: 4 }}><div style={{ width: 10, height: 10, background: "var(--amber)", borderRadius: 2 }}/>Steady</div>
            <div className="row" style={{ gap: 4 }}><div style={{ width: 10, height: 10, background: "var(--red)", borderRadius: 2 }}/>Slow</div>
          </div>
        </Card>

        <Card>
          <div className="t-h2" style={{ marginBottom: 14 }}>Pace zones</div>
          <div className="col" style={{ gap: 8 }}>
            {[
              { z: "Z5 Sprint", pct: 8, color: "var(--red)" },
              { z: "Z4 VO2", pct: 12, color: "var(--c-recreation)" },
              { z: "Z3 Threshold", pct: 28, color: "var(--amber)" },
              { z: "Z2 Aerobic", pct: 38, color: "var(--mint)" },
              { z: "Z1 Recovery", pct: 14, color: "var(--aqua)" },
            ].map(z => (
              <div key={z.z} className="col" style={{ gap: 4 }}>
                <div className="between"><span style={{ fontSize: 12, fontWeight: 600 }}>{z.z}</span><span className="t-mono-sm" style={{ fontWeight: 600 }}>{z.pct}%</span></div>
                <ProgressBar pct={z.pct} color={z.color}/>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Lap-by-lap</div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--f-mono)", fontSize: 13 }}>
            <thead>
              <tr style={{ textAlign: "left", color: "var(--gray-500)", fontSize: 11, textTransform: "uppercase", letterSpacing: 1 }}>
                <th style={{ padding: 10 }}>Lap</th><th>Split</th><th>Cumulative</th><th>Pace zone</th><th/>
              </tr>
            </thead>
            <tbody>
              {laps.map(l => (
                <tr key={l.n} style={{ borderTop: "1px solid var(--gray-100)", background: l.best ? "var(--mint-50)" : l.worst ? "var(--red-50)" : "transparent" }}>
                  <td style={{ padding: 10, fontWeight: 700 }}>#{l.n}</td>
                  <td>{fmt(l.t)}</td>
                  <td>{fmt(l.cum)}</td>
                  <td><Pill tone={l.pace === "Z3" ? "aqua" : l.pace === "Z2" ? "mint" : "default"}>{l.pace}</Pill></td>
                  <td>{l.best && <Pill tone="mint" icon="trophy">Best</Pill>}{l.worst && <Pill tone="red">Slowest</Pill>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      <div className="row" style={{ gap: 8 }}>
        <Button variant="secondary" icon="share">Share</Button>
        <Button variant="ghost" icon="edit">Annotate</Button>
        <div style={{ flex: 1 }}/>
        <Button variant="primary" onClick={() => setSubroute("home")}>Done</Button>
      </div>
    </div>
  );
}

function TrainHub({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Train" sub="Sessions, templates and race simulation"/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
        {[
          { id: "presession", label: "Free swim", desc: "Quick lap timer", icon: "wave", color: "var(--c-competitive)" },
          { id: "templates", label: "Workout templates", desc: "Pre-built sets", icon: "ladder", color: "var(--aqua)" },
          { id: "race-sim", label: "Race simulation", desc: "Pace against a ghost", icon: "trophy", color: "var(--gold)" },
        ].map(t => (
          <button key={t.id} onClick={() => setSubroute(t.id)} className="card" style={{ textAlign: "left", border: `1.5px solid ${t.color}33`, transition: "all 160ms" }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: `${t.color}22`, display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
              <Icon name={t.icon} size={22} color={t.color}/>
            </div>
            <div className="t-h2" style={{ fontSize: 18 }}>{t.label}</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t.desc}</div>
          </button>
        ))}
      </div>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Quick-start templates</div>
        <div className="col" style={{ gap: 8 }}>
          {[
            { name: "Warm-up · 600m easy", time: "10 min", focus: "Warm-up" },
            { name: "8x100 Free on 1:30", time: "12 min", focus: "Endurance" },
            { name: "Threshold ladder", time: "28 min", focus: "Speed" },
            { name: "IM technique set", time: "32 min", focus: "Technique" },
          ].map((t, i) => (
            <button key={i} onClick={() => setSubroute("presession")} className="between" style={{ padding: 14, background: "var(--gray-50)", borderRadius: 10, textAlign: "left", width: "100%" }}>
              <div>
                <div style={{ fontWeight: 600 }}>{t.name}</div>
                <div className="row" style={{ gap: 10, marginTop: 4 }}>
                  <Pill tone="aqua">{t.focus}</Pill>
                  <span className="t-caption"><Icon name="clock" size={12}/> {t.time}</span>
                </div>
              </div>
              <Icon name="play" size={16}/>
            </button>
          ))}
        </div>
      </Card>
    </div>
  );
}

function TrainingLog({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Training log" sub="May 2026 · 9 sessions, 32,800m total"
        actions={<Tabs tabs={[{ id: "month", label: "Month" }, { id: "list", label: "List" }]} value="month" onChange={() => {}}/>}
      />

      <Card>
        <div className="row" style={{ marginBottom: 16, gap: 10 }}>
          <button className="btn-icon"><Icon name="chev-left" size={18}/></button>
          <div className="t-h2" style={{ flex: 1, textAlign: "center" }}>May 2026</div>
          <button className="btn-icon"><Icon name="chev-right" size={18}/></button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 6 }}>
          {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => (
            <div key={d} style={{ fontSize: 11, color: "var(--gray-500)", textAlign: "center", padding: 4, fontWeight: 600 }}>{d}</div>
          ))}
          {Array.from({ length: 31 }).map((_, i) => {
            const day = i + 1;
            const intensity = [3, 5, 6, 8, 9, 10, 12, 14].includes(day) ? Math.random() > 0.4 ? "hard" : "easy" : null;
            const isToday = day === 14;
            return (
              <button key={i} className="col" style={{
                aspectRatio: "1", borderRadius: 10, padding: 4,
                background: isToday ? "var(--aqua-50)" : intensity ? "var(--gray-50)" : "transparent",
                border: isToday ? "1.5px solid var(--aqua)" : "1px solid var(--gray-100)",
                color: intensity ? "var(--gray-900)" : "var(--gray-500)",
                alignItems: "center", justifyContent: "center", gap: 4,
              }} onClick={() => setSubroute("postsession")}>
                <div style={{ fontSize: 12, fontWeight: isToday ? 700 : 500 }}>{day}</div>
                {intensity && <div style={{ width: 8, height: 8, borderRadius: "50%", background: intensity === "hard" ? "var(--c-competitive)" : "var(--mint)" }}/>}
              </button>
            );
          })}
        </div>
      </Card>

      <div className="row" style={{ gap: 14, fontSize: 12, color: "var(--gray-600)", padding: "0 4px" }}>
        <div className="row" style={{ gap: 6 }}><div style={{ width: 10, height: 10, background: "var(--mint)", borderRadius: 999 }}/>Easy/aerobic</div>
        <div className="row" style={{ gap: 6 }}><div style={{ width: 10, height: 10, background: "var(--c-competitive)", borderRadius: 999 }}/>Hard/speed</div>
      </div>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Distance over time</div>
        <LineChart values={[2400, 3200, 2800, 4000, 3200, 2200, 3800, 4400, 3600, 3000, 4200, 3200]} labels={["W1","W2","W3","W4","W5","W6","W7","W8","W9","W10","W11","W12"]} color="var(--c-competitive)" height={180}/>
      </Card>
    </div>
  );
}

function PersonalRecords() {
  const [stroke, setStroke] = useState("free");
  const records = [
    { event: "50m Free",  time: "0:27.42", sec: 27.42, std: "F-13-14-50FR-SCY",  date: "Mar 22, 2026" },
    { event: "100m Free", time: "1:00.42", sec: 60.42, std: "F-13-14-100FR-SCY", date: "May 14, 2026", pb: true },
    { event: "200m IM",   time: "2:24.18", sec: 144.18, std: "F-13-14-200IM-SCY", date: "Apr 10, 2026" },
  ];

  // Counts for badge summary
  const counts = { B: 0, BB: 0, A: 0, AA: 0, AAA: 0, AAAA: 0 };
  records.forEach(r => { const ev = evaluateStandard(r.sec, r.std); if (ev?.earned) counts[ev.earned]++; });

  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Personal records" sub="Best times and USA Swimming standards earned"/>

      <Card>
        <div className="t-h2" style={{ marginBottom: 6 }}>Time-standard badges</div>
        <div className="t-caption" style={{ marginBottom: 14 }}>Highest tier earned per event · USA Swimming motivational standards</div>
        <BadgeSummary counts={counts}/>
      </Card>

      <Tabs tabs={[
        { id: "free", label: "Freestyle" },
        { id: "back", label: "Backstroke" },
        { id: "breast", label: "Breaststroke" },
        { id: "fly", label: "Butterfly" },
        { id: "im", label: "IM" },
      ]} value={stroke} onChange={setStroke}/>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Records & standards</div>
        <BadgeCollection swimmer={records}/>
      </Card>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>100m Freestyle progression</div>
        <LineChart values={[78, 76, 74, 73, 72, 71, 70, 70, 69, 68, 61.4, 60.4]} labels={["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"]} color="var(--gold)" height={180}/>
      </Card>
    </div>
  );
}

function WorkoutTemplates({ setSubroute }) {
  const [tab, setTab] = useState("all");
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Workout templates"
        actions={<Button variant="primary" icon="plus">New template</Button>}/>
      <Tabs tabs={[
        { id: "all", label: "All" }, { id: "warm", label: "Warm-up" }, { id: "end", label: "Endurance" },
        { id: "spd", label: "Speed" }, { id: "tech", label: "Technique" }, { id: "cool", label: "Cool-down" },
        { id: "fav", label: "★ Favorites" },
      ]} value={tab} onChange={setTab}/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
        {[
          { name: "Speed pyramid", focus: "Speed", time: "62 min", distance: "3,200m", sets: 14 },
          { name: "Endurance cruise", focus: "Endurance", time: "82 min", distance: "4,000m", sets: 6 },
          { name: "IM technique set", focus: "Technique", time: "55 min", distance: "2,400m", sets: 12 },
          { name: "Threshold ladder", focus: "Speed", time: "48 min", distance: "2,800m", sets: 16 },
          { name: "Long warm-up", focus: "Warm-up", time: "15 min", distance: "800m", sets: 4 },
          { name: "Easy cool-down", focus: "Cool-down", time: "10 min", distance: "400m", sets: 2 },
        ].map((w, i) => (
          <Card key={i} onClick={() => setSubroute("presession")} style={{ cursor: "pointer" }}>
            <Pill tone={w.focus === "Speed" ? "amber" : w.focus === "Endurance" ? "aqua" : w.focus === "Technique" ? "mint" : "default"}>{w.focus}</Pill>
            <div className="t-h2" style={{ marginTop: 10, fontSize: 17 }}>{w.name}</div>
            <div className="row" style={{ gap: 14, marginTop: 12, color: "var(--gray-600)", fontSize: 13 }}>
              <div className="row" style={{ gap: 4 }}><Icon name="clock" size={14}/>{w.time}</div>
              <div className="row" style={{ gap: 4 }}><Icon name="wave" size={14}/>{w.distance}</div>
              <div className="row" style={{ gap: 4 }}><Icon name="ladder" size={14}/>{w.sets} sets</div>
            </div>
            <Button variant="ghost" full style={{ marginTop: 12 }}><Icon name="play" size={14}/>Start workout</Button>
          </Card>
        ))}
      </div>
    </div>
  );
}

function RaceSimulation({ setSubroute }) {
  return (
    <div className="col" style={{ gap: 16, maxWidth: 720 }}>
      <PageHeader title="Race simulation" sub="Pace yourself against a target time"/>

      <Card style={{ background: "linear-gradient(135deg, #2a2014, var(--navy-900))", color: "white" }}>
        <Pill tone="navy" style={{ background: "rgba(255,255,255,0.18)", color: "white" }}>Goal</Pill>
        <div className="t-h1" style={{ color: "white", marginTop: 10 }}>Beat 1:05.00 — 100m Free</div>
        <div style={{ color: "rgba(255,255,255,0.7)", marginTop: 4 }}>Your PB: 1:07.42 · Pacer ghost will swim 1:05.00 even-split.</div>
      </Card>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Set your target</div>
        <div className="col" style={{ gap: 14 }}>
          <div className="field"><label>Distance</label><select className="select"><option>100m</option><option>200m</option><option>400m</option></select></div>
          <div className="field"><label>Stroke</label><select className="select"><option>Freestyle</option></select></div>
          <div className="field"><label>Target time</label>
            <div className="row" style={{ gap: 8 }}>
              <input className="input" style={{ fontFamily: "var(--f-mono)", textAlign: "center" }} defaultValue="01"/>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 22 }}>:</span>
              <input className="input" style={{ fontFamily: "var(--f-mono)", textAlign: "center" }} defaultValue="05"/>
              <span style={{ fontFamily: "var(--f-mono)", fontSize: 22 }}>.</span>
              <input className="input" style={{ fontFamily: "var(--f-mono)", textAlign: "center" }} defaultValue="00"/>
            </div>
          </div>
          <div className="field">
            <label>Pacer strategy</label>
            <div className="row" style={{ gap: 8 }}>
              {["Even split", "Negative split", "Front-load"].map(s => (
                <button key={s} className="btn btn-sm" style={{ flex: 1, background: s === "Even split" ? "var(--navy)" : "white", color: s === "Even split" ? "white" : "var(--gray-700)", border: `1px solid ${s === "Even split" ? "var(--navy)" : "var(--gray-300)"}` }}>{s}</button>
              ))}
            </div>
          </div>
          <div className="between" style={{ padding: "10px 0", borderTop: "1px solid var(--gray-200)" }}>
            <div><div style={{ fontWeight: 600 }}>Audio cues</div><div className="t-caption">Beep at halfway, 75%, last 25m</div></div>
            <Toggle on={true} onChange={() => {}}/>
          </div>
        </div>
      </Card>

      <Button variant="primary" size="lg" full onClick={() => setSubroute("active")}>Start race simulation</Button>
    </div>
  );
}

function GoalTracker() {
  return (
    <div className="col" style={{ gap: 16 }}>
      <PageHeader title="Goals" actions={<Button variant="primary" icon="plus">New goal</Button>}/>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 12 }}>
        {[
          { name: "Sub 1:05 — 100m Free", pct: 45, sub: "Current: 1:07.42 · 2.4s to go", color: "var(--c-competitive)" },
          { name: "12k weekly volume", pct: 78, sub: "9,400 / 12,000 m this week", color: "var(--aqua)" },
          { name: "Daily streak (30 days)", pct: 47, sub: "Day 14 / 30", color: "var(--c-recreation)" },
          { name: "VO2 sets weekly", pct: 62, sub: "5 / 8 sessions this month", color: "var(--mint)" },
        ].map((g, i) => (
          <Card key={i}>
            <div className="between" style={{ marginBottom: 14 }}>
              <div className="t-h3">{g.name}</div>
              <button className="btn-icon"><Icon name="more" size={16}/></button>
            </div>
            <div className="row" style={{ gap: 14, alignItems: "center" }}>
              <ProgressRing pct={g.pct} size={72} color={g.color}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, color: "var(--gray-600)" }}>{g.sub}</div>
              </div>
            </div>
          </Card>
        ))}
      </div>

      <Card>
        <div className="t-h2" style={{ marginBottom: 14 }}>Streak history</div>
        <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
          {Array.from({ length: 90 }).map((_, i) => {
            const has = Math.random() > 0.35;
            return <div key={i} title={`Day ${i+1}`} style={{ width: 22, height: 22, borderRadius: 4, background: has ? "var(--mint)" : "var(--gray-200)", opacity: has ? 0.3 + Math.random() * 0.7 : 1 }}/>;
          })}
        </div>
        <div className="row" style={{ marginTop: 12, fontSize: 12, color: "var(--gray-600)", gap: 14 }}>
          <div><span className="t-mono-sm" style={{ fontWeight: 700, color: "var(--c-recreation)" }}>14 days</span> current</div>
          <div><span className="t-mono-sm" style={{ fontWeight: 700 }}>21 days</span> longest</div>
        </div>
      </Card>
    </div>
  );
}

function SwimmerProfile() {
  return (
    <div className="col" style={{ gap: 16, maxWidth: 720 }}>
      <PageHeader title="Profile"/>
      <Card>
        <div className="row" style={{ gap: 16, flexWrap: "wrap" }}>
          <Avatar name="Alex Rivera" size="lg"/>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div className="t-h1">Alex Rivera</div>
            <div className="muted">Competitive swimmer · Aqua Center · Lane 4</div>
            <div className="row" style={{ marginTop: 10, gap: 6, flexWrap: "wrap" }}>
              <Pill tone="aqua">Senior Open</Pill>
              <Pill tone="mint">Distance specialist</Pill>
              <Pill tone="amber">USA Swimming</Pill>
            </div>
          </div>
          <Button variant="secondary" icon="edit">Edit</Button>
        </div>
      </Card>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
        <StatCard label="Total distance" value="248 km" sub="Lifetime" accent="var(--aqua)"/>
        <StatCard label="Total sessions" value="284" accent="var(--c-competitive)"/>
        <StatCard label="Avg per week" value="12.1 km" accent="var(--mint)"/>
        <StatCard label="Member since" value="2 years" accent="var(--navy)"/>
      </div>
    </div>
  );
}

Object.assign(window, { CompetitivePortal });
