// Coach web dashboard — sidebar nav + multiple views
const { useState: cUseState, useMemo: cUseMemo } = React;

// ────────────── Coach wallpaper (lighter for web) ──────────────
function CoachWallpaper({ variant }) {
  return variant === "pure"
    ? <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(180deg, #FBF7F0 0%, #F4ECDC 100%)",
      }}><div style={{
        position: "absolute", top: -200, right: -200, width: 600, height: 600,
        borderRadius: "50%", filter: "blur(120px)", opacity: 0.25,
        background: "radial-gradient(circle, #FFB627, transparent 70%)",
      }} /></div>
    : <div style={{
        position: "absolute", inset: 0,
        background: "linear-gradient(135deg, #FFF3E0 0%, #FAF5EE 50%, #F1E4CB 100%)",
      }}>
        <div style={{
          position: "absolute", top: -300, right: -200, width: 800, height: 800,
          borderRadius: "50%", filter: "blur(120px)", opacity: 0.55,
          background: "radial-gradient(circle, #FFB36B, transparent 65%)",
        }} />
        <div style={{
          position: "absolute", bottom: -400, left: -200, width: 900, height: 900,
          borderRadius: "50%", filter: "blur(140px)", opacity: 0.4,
          background: "radial-gradient(circle, #FF8C5A, transparent 65%)",
        }} />
        <div style={{
          position: "absolute", top: "30%", left: "40%", width: 500, height: 500,
          borderRadius: "50%", filter: "blur(120px)", opacity: 0.35,
          background: "radial-gradient(circle, #FFD89B, transparent 65%)",
        }} />
      </div>;
}

// ────────────── Sidebar ──────────────
function Sidebar({ view, setView, athleteOpen, setAthleteOpen }) {
  const items = [
    { id: "roster", label: "Roster", icon: Ic.Users, count: 8 },
    { id: "calendar", label: "Calendar", icon: Ic.Calendar },
    { id: "plans", label: "Plan builder", icon: Ic.Library },
    { id: "analytics", label: "Analytics", icon: Ic.Trend },
    { id: "messages", label: "Messages", icon: Ic.Chat, count: 3 },
  ];
  return (
    <div className="glass" style={{
      width: 248, margin: 14, marginRight: 0, borderRadius: 24,
      padding: "20px 14px", display: "flex", flexDirection: "column", gap: 4,
      position: "relative", zIndex: 2,
    }}>
      {/* Brand */}
      <div style={{ padding: "4px 10px 16px", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 10,
          background: "linear-gradient(135deg, #FF6B35, #FF3B30)",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 2px 8px rgba(255,107,53,0.25), inset 0 1px 0 rgba(255,255,255,0.3)",
        }}>
          <div style={{ width: 14, height: 14, borderRadius: 7, border: "2.5px solid white", borderRightColor: "transparent", transform: "rotate(-45deg)" }} />
        </div>
        <div>
          <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: -0.4, lineHeight: 1 }}>Run</div>
          <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>Coach · M. Webb</div>
        </div>
      </div>

      {/* Nav */}
      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {items.map(item => {
          const active = view === item.id && !athleteOpen;
          return (
            <button key={item.id}
              onClick={() => { setAthleteOpen(null); setView(item.id); }}
              style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "9px 12px", borderRadius: 12, textAlign: "left",
                background: active ? "rgba(255,107,53,0.12)" : "transparent",
                color: active ? "var(--accent)" : "var(--ink-2)",
                fontSize: 13.5, fontWeight: active ? 600 : 500,
                position: "relative",
              }}>
              <item.icon size={18} color={active ? "var(--accent)" : "var(--ink-2)"} />
              <span style={{ flex: 1 }}>{item.label}</span>
              {item.count && (
                <span style={{
                  fontSize: 10, fontWeight: 700, padding: "2px 6px", borderRadius: 8,
                  background: active ? "var(--accent)" : "rgba(28,25,23,0.08)",
                  color: active ? "#fff" : "var(--ink-3)",
                }}>{item.count}</span>
              )}
            </button>
          );
        })}
      </div>

      {/* Section: Athletes */}
      <div style={{ padding: "18px 12px 6px", fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.6 }}>
        ATHLETES
      </div>
      <div style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
        {RUN_DATA.roster.slice(0, 6).map((a, i) => (
          <button key={i} onClick={() => { setView("roster"); setAthleteOpen(i); }}
            style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "7px 10px", borderRadius: 10, textAlign: "left",
              background: athleteOpen === i ? "rgba(28,25,23,0.05)" : "transparent",
              fontSize: 13,
            }}>
            <div style={{ width: 26, height: 26, borderRadius: 13, background: a.avatar, flexShrink: 0 }} />
            <span style={{ flex: 1, color: "var(--ink-2)", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{a.name}</span>
            <span style={{
              width: 6, height: 6, borderRadius: 3,
              background: a.status === "green" ? "#30D158" : a.status === "yellow" ? "#FFB627" : "#FF3B30",
            }} />
          </button>
        ))}
      </div>

      <div style={{ marginTop: 10, padding: "10px 12px", borderTop: "0.5px solid var(--line)", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 28, height: 28, borderRadius: 14, background: "linear-gradient(135deg, #C8431A, #FF6B35)" }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Marcus Webb</div>
          <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Boulder Track Club</div>
        </div>
        <Ic.Settings size={16} color="var(--ink-3)" />
      </div>
    </div>
  );
}

// ────────────── Topbar ──────────────
function Topbar({ title, subtitle, right }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "18px 24px 14px",
    }}>
      <div>
        {subtitle && <div style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-3)", letterSpacing: 0.4 }}>{subtitle}</div>}
        <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.6, lineHeight: 1.1 }}>{title}</div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>{right}</div>
    </div>
  );
}

function SearchPill({ placeholder = "Search…" }) {
  return (
    <div className="glass" style={{
      display: "flex", alignItems: "center", gap: 8,
      padding: "8px 14px", borderRadius: 999, width: 260,
      fontSize: 13, color: "var(--ink-3)",
    }}>
      <Ic.Search size={15} color="var(--ink-3)" />
      <span style={{ flex: 1 }}>{placeholder}</span>
      <span style={{
        padding: "1px 6px", borderRadius: 4,
        background: "rgba(28,25,23,0.08)", fontSize: 10, fontWeight: 600,
      }}>⌘K</span>
    </div>
  );
}

function GBtn({ children, primary, onClick, style }) {
  return (
    <button onClick={onClick} style={{
      padding: "8px 14px", borderRadius: 12, fontSize: 13, fontWeight: 600,
      display: "inline-flex", alignItems: "center", gap: 6,
      background: primary ? "var(--ink)" : "rgba(255,252,245,0.6)",
      color: primary ? "#fff" : "var(--ink-2)",
      backdropFilter: primary ? "none" : "blur(20px)",
      WebkitBackdropFilter: primary ? "none" : "blur(20px)",
      border: primary ? "none" : "0.5px solid rgba(28,25,23,0.08)",
      boxShadow: primary ? "0 1px 0 rgba(255,255,255,0.1) inset, 0 4px 12px rgba(28,25,23,0.18)" : "none",
      ...style,
    }}>{children}</button>
  );
}

// ════════════════════════════════════════════════════════════════════
// ROSTER VIEW
// ════════════════════════════════════════════════════════════════════
function RosterView({ onOpenAthlete }) {
  const roster = RUN_DATA.roster;
  const greenCount = roster.filter(a => a.status === "green").length;
  const yellowCount = roster.filter(a => a.status === "yellow").length;
  const redCount = roster.filter(a => a.status === "red").length;

  return (
    <div style={{ padding: "0 24px 24px", overflowY: "auto", height: "100%" }}>
      <Topbar
        subtitle="THURSDAY · MAY 15 · WEEK 14 OF 26"
        title="My athletes"
        right={
          <>
            <SearchPill placeholder="Find athlete…" />
            <GBtn><Ic.Filter size={14} color="var(--ink-2)" /> Filter</GBtn>
            <GBtn primary><Ic.Plus size={14} color="#fff" /> Invite</GBtn>
          </>
        }
      />

      {/* Summary cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 18 }}>
        <SummaryCard label="ROSTER" value="8" sub="3 elite · 3 sub-elite · 2 development" />
        <SummaryCard label="STATUS" value={
          <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
            <span style={{ color: "#1A7A36" }}>{greenCount}</span>
            <span style={{ fontSize: 14, color: "var(--ink-3)", fontWeight: 500 }}>/</span>
            <span style={{ color: "#A36B00", fontSize: 18 }}>{yellowCount}</span>
            <span style={{ color: "#B0211B", fontSize: 18 }}>{redCount}</span>
          </div>
        } sub="green · caution · over" />
        <SummaryCard label="LOAD AVG" value="76" sub="ATL · trending +3% wk" />
        <SummaryCard label="UNREAD" value="3" sub="from Jordan, Sophie, Aïsha" highlight />
      </div>

      {/* Roster table */}
      <GlassCard radius={20} style={{ overflow: "hidden" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "2fr 1fr 1.2fr 1.5fr 1fr 1fr 60px",
          padding: "12px 18px", fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4,
          borderBottom: "0.5px solid var(--line)",
        }}>
          <div>ATHLETE</div>
          <div>GROUP</div>
          <div>LAST RUN</div>
          <div>LOAD (ATL)</div>
          <div>TREND</div>
          <div>NEXT RACE</div>
          <div></div>
        </div>
        {roster.map((a, i) => (
          <button key={i} onClick={() => onOpenAthlete(i)} style={{
            display: "grid", gridTemplateColumns: "2fr 1fr 1.2fr 1.5fr 1fr 1fr 60px",
            padding: "14px 18px", fontSize: 13, alignItems: "center", textAlign: "left",
            borderBottom: i < roster.length - 1 ? "0.5px solid var(--line)" : "none",
            width: "100%", color: "inherit",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 16, background: a.avatar, position: "relative" }}>
                <div style={{
                  position: "absolute", bottom: -1, right: -1, width: 10, height: 10, borderRadius: 5,
                  background: a.status === "green" ? "#30D158" : a.status === "yellow" ? "#FFB627" : "#FF3B30",
                  border: "2px solid var(--bg-0)",
                }} />
              </div>
              <div>
                <div style={{ fontWeight: 600 }}>{a.name}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{a.races[0]}</div>
              </div>
            </div>
            <div style={{ color: "var(--ink-2)" }}>{a.group}</div>
            <div style={{ color: "var(--ink-2)" }}>{a.lastRun}</div>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span className="tabnum" style={{ fontWeight: 600, color: a.load > 100 ? "var(--accent-3)" : a.load > 90 ? "var(--accent-2)" : "var(--ink)" }}>{a.load}</span>
                <div style={{ flex: 1, height: 4, borderRadius: 2, background: "rgba(28,25,23,0.06)", maxWidth: 100 }}>
                  <div style={{
                    width: `${Math.min(a.load, 110) / 110 * 100}%`, height: "100%", borderRadius: 2,
                    background: a.load > 100 ? "var(--accent-3)" : a.load > 90 ? "var(--accent-2)" : "var(--accent)",
                  }} />
                </div>
              </div>
            </div>
            <div className="tabnum" style={{ color: a.trend > 0 ? "#1A7A36" : a.trend < 0 ? "var(--accent-3)" : "var(--ink-3)", fontWeight: 600 }}>
              {a.trend > 0 ? `▲ +${a.trend}` : a.trend < 0 ? `▼ ${a.trend}` : "—"}
            </div>
            <div className="tabnum" style={{ color: "var(--ink-2)" }}>{a.nextRace}</div>
            <Ic.Chevron size={14} color="var(--ink-4)" />
          </button>
        ))}
      </GlassCard>
    </div>
  );
}

function SummaryCard({ label, value, sub, highlight }) {
  return (
    <GlassCard radius={18} style={{ padding: "14px 16px", position: "relative", overflow: "hidden" }}>
      {highlight && <div style={{
        position: "absolute", left: 0, top: 0, bottom: 0, width: 3,
        background: "var(--accent)",
      }} />}
      <div style={{ fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.5 }}>{label}</div>
      <div className="tabnum" style={{ fontSize: 26, fontWeight: 700, marginTop: 4, letterSpacing: -0.5, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>{sub}</div>
    </GlassCard>
  );
}

// ════════════════════════════════════════════════════════════════════
// ATHLETE DEEP-DIVE
// ════════════════════════════════════════════════════════════════════
function AthleteDetail({ idx, onBack }) {
  const a = RUN_DATA.roster[idx];
  const t = RUN_DATA.trends;
  return (
    <div style={{ padding: "0 24px 24px", overflowY: "auto", height: "100%" }}>
      <Topbar
        subtitle={<button onClick={onBack} style={{ display: "flex", alignItems: "center", gap: 4, color: "var(--ink-3)", fontSize: 11, fontWeight: 600, letterSpacing: 0.4 }}><Ic.ChevronLeft size={12} color="var(--ink-3)" /> BACK TO ROSTER</button>}
        title={a.name}
        right={
          <>
            <GBtn><Ic.Chat size={14} color="var(--ink-2)" /> Message</GBtn>
            <GBtn><Ic.Mic size={14} color="var(--ink-2)" /> Voice note</GBtn>
            <GBtn primary><Ic.Plus size={14} color="#fff" /> Add session</GBtn>
          </>
        }
      />

      {/* Profile band */}
      <GlassCard radius={22} style={{ padding: 20, marginBottom: 14, display: "flex", alignItems: "center", gap: 18 }}>
        <div style={{ width: 72, height: 72, borderRadius: 36, background: a.avatar, flexShrink: 0,
          boxShadow: "0 4px 14px rgba(0,0,0,0.08)" }} />
        <div style={{ flex: 1, display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 18 }}>
          <Metric label="GROUP" value={a.group} />
          <Metric label="5K PR" value="18:42" />
          <Metric label="10K PR" value="39:18" />
          <Metric label="NEXT RACE" value={a.races[0]} sub={`in ${a.nextRace}`} />
          <Metric label="STATUS" value={<Pill tone={a.status === "green" ? "green" : a.status === "yellow" ? "amber" : "red"}>{a.status.toUpperCase()}</Pill>} />
        </div>
      </GlassCard>

      {/* Charts row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 14, marginBottom: 14 }}>
        {/* Load over time */}
        <GlassCard radius={20} style={{ padding: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4 }}>FITNESS / FATIGUE</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 4 }}>ATL 86 · CTL 78 · Form +8</div>
            </div>
            <div style={{ display: "flex", gap: 14, fontSize: 11, color: "var(--ink-3)" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{ width: 8, height: 2, background: "var(--accent)" }} /> Fitness
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{ width: 8, height: 2, background: "var(--accent-3)" }} /> Fatigue
              </span>
            </div>
          </div>
          <FitnessChart />
        </GlassCard>

        {/* Pace progression */}
        <GlassCard radius={20} style={{ padding: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4 }}>5K PACE TREND</div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.4, marginTop: 4 }} className="tabnum">
            6:01<span style={{ fontSize: 12, color: "#1A7A36", fontWeight: 600, marginLeft: 8 }}>▼ 8s / mi</span>
          </div>
          <PaceChart />
        </GlassCard>

        {/* Race readiness */}
        <GlassCard radius={20} style={{ padding: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4 }}>RACE READINESS</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 2 }}>Boulder 10K · 28d</div>
          <div style={{ marginTop: 14, display: "flex", alignItems: "center", justifyContent: "center" }}>
            <ReadinessRing value={86} />
          </div>
          <div style={{ marginTop: 12, fontSize: 11, color: "var(--ink-3)", textAlign: "center" }}>
            Projected target: <span style={{ color: "var(--accent)", fontWeight: 600 }}>38:40 — 39:10</span>
          </div>
        </GlassCard>
      </div>

      {/* AI recommendation */}
      <GlassCard radius={20} style={{ padding: 18, marginBottom: 14, display: "flex", gap: 14 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 12, flexShrink: 0,
          background: "linear-gradient(135deg, #FF6B35, #FFB627)", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 4px 12px rgba(255,107,53,0.25)",
        }}>
          <Ic.Sparkle size={20} color="#fff" />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: 0.4 }}>AI · WEEKLY RECOMMENDATION</div>
          <div style={{ fontSize: 14, color: "var(--ink), marginTop: 4", lineHeight: 1.5 }}>
            Maya's recovery is strong (HRV +4 days, ATL/CTL ratio 1.10). Consider <span style={{ color: "var(--accent)", fontWeight: 600 }}>nudging Saturday's tempo to 6:45/mi</span> from 6:50, and adding a 6th rep to Tuesday's 1K set. Hold long-run volume — high but in band.
          </div>
          <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
            <GBtn primary>Apply suggestions</GBtn>
            <GBtn>Modify</GBtn>
            <GBtn>Dismiss</GBtn>
          </div>
        </div>
      </GlassCard>

      {/* Recent sessions */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14 }}>
        <GlassCard radius={20} style={{ padding: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: -0.2 }}>Recent sessions</div>
            <button style={{ fontSize: 12, color: "var(--accent)", fontWeight: 600 }}>View all</button>
          </div>
          {RUN_DATA.week.filter(d => d.status === "done").map((s, i, arr) => (
            <div key={i} style={{
              padding: "10px 0", display: "flex", alignItems: "center", gap: 14,
              borderBottom: i < arr.length - 1 ? "0.5px solid var(--line)" : "none",
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                background: s.type === "Speed" ? "rgba(255,107,53,0.12)" : s.type === "Long" ? "rgba(255,59,48,0.12)" : "rgba(255,182,39,0.16)",
                color: s.type === "Speed" ? "var(--accent)" : s.type === "Long" ? "var(--accent-3)" : "var(--accent-2)",
                display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 700,
              }}>{s.day.slice(0,3).toUpperCase()}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{s.title}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{s.actual}</div>
              </div>
              <Pill tone="green"><Ic.Check size={11} color="#1A7A36" /> Hit target</Pill>
            </div>
          ))}
        </GlassCard>

        <GlassCard radius={20} style={{ padding: 18 }}>
          <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 14 }}>Training heatmap</div>
          <Heatmap />
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: "0.5px solid var(--line)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            <Metric label="49-DAY CONSISTENCY" value="94%" />
            <Metric label="MO. DISTANCE" value="162 mi" />
          </div>
        </GlassCard>
      </div>
    </div>
  );
}

function Metric({ label, value, sub }) {
  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4 }}>{label}</div>
      <div style={{ fontSize: 17, fontWeight: 700, marginTop: 2, letterSpacing: -0.3 }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function FitnessChart() {
  // 8 weeks of data
  const fit = [62, 65, 68, 72, 74, 76, 77, 78];
  const fat = [55, 60, 58, 65, 62, 68, 64, 42];
  const max = 90;
  const w = 280, h = 100;
  const stepX = w / (fit.length - 1);
  const toPath = (arr) => arr.map((v, i) => `${i === 0 ? 'M' : 'L'} ${i * stepX} ${h - (v / max) * h}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: 110, marginTop: 6 }}>
      <defs>
        <linearGradient id="fit-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FF6B35" stopOpacity="0.3" />
          <stop offset="100%" stopColor="#FF6B35" stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={`${toPath(fit)} L ${w} ${h} L 0 ${h} Z`} fill="url(#fit-grad)" />
      <path d={toPath(fit)} stroke="#FF6B35" strokeWidth="2" fill="none" strokeLinecap="round" />
      <path d={toPath(fat)} stroke="#FF3B30" strokeWidth="2" fill="none" strokeLinecap="round" strokeDasharray="3 3" />
      {fit.map((v, i) => (
        <circle key={i} cx={i * stepX} cy={h - (v / max) * h} r="2.5" fill="#FF6B35" />
      ))}
    </svg>
  );
}

function PaceChart() {
  // Lower is better (pace)
  const pace = [382, 378, 375, 368, 365, 363, 361, 361]; // seconds
  const min = 355, max = 385;
  const w = 220, h = 70;
  const stepX = w / (pace.length - 1);
  const path = pace.map((v, i) => `${i === 0 ? 'M' : 'L'} ${i * stepX} ${((v - min) / (max - min)) * h}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: 80, marginTop: 8 }}>
      <path d={path} stroke="#1A7A36" strokeWidth="2" fill="none" strokeLinecap="round" />
      {pace.map((v, i) => (
        <circle key={i} cx={i * stepX} cy={((v - min) / (max - min)) * h} r="2.5" fill="#1A7A36" />
      ))}
    </svg>
  );
}

// ════════════════════════════════════════════════════════════════════
// CALENDAR VIEW (week view)
// ════════════════════════════════════════════════════════════════════
function CalendarView() {
  const days = ["Mon May 12", "Tue May 13", "Wed May 14", "Thu May 15", "Fri May 16", "Sat May 17", "Sun May 18"];
  const athletes = RUN_DATA.roster.slice(0, 5);

  return (
    <div style={{ padding: "0 24px 24px", height: "100%", overflowY: "auto", display: "flex", flexDirection: "column" }}>
      <Topbar
        subtitle="WEEK 14 · MAY 12 – 18"
        title="Calendar"
        right={
          <>
            <div style={{ display: "flex", gap: 4 }}>
              <GBtn>←</GBtn>
              <GBtn>This week</GBtn>
              <GBtn>→</GBtn>
            </div>
            <GBtn primary><Ic.Plus size={14} color="#fff" /> Add session</GBtn>
          </>
        }
      />

      <GlassCard radius={20} style={{ flex: 1, overflow: "auto", padding: 0 }}>
        {/* Header row */}
        <div style={{
          display: "grid", gridTemplateColumns: "160px repeat(7, 1fr)",
          borderBottom: "0.5px solid var(--line)", position: "sticky", top: 0,
          background: "rgba(255,252,245,0.92)", backdropFilter: "blur(20px)",
          zIndex: 2,
        }}>
          <div style={{ padding: "12px 14px", fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.5 }}>ATHLETE</div>
          {days.map((d, i) => {
            const isToday = i === 3;
            return (
              <div key={i} style={{
                padding: "12px 10px", fontSize: 11, fontWeight: 600,
                color: isToday ? "var(--accent)" : "var(--ink-3)",
                borderLeft: "0.5px solid var(--line)",
                textAlign: "center",
              }}>
                <div style={{ fontSize: 10, letterSpacing: 0.4 }}>{d.split(" ")[0].toUpperCase()}</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: isToday ? "#fff" : "var(--ink)", marginTop: 4 }}>
                  <span style={{
                    display: "inline-block", padding: isToday ? "1px 8px" : 0,
                    borderRadius: 10, background: isToday ? "var(--accent)" : "transparent",
                  }}>{d.split(" ")[2]}</span>
                </div>
              </div>
            );
          })}
        </div>

        {/* Athletes rows */}
        {athletes.map((a, ai) => (
          <div key={ai} style={{
            display: "grid", gridTemplateColumns: "160px repeat(7, 1fr)",
            borderBottom: ai < athletes.length - 1 ? "0.5px solid var(--line)" : "none",
            minHeight: 92,
          }}>
            <div style={{ padding: "14px", display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 28, height: 28, borderRadius: 14, background: a.avatar, flexShrink: 0 }} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div>
                <div style={{ fontSize: 10, color: "var(--ink-3)" }}>{a.group}</div>
              </div>
            </div>
            {[0,1,2,3,4,5,6].map(di => {
              const session = sampleSession(ai, di);
              return (
                <div key={di} style={{ borderLeft: "0.5px solid var(--line)", padding: 6, position: "relative" }}>
                  {session && (
                    <div style={{
                      padding: "6px 8px", borderRadius: 8, fontSize: 11,
                      background: session.color, color: session.fg,
                      border: `0.5px solid ${session.border}`,
                      cursor: "pointer",
                    }}>
                      <div style={{ fontWeight: 700, letterSpacing: 0.2, fontSize: 9.5, textTransform: "uppercase" }}>{session.type}</div>
                      <div style={{ fontWeight: 600, marginTop: 2 }}>{session.title}</div>
                      <div style={{ marginTop: 2, opacity: 0.75 }}>{session.detail}</div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ))}
      </GlassCard>
    </div>
  );
}

function sampleSession(athleteIdx, dayIdx) {
  // Deterministic distribution
  const matrix = [
    // Mon Tue Wed Thu Fri Sat Sun
    ["easy", "speed", "easy", "speed", null, "long", "easy"],
    ["easy", "tempo", "easy", "speed", null, "long", "rest"],
    [null, "speed", "easy", null, "tempo", "long", "easy"],
    ["easy", "tempo", "rest", "speed", null, "long", "easy"],
    ["easy", "speed", "easy", "tempo", null, "long", "easy"],
  ];
  const t = matrix[athleteIdx]?.[dayIdx];
  if (!t) return null;
  const M = {
    easy: { type: "Easy", title: "5–6 mi", detail: "8:30/mi", color: "rgba(255,182,39,0.10)", fg: "#A36B00", border: "rgba(255,182,39,0.3)" },
    speed: { type: "Speed", title: "8×400", detail: "85s/400", color: "rgba(255,107,53,0.12)", fg: "#C8431A", border: "rgba(255,107,53,0.3)" },
    tempo: { type: "Tempo", title: "4 mi @ T", detail: "6:45/mi", color: "rgba(255,107,53,0.08)", fg: "#C8431A", border: "rgba(255,107,53,0.22)" },
    long: { type: "Long", title: "10–12 mi", detail: "Last 4 fast", color: "rgba(255,59,48,0.10)", fg: "#B0211B", border: "rgba(255,59,48,0.28)" },
    rest: { type: "Rest", title: "Mobility", detail: "—", color: "rgba(28,25,23,0.04)", fg: "var(--ink-3)", border: "rgba(28,25,23,0.08)" },
  };
  return M[t];
}

// ════════════════════════════════════════════════════════════════════
// PLAN BUILDER
// ════════════════════════════════════════════════════════════════════
function PlanBuilder() {
  const w = RUN_DATA.todayWorkout;
  return (
    <div style={{ padding: "0 24px 24px", height: "100%", overflowY: "auto" }}>
      <Topbar
        subtitle="EDITING · 8×400M · ASSIGNED TO 5"
        title="Plan builder"
        right={
          <>
            <GBtn><Ic.Library size={14} color="var(--ink-2)" /> Library</GBtn>
            <GBtn>Save as template</GBtn>
            <GBtn primary>Publish to athletes</GBtn>
          </>
        }
      />

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 14 }}>
        {/* Builder canvas */}
        <GlassCard radius={20} style={{ padding: 20 }}>
          {/* Title row */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, paddingBottom: 16, borderBottom: "0.5px solid var(--line)" }}>
            <Pill tone="accent">SPEED · 5K PACE</Pill>
            <div style={{
              padding: "6px 12px", borderRadius: 10, background: "rgba(255,252,245,0.5)",
              border: "0.5px solid var(--line)", fontSize: 13, fontWeight: 600, flex: 1,
            }}>{w.title}</div>
            <span style={{ fontSize: 12, color: "var(--ink-3)" }}>~57 min · 6.5 mi</span>
          </div>

          {/* Steps */}
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {w.structure.map((s, i) => (
              <div key={i} style={{
                padding: 14, borderRadius: 14, display: "flex", alignItems: "center", gap: 14,
                background: s.isMain ? "rgba(255,107,53,0.08)" : "rgba(255,252,245,0.5)",
                border: `0.5px solid ${s.isMain ? "rgba(255,107,53,0.2)" : "var(--line)"}`,
              }}>
                <div style={{ color: "var(--ink-4)", fontSize: 14, cursor: "grab" }}>⋮⋮</div>
                <div style={{
                  width: 32, height: 32, borderRadius: 10,
                  background: s.isMain ? "var(--accent)" : "rgba(28,25,23,0.06)",
                  color: s.isMain ? "#fff" : "var(--ink-2)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, fontWeight: 700,
                }}>{i + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{s.label}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{s.detail}</div>
                </div>
                <div style={{ display: "flex", gap: 6 }}>
                  <div style={{ padding: "4px 10px", borderRadius: 8, background: "rgba(28,25,23,0.05)", fontSize: 11, fontWeight: 600 }} className="tabnum">{s.duration}</div>
                  <div style={{ padding: "4px 10px", borderRadius: 8, background: "rgba(28,25,23,0.05)", fontSize: 11, fontWeight: 600 }} className="tabnum">{s.pace}</div>
                </div>
                <button style={{ color: "var(--ink-4)" }}>×</button>
              </div>
            ))}
            <button style={{
              padding: 14, borderRadius: 14, display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
              border: "1px dashed var(--line-2)", color: "var(--ink-3)", fontSize: 13, fontWeight: 600,
              background: "transparent",
            }}>
              <Ic.Plus size={16} color="var(--ink-3)" /> Add step
            </button>
          </div>

          {/* Coach note */}
          <div style={{ marginTop: 18, paddingTop: 18, borderTop: "0.5px solid var(--line)" }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4, marginBottom: 8 }}>COACH NOTE</div>
            <div style={{
              padding: 14, borderRadius: 14, background: "rgba(255,252,245,0.5)",
              border: "0.5px solid var(--line)", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5,
            }}>"{w.coachNote}"</div>
            <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
              <GBtn><Ic.Mic size={13} color="var(--ink-2)" /> Record voice note</GBtn>
            </div>
          </div>
        </GlassCard>

        {/* Right rail */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <GlassCard radius={20} style={{ padding: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4, marginBottom: 12 }}>ASSIGN TO</div>
            {RUN_DATA.roster.slice(0, 5).map((a, i) => (
              <label key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", cursor: "pointer" }}>
                <input type="checkbox" defaultChecked={i < 5} style={{ accentColor: "#FF6B35" }} />
                <div style={{ width: 24, height: 24, borderRadius: 12, background: a.avatar, flexShrink: 0 }} />
                <span style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{a.name}</span>
                <span style={{ fontSize: 10, color: "var(--ink-3)" }}>{a.group}</span>
              </label>
            ))}
          </GlassCard>

          <GlassCard radius={20} style={{ padding: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-3)", letterSpacing: 0.4, marginBottom: 10 }}>SCHEDULE</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)" }}>Thursday · May 15</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>4:00 PM · Boulder HS Track</div>
            <div style={{ marginTop: 12, display: "flex", gap: 6, flexWrap: "wrap" }}>
              {["Auto-adjust", "Reminders", "Sync to watches"].map(t => (
                <Pill key={t} tone="neutral">{t}</Pill>
              ))}
            </div>
          </GlassCard>

          <GlassCard radius={20} style={{ padding: 18 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <Ic.Sparkle size={14} color="var(--accent)" />
              <div style={{ fontSize: 11, fontWeight: 700, color: "var(--accent)", letterSpacing: 0.4 }}>AI SUGGESTION</div>
            </div>
            <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.45 }}>
              Jordan's load is at 104 — consider dropping him to <b>6×400</b> or substituting an easy day.
            </div>
            <GBtn style={{ marginTop: 10, width: "100%", justifyContent: "center" }}>Apply variation for Jordan</GBtn>
          </GlassCard>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// ANALYTICS VIEW
// ════════════════════════════════════════════════════════════════════
function AnalyticsView() {
  return (
    <div style={{ padding: "0 24px 24px", height: "100%", overflowY: "auto" }}>
      <Topbar
        subtitle="LAST 12 WEEKS · ALL ATHLETES"
        title="Team analytics"
        right={
          <>
            <GBtn>This season</GBtn>
            <GBtn><Ic.Filter size={14} color="var(--ink-2)" /> Group</GBtn>
            <GBtn primary>Export</GBtn>
          </>
        }
      />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 14 }}>
        <SummaryCard label="TEAM MILEAGE" value="284 mi" sub="this week · ▲ 4%" />
        <SummaryCard label="AVG LOAD" value="76" sub="ATL · band 60–90" />
        <SummaryCard label="ON-TARGET" value="87%" sub="of planned sessions" />
        <SummaryCard label="AT RISK" value="1" sub="Jordan Reyes · load 104" highlight />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 14, marginBottom: 14 }}>
        <GlassCard radius={20} style={{ padding: 20 }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Team weekly mileage</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>Sum across all 8 athletes</div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              {["12w", "6m", "1y"].map((p, i) => (
                <button key={p} style={{
                  padding: "4px 10px", borderRadius: 8, fontSize: 11, fontWeight: 600,
                  background: i === 0 ? "var(--ink)" : "transparent", color: i === 0 ? "#fff" : "var(--ink-3)",
                  border: i === 0 ? "none" : "0.5px solid var(--line)",
                }}>{p}</button>
              ))}
            </div>
          </div>
          <TeamMileageChart />
        </GlassCard>

        <GlassCard radius={20} style={{ padding: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Load distribution</div>
          <div style={{ fontSize: 11, color: "var(--ink-3)", marginBottom: 14 }}>Current ATL across roster</div>
          {RUN_DATA.roster.map((a, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
              <div style={{ width: 18, height: 18, borderRadius: 9, background: a.avatar, flexShrink: 0 }} />
              <div style={{ flex: 1, fontSize: 11, fontWeight: 600 }}>{a.name.split(" ")[0]}</div>
              <div style={{ flex: 2, height: 5, borderRadius: 3, background: "rgba(28,25,23,0.06)", overflow: "hidden" }}>
                <div style={{
                  width: `${Math.min(a.load, 110) / 110 * 100}%`, height: "100%",
                  background: a.load > 100 ? "var(--accent-3)" : a.load > 90 ? "var(--accent-2)" : "var(--accent)",
                  borderRadius: 3,
                }} />
              </div>
              <div className="tabnum" style={{ fontSize: 11, fontWeight: 600, color: "var(--ink-2)", width: 26, textAlign: "right" }}>{a.load}</div>
            </div>
          ))}
        </GlassCard>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <GlassCard radius={20} style={{ padding: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 14 }}>Team heatmap · last 7 weeks</div>
          <Heatmap />
          <div style={{ marginTop: 14, display: "flex", gap: 16, fontSize: 11, color: "var(--ink-3)" }}>
            <Metric label="ACTIVE DAYS" value="42/49" />
            <Metric label="TEAM CONSISTENCY" value="86%" />
            <Metric label="HARD DAYS" value="14" />
          </div>
        </GlassCard>

        <GlassCard radius={20} style={{ padding: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
            <Ic.Sparkle size={14} color="var(--accent)" />
            <div style={{ fontSize: 13, fontWeight: 700 }}>AI insights</div>
          </div>
          {[
            { color: "var(--accent-3)", title: "Jordan: 3-day load spike", body: "ATL 104 with HRV dropping — recommend rest or substitution Thursday." },
            { color: "var(--accent-2)", title: "Sophie peaking nicely", body: "Form rising into Boulder 5K (14d). Maintain volume; sharpen Wednesday." },
            { color: "#1A7A36", title: "Aïsha streak: 6 PRs in 6 weeks", body: "Confidence + consistency strong. Consider testing 1500m PR." },
          ].map((insight, i) => (
            <div key={i} style={{ padding: "12px 0", borderTop: i > 0 ? "0.5px solid var(--line)" : "none" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 6, height: 6, borderRadius: 3, background: insight.color }} />
                <div style={{ fontSize: 12, fontWeight: 700 }}>{insight.title}</div>
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4, lineHeight: 1.45 }}>{insight.body}</div>
            </div>
          ))}
        </GlassCard>
      </div>
    </div>
  );
}

function TeamMileageChart() {
  const data = [228, 245, 252, 268, 274, 261, 278, 286, 271, 282, 274, 284];
  const max = 300;
  const w = 500, h = 140;
  const stepX = w / (data.length - 1);
  const path = data.map((v, i) => `${i === 0 ? 'M' : 'L'} ${i * stepX} ${h - (v / max) * h}`).join(" ");
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: 150 }}>
      <defs>
        <linearGradient id="team-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#FF6B35" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#FF6B35" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* gridlines */}
      {[0.25, 0.5, 0.75].map(g => (
        <line key={g} x1="0" x2={w} y1={h * g} y2={h * g} stroke="rgba(28,25,23,0.06)" strokeDasharray="2 4" />
      ))}
      <path d={`${path} L ${w} ${h} L 0 ${h} Z`} fill="url(#team-grad)" />
      <path d={path} stroke="#FF6B35" strokeWidth="2" fill="none" strokeLinecap="round" />
      {data.map((v, i) => (
        <circle key={i} cx={i * stepX} cy={h - (v / max) * h} r="3" fill="#FFF5EE" stroke="#FF6B35" strokeWidth="1.5" />
      ))}
    </svg>
  );
}

// ════════════════════════════════════════════════════════════════════
// MESSAGES VIEW (coach side)
// ════════════════════════════════════════════════════════════════════
function CoachMessagesView() {
  const [selected, setSelected] = cUseState(0);
  const conversations = RUN_DATA.roster.map((a, i) => ({
    ...a,
    lastMsg: i === 0 ? "Got it. Heading to the track at 4." :
             i === 1 ? "Saw the long run notes — quick Q on Sat" :
             i === 2 ? "Felt great today, ready for tomorrow!" :
             i === 3 ? "Hamstring still tight after Tuesday." :
             "Thanks coach 🙌",
    unread: i === 1 || i === 3 || i === 4,
    when: i === 0 ? "9:18 AM" : i === 1 ? "8:34 AM" : i === 2 ? "Y'day" : i === 3 ? "Y'day" : "2d",
  }));

  return (
    <div style={{ padding: "0 24px 24px", height: "100%", display: "flex", flexDirection: "column" }}>
      <Topbar
        subtitle="3 UNREAD"
        title="Messages"
        right={<><SearchPill placeholder="Search messages…" /><GBtn primary><Ic.Mic size={14} color="#fff" /> Voice broadcast</GBtn></>}
      />
      <GlassCard radius={20} style={{ flex: 1, overflow: "hidden", display: "grid", gridTemplateColumns: "280px 1fr" }}>
        {/* Conv list */}
        <div style={{ borderRight: "0.5px solid var(--line)", overflowY: "auto" }}>
          {conversations.map((c, i) => (
            <button key={i} onClick={() => setSelected(i)} style={{
              width: "100%", padding: "14px 16px", display: "flex", gap: 12, textAlign: "left",
              background: selected === i ? "rgba(255,107,53,0.06)" : "transparent",
              borderBottom: "0.5px solid var(--line)", position: "relative",
            }}>
              {selected === i && <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--accent)" }} />}
              <div style={{ width: 38, height: 38, borderRadius: 19, background: c.avatar, flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 2 }}>
                  <div style={{ fontSize: 13, fontWeight: c.unread ? 700 : 600 }}>{c.name}</div>
                  <div style={{ fontSize: 10, color: "var(--ink-3)" }}>{c.when}</div>
                </div>
                <div style={{
                  fontSize: 12, color: c.unread ? "var(--ink-2)" : "var(--ink-3)",
                  fontWeight: c.unread ? 500 : 400,
                  whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis",
                }}>{c.lastMsg}</div>
              </div>
              {c.unread && <div style={{ width: 8, height: 8, borderRadius: 4, background: "var(--accent)", marginTop: 8 }} />}
            </button>
          ))}
        </div>

        {/* Thread */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
          <div style={{ padding: "14px 20px", borderBottom: "0.5px solid var(--line)", display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 18, background: conversations[selected].avatar }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>{conversations[selected].name}</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{conversations[selected].group} · {conversations[selected].races[0]} in {conversations[selected].nextRace}</div>
            </div>
            <GBtn><Ic.User size={14} color="var(--ink-2)" /> Profile</GBtn>
          </div>
          <div style={{ flex: 1, overflowY: "auto", padding: 20, display: "flex", flexDirection: "column", gap: 8 }}>
            {RUN_DATA.messages.map((m, i) => {
              const isMe = m.from !== "me"; // flipped on coach side — "me" in athlete data is coach
              // actually: in coach view, "coach" = me, "me" (athlete) = them
              const fromCoach = m.from === "coach";
              return (
                <div key={i} style={{ display: "flex", justifyContent: fromCoach ? "flex-end" : "flex-start" }}>
                  <div style={{
                    maxWidth: "70%", padding: "10px 14px", borderRadius: 18,
                    background: fromCoach ? "var(--accent)" : "rgba(255,252,245,0.85)",
                    backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
                    color: fromCoach ? "#fff" : "var(--ink)",
                    border: fromCoach ? "none" : "0.5px solid var(--line)",
                    fontSize: 13.5, lineHeight: 1.45,
                  }}>
                    {m.voice ? (
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Ic.Play size={16} color={fromCoach ? "#fff" : "var(--accent)"} />
                        <div style={{ display: "flex", gap: 1.5 }}>
                          {[6,9,12,8,14,10,16,7,12,10,14,8,11,9,13,6,10,8].map((h, idx) => (
                            <div key={idx} style={{ width: 2, height: h, borderRadius: 1, background: fromCoach ? "rgba(255,255,255,0.7)" : "var(--ink-3)" }} />
                          ))}
                        </div>
                        <span className="tabnum" style={{ fontSize: 11 }}>{m.duration}</span>
                      </div>
                    ) : m.text}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ padding: 16, borderTop: "0.5px solid var(--line)", display: "flex", gap: 8, alignItems: "center" }}>
            <button style={{ width: 36, height: 36, borderRadius: 18, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)" }}>
              <Ic.Plus size={18} color="var(--ink-3)" />
            </button>
            <div style={{
              flex: 1, padding: "10px 14px", borderRadius: 16,
              background: "rgba(255,252,245,0.6)", border: "0.5px solid var(--line)",
              fontSize: 13, color: "var(--ink-3)",
            }}>Message Maya…</div>
            <button style={{
              width: 36, height: 36, borderRadius: 18, background: "var(--accent)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}><Ic.Send size={16} color="#fff" /></button>
            <button style={{
              width: 36, height: 36, borderRadius: 18,
              background: "rgba(255,252,245,0.6)", border: "0.5px solid var(--line)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}><Ic.Mic size={16} color="var(--ink-2)" /></button>
          </div>
        </div>
      </GlassCard>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════
// Coach App shell
// ════════════════════════════════════════════════════════════════════
function CoachApp({ variant }) {
  const [view, setView] = cUseState("roster");
  const [athleteOpen, setAthleteOpen] = cUseState(null);

  let content;
  if (view === "roster" && athleteOpen !== null) content = <AthleteDetail idx={athleteOpen} onBack={() => setAthleteOpen(null)} />;
  else if (view === "roster") content = <RosterView onOpenAthlete={i => setAthleteOpen(i)} />;
  else if (view === "calendar") content = <CalendarView />;
  else if (view === "plans") content = <PlanBuilder />;
  else if (view === "analytics") content = <AnalyticsView />;
  else if (view === "messages") content = <CoachMessagesView />;

  return (
    <div style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden", display: "flex" }}>
      <CoachWallpaper variant={variant} />
      <div style={{ position: "relative", zIndex: 1, display: "flex", width: "100%", height: "100%" }}>
        <Sidebar view={view} setView={setView} athleteOpen={athleteOpen} setAthleteOpen={setAthleteOpen} />
        <div style={{ flex: 1, padding: 14, paddingLeft: 14, minWidth: 0, display: "flex" }}>
          <GlassCard radius={24} style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>
            {content}
          </GlassCard>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CoachApp });
