// Student Home — two age variations + theme-aware
// Single component, age & theme as props. Built to live inside a 1400x900 artboard.

const STUDENT_TABS = [["Home","/app/student"],["Schedule","/app/student/schedule"],["Courses","/app/student/courses"],["Quests","/app/student/quiz"],["Forum","/app/student/forum"],["Shop","/app/student/shop"]];
const TopBar = ({ name = "", level = 1, xp = 0, xpMax = 500, streak = 0, coins = 0, theme, go, route = "/app/student" }) => (
  <div style={{
    display: "flex", alignItems: "center", gap: 16, padding: "14px 22px",
    background: "var(--paper-card)", borderBottom: "var(--border)",
  }}>
    <div className="display" style={{ fontSize: 22, letterSpacing: "-0.03em" }}>
      <span style={{ color: "var(--coral)" }}>code</span><span>land</span><span style={{ color: "var(--ink-mute)", fontWeight: 400 }}>/</span>
    </div>
    <div style={{ display: "flex", gap: 4 }}>
      {STUDENT_TABS.map(([t, path]) => {
        const active = path && route === path;
        return (
          <button key={t} onClick={() => path && go && go(path)} style={{
            padding: "8px 14px", borderRadius: "var(--r-pill)",
            background: active ? "var(--ink)" : "transparent",
            color: active ? "var(--paper-card)" : "var(--ink-soft)",
            border: "none", fontWeight: 700, fontSize: 13, cursor: "pointer",
          }}>{t}</button>
        );
      })}
    </div>
    <div style={{ flex: 1 }}/>
    <div className="chip" style={{ background: "var(--gold)" }}>
      <span style={{ width: 16, height: 16, display: "grid", placeItems: "center" }}>{I.flame({ size: 16 })}</span>
      {streak} day streak
    </div>
    <div className="chip">
      <span style={{ color: "var(--gold-deep)" }}>{I.coin({ size: 16 })}</span>
      {coins}
    </div>
    <div className="chip" style={{ padding: 4, paddingRight: 12, cursor: "pointer" }} onClick={() => go && go("/app/student/profile")}>
      <Avatar name={name[0]} color="var(--plum)" size={26}/>
      <span style={{ fontSize: 13 }}>{name}</span>
    </div>
  </div>
);

// Adventure path — round nodes connected by chunky lines
const AdventurePath = ({ age }) => {
  const nodes = [
    { id: 1, label: "Loops", state: "done", icon: I.code },
    { id: 2, label: "If/Else", state: "done", icon: I.puzzle },
    { id: 3, label: "Functions", state: "current", icon: I.bolt2 },
    { id: 4, label: "Lists", state: "next", icon: I.book },
    { id: 5, label: "Boss", state: "locked", icon: I.shield },
  ];
  const size = age === "older" ? 56 : 72;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
      {nodes.map((n, i) => (
        <React.Fragment key={n.id}>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
            <div style={{
              width: size, height: size, borderRadius: "50%",
              background: n.state === "done" ? "var(--moss)"
                       : n.state === "current" ? "var(--coral)"
                       : n.state === "next" ? "var(--paper-card)" : "var(--paper-deep)",
              color: n.state === "locked" ? "var(--ink-mute)" : (n.state === "next" ? "var(--ink)" : "white"),
              border: "2px solid var(--rule-bold)",
              boxShadow: n.state === "current" ? "var(--sh-3)" : "var(--sh-2)",
              display: "grid", placeItems: "center",
              position: "relative",
              transform: n.state === "current" ? "translateY(-4px)" : "none",
            }}>
              {n.state === "locked" ? I.lock({ size: size * 0.4 }) : n.icon({ size: size * 0.42 })}
              {n.state === "current" && (
                <span style={{
                  position: "absolute", top: -10, right: -10,
                  background: "var(--gold)", borderRadius: "50%", width: 24, height: 24,
                  border: "1.5px solid var(--rule-bold)", display: "grid", placeItems: "center",
                  fontSize: 10, fontWeight: 800,
                }}>!</span>
              )}
            </div>
            <div style={{ fontSize: 12, fontWeight: 700, color: n.state === "locked" ? "var(--ink-mute)" : "var(--ink)" }}>{n.label}</div>
          </div>
          {i < nodes.length - 1 && (
            <div style={{
              flex: 1, height: 4, marginTop: -22, minWidth: 28,
              background: n.state === "done" ? "var(--moss)" : "var(--paper-deep)",
              border: "1.5px solid var(--rule-bold)",
              borderRadius: 2,
              backgroundImage: n.state === "done" ? "none" : "repeating-linear-gradient(90deg, transparent 0 6px, var(--rule) 6px 8px)",
            }}/>
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

// Join class card — big hero, countdown
const JoinClassCard = ({ age }) => {
  const [time, setTime] = React.useState("14:32");
  React.useEffect(() => {
    let t = 14*60 + 32;
    const id = setInterval(() => {
      t = Math.max(0, t - 1);
      const m = String(Math.floor(t/60)).padStart(2,"0");
      const s = String(t%60).padStart(2,"0");
      setTime(`${m}:${s}`);
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="card" style={{
      padding: age === "older" ? 22 : 26,
      background: "var(--paper-card)",
      position: "relative", overflow: "hidden",
    }}>
      {/* Decorative stripes */}
      <div style={{
        position: "absolute", right: -40, top: -40, width: 220, height: 220,
        background: "var(--coral)", borderRadius: "50%", opacity: 0.18,
      }}/>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="pill" style={{ background: "var(--moss)", color: "white", padding: "4px 10px", fontSize: 11 }}>● LIVE SOON</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>Mon · 7:00 PM IST</span>
      </div>
      <div className="display" style={{ fontSize: age === "older" ? 30 : 36, marginTop: 10, lineHeight: 1.05 }}>
        Lesson 12 · <span style={{ color: "var(--coral)" }}>Loops that draw shapes</span>
      </div>
      <div style={{ marginTop: 8, color: "var(--ink-soft)", fontSize: 14, maxWidth: 460 }}>
        Today we'll make a turtle draw a square, then a snowflake. Bring your warm-up doodles!
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 18 }}>
        <button className="btn btn-primary" style={{ fontSize: 15, padding: "12px 22px" }}>
          {I.play({ size: 18 })} Join class
        </button>
        <div style={{ display: "flex", flexDirection: "column" }}>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)" }}>STARTS IN</div>
          <div className="display" style={{ fontSize: 22 }}>{time}</div>
        </div>
        <div style={{ flex: 1 }}/>
        <div style={{ display: "flex", alignItems: "center", gap: -8 }}>
          {["A", "R", "K"].map((n, i) => (
            <div key={i} style={{ marginLeft: i ? -8 : 0 }}>
              <Avatar name={n} color={["var(--sky)","var(--plum)","var(--moss)"][i]} size={28}/>
            </div>
          ))}
          <span style={{ marginLeft: 6, fontSize: 12, color: "var(--ink-soft)", fontWeight: 600 }}>4 in class</span>
        </div>
      </div>
    </div>
  );
};

// Parse "7:00 PM" on "2026-06-10" into a Date
const parseClassTime = (day, timeStr) => {
  if (!day || !timeStr) return null;
  const m = timeStr.match(/^(\d+):(\d+)\s*(AM|PM)$/i);
  if (!m) return null;
  let h = parseInt(m[1]), min = parseInt(m[2]);
  if (m[3].toUpperCase() === "PM" && h !== 12) h += 12;
  if (m[3].toUpperCase() === "AM" && h === 12) h = 0;
  const d = new Date(day + "T00:00:00");
  d.setHours(h, min, 0, 0);
  return d;
};

const fmtClassDate = d => {
  if (!d) return "";
  try { return new Date(d + "T00:00:00").toLocaleDateString("en-GB", { weekday:"short", day:"numeric", month:"short" }); }
  catch { return d; }
};

const NextClassCard = ({ nextClass, nextClassAfter }) => {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);

  const startTime = parseClassTime(nextClass?.day, nextClass?.time);
  const endTime   = parseClassTime(nextClass?.day, nextClass?.end);

  if (!startTime) return null;

  const secsToStart = Math.floor((startTime - now) / 1000);
  const secsToEnd   = endTime ? Math.floor((endTime - now) / 1000) : null;

  const isEnded      = secsToEnd !== null && secsToEnd <= 0;
  const isInProgress = !isEnded && secsToStart <= 0;
  const inWindow     = !isEnded && secsToStart <= 15 * 60; // within 15-min window
  const canJoin      = !isEnded && secsToStart <= 5 * 60 && !!nextClass.meet;

  const fmtSecs = s => {
    const abs = Math.max(0, s);
    const m = Math.floor(abs / 60), sec = abs % 60;
    return `${String(m).padStart(2,"0")}:${String(sec).padStart(2,"0")}`;
  };

  // After class ended — show next session info
  if (isEnded) {
    return (
      <div className="card" style={{ padding: 22, background: "var(--ink)", color: "white", position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: -40, right: -40, width: 160, height: 160, borderRadius: "50%", background: "rgba(255,255,255,.05)" }}/>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ padding: "3px 10px", borderRadius: 999, background: "var(--rule)", color: "white", fontSize: 11, fontWeight: 700 }}>CLASS ENDED</span>
        </div>
        <div className="display" style={{ fontSize: 20, opacity: .6 }}>{nextClass.course}</div>
        {nextClassAfter ? (
          <div style={{ marginTop: 14, padding: "12px 16px", borderRadius: 10, background: "rgba(255,255,255,.07)" }}>
            <div style={{ fontSize: 10, fontWeight: 700, opacity: .6, letterSpacing: ".08em", marginBottom: 4 }}>NEXT CLASS</div>
            <div className="display" style={{ fontSize: 18 }}>{nextClassAfter.course}</div>
            <div style={{ fontSize: 13, opacity: .7, marginTop: 4 }}>{fmtClassDate(nextClassAfter.day)} · {nextClassAfter.time}</div>
          </div>
        ) : (
          <div style={{ marginTop: 14, fontSize: 13, opacity: .6 }}>No more upcoming classes scheduled</div>
        )}
      </div>
    );
  }

  // Active card — before class or in progress
  const statusLabel = isInProgress ? "● LIVE NOW" : "LIVE SOON";
  const statusBg    = isInProgress ? "var(--coral)" : "var(--moss)";

  return (
    <div className="card" style={{ padding: 22, background: "var(--ink)", color: "white", position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: -40, right: -40, width: 160, height: 160, borderRadius: "50%", background: "rgba(255,255,255,.05)" }}/>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
        <span style={{ padding: "3px 10px", borderRadius: 999, background: statusBg, color: "white", fontSize: 11, fontWeight: 700 }}>{statusLabel}</span>
        <span style={{ fontSize: 12, opacity: .7 }}>{fmtClassDate(nextClass.day)} · {nextClass.time}</span>
      </div>
      <div className="display" style={{ fontSize: 24 }}>{nextClass.course}</div>
      <div style={{ fontSize: 13, opacity: .7, marginTop: 4, marginBottom: 16 }}>{nextClass.batch}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
        {nextClass.meet ? (
          <a
            href={canJoin ? nextClass.meet : undefined}
            onClick={canJoin ? undefined : e => e.preventDefault()}
            target="_blank" rel="noreferrer"
            style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "11px 22px", borderRadius: 999, fontSize: 14, fontWeight: 700,
              background: canJoin ? "var(--coral)" : "rgba(255,255,255,.15)",
              color: "white", textDecoration: "none",
              cursor: canJoin ? "pointer" : "not-allowed",
              opacity: canJoin ? 1 : 0.6,
              transition: "background .2s, opacity .2s",
            }}
          >
            {I.play({ size: 16 })} Join class
          </a>
        ) : (
          <span style={{ fontSize: 13, opacity: .5 }}>No meeting link yet</span>
        )}
        {isInProgress ? (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ fontSize: 10, fontWeight: 700, opacity: .6, letterSpacing: ".08em" }}>IN PROGRESS</div>
            {secsToEnd !== null && <div className="display" style={{ fontSize: 22, color: "var(--coral)" }}>{fmtSecs(secsToEnd)} left</div>}
          </div>
        ) : inWindow ? (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ fontSize: 10, fontWeight: 700, opacity: .6, letterSpacing: ".08em" }}>
              {canJoin ? "JOIN NOW — STARTS IN" : "STARTS IN"}
            </div>
            <div className="display" style={{ fontSize: 28, color: canJoin ? "var(--coral)" : "white" }}>{fmtSecs(secsToStart)}</div>
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ fontSize: 10, fontWeight: 700, opacity: .6, letterSpacing: ".08em" }}>SCHEDULED</div>
            <div style={{ fontSize: 14, opacity: .9, marginTop: 2 }}>{fmtClassDate(nextClass.day)} · {nextClass.time}</div>
          </div>
        )}
      </div>
    </div>
  );
};

const StudentHome = ({ theme = "", age = "younger", go, session, route = "/app/student" }) => {
  const sid = session?.studentId;
  const { data: dash, loading } = useApi(sid ? `/student/dashboard/${sid}` : "/student/dashboard/0", {});
  const student        = dash.student        || {};
  const leaderboard    = dash.leaderboard    || [];
  const nextClass      = dash.nextClass      || null;
  const nextClassAfter = dash.nextClassAfter || null;
  const hwStats        = dash.homework       || {};
  const xp         = student.xp || 0;
  const level      = Math.floor(xp / 500) + 1;
  const xpInLevel  = xp % 500;
  const days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  const today = days[new Date().getDay()];

  if (loading) return <Spinner />;
  return (
  <Themed theme={theme} style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column" }}>
    <TopBar go={go} route={route} name={student.name || session?.name || ""} xp={xpInLevel} xpMax={500} level={level} streak={0} coins={xp}/>
    <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18, padding: 22, flex: 1, background: "var(--paper)", overflow: "auto" }}>
      {/* MAIN COLUMN */}
      <div style={{ display: "flex", flexDirection: "column", gap: 18, minWidth: 0 }}>
        {/* Greeting */}
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          {age === "younger" && <Mascot size={86} variant={theme || "default"}/>}
          <div style={{ flex: 1 }}>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-mute)", letterSpacing: ".08em" }}>{today.toUpperCase()} · {student.batch || "No batch yet"}</div>
            <h1 className="display" style={{ fontSize: age === "older" ? 36 : 44, margin: "4px 0 0", lineHeight: 1 }}>
              Hey {student.name ? student.name.split(" ")[0] : session?.name?.split(" ")[0] || "there"} — <span style={{ color: "var(--coral)" }}>let's code!</span>
            </h1>
            <div style={{ color: "var(--ink-soft)", marginTop: 6, fontSize: 14 }}>
              {student.course_name ? `${student.course_name} · ${student.course_level}` : "No course assigned yet"}
              {student.teacher ? ` · ${student.teacher}` : ""}
            </div>
          </div>
          <div style={{ width: 220 }}>
            <XPBar value={xpInLevel} max={500} level={level}/>
          </div>
        </div>

        {/* Next class */}
        {nextClass ? (
          <NextClassCard nextClass={nextClass} nextClassAfter={nextClassAfter}/>
        ) : (
          <div className="card" style={{ padding: 22, textAlign: "center", color: "var(--ink-mute)" }}>
            <div style={{ fontSize: 28, marginBottom: 8 }}>📅</div>
            <div style={{ fontWeight: 700 }}>No upcoming classes</div>
            <div style={{ fontSize: 13, marginTop: 4 }}>Your schedule will appear here once sessions are added</div>
          </div>
        )}

        {/* Quick links */}
        <div>
          <SectionHead eyebrow="QUICK ACCESS" title="Go to"/>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            {[
              { title: "My Courses",  sub: student.course_name || "View content", icon: I.book,   color: "var(--coral)", path: "/app/student/courses" },
              { title: "Quizzes",     sub: "Test your knowledge", icon: I.puzzle, color: "var(--sky)",   path: "/app/student/quiz" },
              { title: "Homework",    sub: hwStats.pending > 0 ? `${hwStats.pending} pending` : "All done!", icon: I.check, color: hwStats.pending > 0 ? "var(--gold)" : "var(--moss)", path: "/app/student/homework" },
              { title: "Forum",       sub: "Ask questions",       icon: I.users,  color: "var(--plum)",  path: "/app/student/forum" },
              { title: "Certificates",sub: "My achievements",     icon: I.trophy, color: "var(--gold)",  path: "/app/student/certificates" },
              { title: "My Progress", sub: "Course map",          icon: I.chart,  color: "var(--moss)",  path: "/app/student/courses" },
            ].map((q, i) => (
              <div key={i} onClick={() => go && go(q.path)} className="card" style={{ padding: 14, cursor: "pointer" }}>
                <div style={{ width: 38, height: 38, borderRadius: 12, background: q.color, color: "white", border: "1.5px solid var(--rule-bold)", boxShadow: "var(--sh-1)", display: "grid", placeItems: "center", marginBottom: 10 }}>
                  {q.icon({ size: 20 })}
                </div>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{q.title}</div>
                <div style={{ fontSize: 12, color: "var(--ink-mute)" }}>{q.sub}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* SIDE COLUMN */}
      <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
        {/* Leaderboard */}
        <div className="card" style={{ padding: 16 }}>
          <SectionHead eyebrow="BATCH LEADERBOARD" title="Top students"/>
          {leaderboard.length === 0 ? (
            <div style={{ color: "var(--ink-mute)", fontSize: 13, padding: "12px 0" }}>No classmates yet</div>
          ) : leaderboard.map((p, i) => (
            <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 10, marginTop: 4, background: p.id === sid ? "var(--paper-deep)" : "transparent", border: p.id === sid ? "1.5px solid var(--rule-bold)" : "1.5px solid transparent" }}>
              <div style={{ width: 22, height: 22, borderRadius: "50%", background: i < 3 ? "var(--ink)" : "transparent", color: i < 3 ? "var(--paper-card)" : "var(--ink-soft)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800 }}>{p.rank}</div>
              <Avatar name={p.name[0]} color={p.color || "var(--coral)"} size={28}/>
              <div style={{ flex: 1, fontSize: 13, fontWeight: p.id === sid ? 700 : 500 }}>
                {p.name.split(" ")[0]} {p.id === sid && <span style={{ color: "var(--coral)", fontSize: 10 }}>YOU</span>}
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--ink-soft)" }}>{p.xp} XP</div>
            </div>
          ))}
        </div>

        {/* XP summary */}
        <div className="card" style={{ padding: 16 }}>
          <SectionHead eyebrow="MY PROGRESS" title="Stats"/>
          {[
            ["Total XP", xp],
            ["Level", level],
            ["Batch", student.batch || "—"],
            ["Course", student.course_name ? `${student.course_name} · ${student.course_level}` : "—"],
            ["Teacher", student.teacher || "—"],
          ].map(([l, v]) => (
            <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: "var(--border-thin)", fontSize: 13 }}>
              <span style={{ color: "var(--ink-mute)" }}>{l}</span>
              <span style={{ fontWeight: 700 }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  </Themed>
  );
};

// ── Student Schedule ───────────────────────────────────────────────────────────
const SCHED_ATTEND_COLOR = {
  present:    "var(--moss)",
  late:       "var(--gold)",
  missed:     "var(--coral)",
  tech_issue: "var(--sky)",
  pending:    "var(--rule-bold)",
  absent:     "var(--coral)",
};
const SCHED_ATTEND_LABEL = {
  present: "Present", late: "Late", missed: "Missed",
  tech_issue: "Tech Issue", pending: "Pending", absent: "Absent",
};

const StudentSchedule = ({ go, session }) => {
  const studentId = session?.studentId || session?.student_id;
  const { data: sessions, loading } = useApi(studentId ? `/student/schedule/${studentId}` : null);

  const fmtDate = d => {
    if (!d) return "—";
    try { return new Date(d + "T00:00:00").toLocaleDateString("en-GB",{ weekday:"short", day:"numeric", month:"short", year:"numeric" }); }
    catch { return d; }
  };

  const upcoming = (sessions||[]).filter(s => s.status === "upcoming" || s.status === "live");
  const past     = (sessions||[]).filter(s => s.status === "done");

  const SessionRow = ({ s }) => {
    const attendColor = SCHED_ATTEND_COLOR[s.attendance] || "var(--rule-bold)";
    const attendLabel = SCHED_ATTEND_LABEL[s.attendance] || s.attendance;
    return (
      <div style={{
        display:"grid", gridTemplateColumns:"130px 1fr 1fr 100px 100px",
        alignItems:"center", gap:12, padding:"14px 20px",
        borderBottom:"var(--border-thin)",
      }}>
        <div>
          <div style={{ fontWeight:700, fontSize:13 }}>{fmtDate(s.day)}</div>
          <div style={{ fontSize:11, color:"var(--ink-mute)", marginTop:2 }}>{s.time}{s.time_end ? ` – ${s.time_end}` : ""}</div>
        </div>
        <div>
          <div style={{ fontWeight:700, fontSize:13 }}>{s.course}</div>
          <div style={{ fontSize:11, color:"var(--ink-mute)", marginTop:2 }}>{s.batch}</div>
        </div>
        <div style={{ fontSize:12, color:"var(--ink-mute)" }}>{s.batch}</div>
        <span style={{
          display:"inline-block", padding:"4px 10px", borderRadius:8,
          background: s.status==="live" ? "var(--coral)" : s.status==="done" ? "var(--paper-deep)" : "var(--paper-deep)",
          color: s.status==="live" ? "white" : "var(--ink-mute)",
          fontSize:11, fontWeight:700, textAlign:"center",
        }}>{s.status==="live" ? "Live now" : s.status==="done" ? "Done" : "Upcoming"}</span>
        <span style={{
          display:"inline-block", padding:"4px 10px", borderRadius:8,
          background: attendColor, color:"white",
          fontSize:11, fontWeight:700, textAlign:"center",
          opacity: s.status !== "done" ? 0.45 : 1,
        }}>{s.status === "done" ? attendLabel : "—"}</span>
      </div>
    );
  };

  return (
    <Themed style={{ width:"100%", height:"100%", display:"flex", flexDirection:"column" }}>
      <TopBar name={session?.name||""} go={go} route="/app/student/schedule"/>
      <div style={{ flex:1, overflow:"auto", padding:24 }}>
        {loading && <div style={{ padding:40, textAlign:"center", color:"var(--ink-mute)" }}>Loading…</div>}
        {!loading && !studentId && <div style={{ padding:40, textAlign:"center", color:"var(--ink-mute)" }}>Student profile not found.</div>}

        {!loading && !!studentId && (
          <>
            {/* Stats row */}
            <div style={{ display:"flex", gap:14, marginBottom:24 }}>
              {[
                { l:"Total sessions", v:(sessions||[]).length, c:"var(--ink)" },
                { l:"Present",  v:(sessions||[]).filter(s=>s.attendance==="present").length,  c:"var(--moss)" },
                { l:"Late",     v:(sessions||[]).filter(s=>s.attendance==="late").length,     c:"var(--gold)" },
                { l:"Missed",   v:(sessions||[]).filter(s=>s.attendance==="missed").length,   c:"var(--coral)" },
                { l:"Tech Issue",v:(sessions||[]).filter(s=>s.attendance==="tech_issue").length,c:"var(--sky)" },
              ].map(k => (
                <div key={k.l} className="card-flat" style={{ flex:1, padding:"14px 18px" }}>
                  <div className="mono" style={{ fontSize:10, color:"var(--ink-mute)", letterSpacing:".06em" }}>{k.l.toUpperCase()}</div>
                  <div className="display" style={{ fontSize:28, marginTop:4, color:k.c }}>{k.v}</div>
                </div>
              ))}
            </div>

            {/* Column headers */}
            <div style={{ display:"grid", gridTemplateColumns:"130px 1fr 1fr 100px 100px", gap:12, padding:"8px 20px", marginBottom:4 }}>
              {["Date","Course","Batch","Status","Attendance"].map(h => (
                <div key={h} className="mono" style={{ fontSize:10, color:"var(--ink-mute)", letterSpacing:".06em" }}>{h.toUpperCase()}</div>
              ))}
            </div>

            {/* Upcoming */}
            {upcoming.length > 0 && (
              <div className="card-flat" style={{ marginBottom:16, overflow:"hidden" }}>
                <div style={{ padding:"10px 20px", background:"var(--paper-deep)", borderBottom:"var(--border-thin)" }}>
                  <span className="mono" style={{ fontSize:11, fontWeight:700 }}>UPCOMING ({upcoming.length})</span>
                </div>
                {upcoming.map(s => <SessionRow key={s.id} s={s}/>)}
              </div>
            )}

            {/* Past */}
            {past.length > 0 && (
              <div className="card-flat" style={{ overflow:"hidden" }}>
                <div style={{ padding:"10px 20px", background:"var(--paper-deep)", borderBottom:"var(--border-thin)" }}>
                  <span className="mono" style={{ fontSize:11, fontWeight:700 }}>PAST SESSIONS ({past.length})</span>
                </div>
                {past.map(s => <SessionRow key={s.id} s={s}/>)}
              </div>
            )}

            {!loading && !(sessions||[]).length && (
              <div style={{ padding:60, textAlign:"center", color:"var(--ink-mute)" }}>
                <div style={{ fontSize:32, marginBottom:8 }}>📅</div>
                <div style={{ fontWeight:700 }}>No sessions scheduled yet</div>
                <div style={{ fontSize:13, marginTop:4 }}>Sessions will appear here once added by your teacher.</div>
              </div>
            )}
          </>
        )}
      </div>
    </Themed>
  );
};

window.StudentHome = StudentHome;
window.StudentSchedule = StudentSchedule;

