// Student views: dashboard, sessions list, session detail, my-classes
// Generalized so admin/teacher can also view any student
const { useState: useStateSt } = React;
const US = window.UI;
const ASS = US.A;
const MS = window.MOCK;
const { PageHeader: PHS } = window.Shell;

// Get a student object (default = the logged-in student)
const getStudent = (id) =>
  MS.STUDENTS.find((s) => s.id === id) || MS.STUDENT_USER;

// Generalized panel — used by:
//  - student looking at themselves
//  - teacher/admin looking at any student (optionally scoped to their classes)
const StudentPanel = ({
  studentId,
  scopeClasses,
  onOpenSession,
  hideHeader,
}) => {
  const student = MS.STUDENTS.find((s) => s.id === studentId) || MS.STUDENT_USER || { name: "", id: "", classes: [] };
  const visibleClasses = scopeClasses
    ? (student.classes || []).filter((c) => scopeClasses.includes(c))
    : (student.classes || []);
  // Prefer per-student cache (filled by App.openStudent for admin/teacher).
  // Fallback to MS.SESSIONS (used for the logged-in student's own view).
  const sessions = (MS._studentSessions && MS._studentSessions[studentId]) || MS.SESSIONS || [];
  const byType = (MS._studentByType && MS._studentByType[studentId]) || (MS._byType || []);
  const last = sessions[0];
  const hasSessions = sessions.length > 0;
  // Score delta over the period: difference between most recent and oldest session.
  // Only show the badge when there's a meaningful trend (≥ 2 sessions and non-zero diff).
  const scoreDelta = sessions.length >= 2
    ? sessions[0].score - sessions[sessions.length - 1].score
    : 0;

  return (
    <>
      {!hideHeader && (
        <PHS
          title={`Olá, ${(student.name || "").split(" ")[0] || "aluno"}.`}
          subtitle="Acompanhe seu desempenho nas simulações de inspeção visual."
        />
      )}

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 14,
          marginBottom: 18,
        }}
        className="metric-grid"
      >
        <US.Glass>
          <US.Metric
            label="Última pontuação"
            value={last ? last.score : "—"}
            sub={last ? last.date : "sem sessões"}
            icon="target"
            accent={ASS.green}
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Média geral"
            value={student.avgScore ? `${student.avgScore}%` : "—"}
            sub={`${student.sessions || 0} sessões`}
            icon="chart"
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Cobertura média"
            value={hasSessions ? `${Math.round(sessions.reduce((s, x) => s + (x.coverage || 0), 0) / sessions.length)}%` : "—"}
            sub="por zona inspecionada"
            icon="layers"
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Turmas"
            value={visibleClasses.length}
            sub={visibleClasses.join(", ") || "—"}
            icon="classes"
            accent={ASS.gold}
          />
        </US.Glass>
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "2fr 1fr",
          gap: 16,
          marginBottom: 18,
        }}
        className="two-col"
      >
        <US.Glass>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              marginBottom: 14,
            }}
          >
            <div>
              <h3
                style={{
                  margin: 0,
                  fontSize: 15,
                  fontWeight: 600,
                  color: ASS.ink,
                  fontFamily: '"Plus Jakarta Sans", sans-serif',
                }}
              >
                Evolução da pontuação
              </h3>
              <p
                style={{ margin: "2px 0 0", fontSize: 12, color: ASS.inkSoft }}
              >
                {sessions.length === 0
                  ? "Sem sessões registradas ainda"
                  : sessions.length === 1
                  ? "1 sessão registrada"
                  : `Últimas ${sessions.length} simulações`}
              </p>
            </div>
            {scoreDelta !== 0 && (
              <US.Badge tone={scoreDelta > 0 ? "green" : "danger"}>
                {scoreDelta > 0 ? "+" : ""}{scoreDelta} pontos no período
              </US.Badge>
            )}
          </div>
          <US.LineChart
            data={[...sessions].reverse().map((s) => ({ value: s.score }))}
            height={180}
          />
        </US.Glass>
        <US.Glass>
          <h3
            style={{
              margin: "0 0 16px",
              fontSize: 15,
              fontWeight: 600,
              color: ASS.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Tipos de defeito — acerto
          </h3>
          {byType.length > 0 ? (
            <US.StackedBar rows={byType} showLegend={false} />
          ) : (
            <div style={{ padding: "24px 8px", textAlign: "center", fontSize: 13, color: ASS.inkMute }}>
              Sem dados ainda. Os tipos aparecerão após a primeira sessão.
            </div>
          )}
        </US.Glass>
      </div>

      <US.Glass>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 14,
          }}
        >
          <h3
            style={{
              margin: 0,
              fontSize: 15,
              fontWeight: 600,
              color: ASS.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Sessões recentes
          </h3>
          {scopeClasses && (
            <US.Badge tone="primary" size="sm">
              Filtradas por: {scopeClasses.join(", ")}
            </US.Badge>
          )}
        </div>
        <US.Table
          onRowClick={(r) => onOpenSession && onOpenSession(r.id)}
          columns={[
            {
              key: "id",
              label: "ID",
              render: (r) => (
                <span
                  style={{
                    fontFamily: "ui-monospace, Menlo, monospace",
                    fontSize: 12,
                    color: ASS.inkSoft,
                  }}
                >
                  {r.id}
                </span>
              ),
            },
            { key: "date", label: "Data" },
            {
              key: "duration",
              label: "Duração",
              render: (r) => (
                <span style={{ fontVariantNumeric: "tabular-nums" }}>
                  {r.duration}
                </span>
              ),
            },
            {
              key: "found",
              label: "Identificados",
              align: "center",
              render: (r) => (
                <span
                  style={{
                    color: ASS.ok,
                    fontWeight: 600,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {r.found}
                </span>
              ),
            },
            {
              key: "missed",
              label: "Perdidos",
              align: "center",
              render: (r) => (
                <span
                  style={{
                    color: ASS.danger,
                    fontWeight: 600,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {r.missed}
                </span>
              ),
            },
            {
              key: "misidentified",
              label: "Mal id.",
              align: "center",
              render: (r) => (
                <span
                  style={{
                    color: ASS.warn,
                    fontWeight: 600,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {r.misidentified}
                </span>
              ),
            },
            {
              key: "coverage",
              label: "Cobertura",
              render: (r) => (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    minWidth: 110,
                  }}
                >
                  <div
                    style={{
                      flex: 1,
                      height: 5,
                      background: "rgba(0,0,0,0.07)",
                      borderRadius: 3,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        width: `${r.coverage}%`,
                        height: "100%",
                        background: ASS.green,
                      }}
                    />
                  </div>
                  <span
                    style={{ fontSize: 12, fontVariantNumeric: "tabular-nums" }}
                  >
                    {r.coverage}%
                  </span>
                </div>
              ),
            },
            {
              key: "score",
              label: "Nota",
              align: "right",
              render: (r) => (
                <b
                  style={{
                    fontSize: 15,
                    fontVariantNumeric: "tabular-nums",
                    color:
                      r.score >= 85
                        ? ASS.ok
                        : r.score >= 70
                          ? ASS.ink
                          : ASS.warn,
                    fontFamily: '"Plus Jakarta Sans", sans-serif',
                  }}
                >
                  {r.score}
                </b>
              ),
            },
          ]}
          rows={sessions}
        />
      </US.Glass>
    </>
  );
};

// Student-as-self overview
const StudentOverview = ({ onOpenSession }) => (
  <StudentPanel studentId={MS.STUDENT_USER.id} onOpenSession={onOpenSession} />
);

// Admin/Teacher viewing a specific student
const StudentDetail = ({
  studentId,
  scopeClasses,
  onBack,
  onOpenSession,
  viewerRole,
}) => {
  const s = MS.STUDENTS.find((x) => x.id === studentId);
  if (!s) return null;
  const [tab, setTab] = useStateSt("overview");
  const [resetMsg, setResetMsg] = useStateSt(null);
  const [resetBusy, setResetBusy] = useStateSt(false);

  const doReset = async () => {
    if (!window.confirm(`Resetar a senha de ${s.name}? Ele(a) criará uma nova no próximo login.`)) return;
    setResetBusy(true);
    try {
      await window.API.resetUserPassword(s.id);
      setResetMsg({ type: "ok", text: `Senha de ${s.name} foi removida. No próximo login será criada uma nova.` });
    } catch (e) {
      setResetMsg({ type: "err", text: "Erro ao redefinir a senha." });
    } finally { setResetBusy(false); }
  };

  const visibleClasses = scopeClasses
    ? s.classes.filter((c) => scopeClasses.includes(c))
    : s.classes;

  return (
    <>
      <PHS
        breadcrumb={[{ label: "Alunos", onClick: onBack }, { label: s.id }]}
        title={s.name}
        subtitle={
          <span>
            {s.id} · {s.email} · em <b>{visibleClasses.length}</b> turma
            {visibleClasses.length !== 1 ? "s" : ""}:{" "}
            {visibleClasses.join(", ")}
          </span>
        }
        actions={
          viewerRole === "admin"
            ? [
                <US.Button key="r" variant="ghost" icon="lock" onClick={doReset} disabled={resetBusy}>
                  {resetBusy ? "…" : "Resetar senha"}
                </US.Button>,
              ]
            : []
        }
      />

      {resetMsg && (
        <div style={{
          marginBottom: 14, padding: "10px 14px",
          background: resetMsg.type === "ok" ? "rgba(47,122,61,0.08)" : "rgba(184,51,31,0.08)",
          border: `1px solid ${resetMsg.type === "ok" ? "rgba(47,122,61,0.25)" : "rgba(184,51,31,0.2)"}`,
          borderRadius: 8, fontSize: 13,
          color: resetMsg.type === "ok" ? ASS.ok : ASS.danger,
        }}>{resetMsg.text}</div>
      )}

      {scopeClasses && s.classes.length !== visibleClasses.length && (
        <div
          style={{
            marginBottom: 14,
            padding: "10px 14px",
            background: "rgba(221,160,3,0.1)",
            border: "1px solid rgba(221,160,3,0.3)",
            borderRadius: 8,
            fontSize: 12,
            color: "#7a5a00",
            display: "flex",
            gap: 8,
            alignItems: "center",
          }}
        >
          <US.Icon name="info" size={16} />
          Você está vendo somente os dados deste aluno nas <b>suas turmas</b>.
          Outras turmas e dados privados não são exibidos.
        </div>
      )}

      <StudentPanel
        studentId={studentId}
        scopeClasses={scopeClasses}
        onOpenSession={onOpenSession}
        hideHeader
      />
    </>
  );
};

const SessionDetail = ({ id, onBack, fromContext }) => {
  const d = MS.SESSION_DETAIL || { id: "", date: "", startedAt: "", duration: "", scenario: "", score: 0, defects: [], zones: [], events: [] };
  const totalFound = (d.defects || []).reduce((s, x) => s + (x.found || 0), 0);
  const totalMissed = (d.defects || []).reduce((s, x) => s + (x.missed || 0), 0);
  const totalMisId = (d.defects || []).reduce((s, x) => s + (x.misId || 0), 0);
  const totalDef = (d.defects || []).reduce((s, x) => s + (x.total || 0), 0);
  const avgCoverage = (d.zones || []).length > 0
    ? Math.round(d.zones.reduce((s, x) => s + (x.covered || 0), 0) / d.zones.length)
    : 0;

  return (
    <>
      <PHS
        breadcrumb={
          fromContext || [
            { label: "Sessões", onClick: onBack },
            { label: d.id || "—" },
          ]
        }
        title={`Sessão ${d.id || ""}`}
        subtitle={`${d.scenario || ""} · ${d.date || ""}${d.startedAt ? " às " + d.startedAt : ""} · duração ${d.duration || ""}`}
      />

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "auto 1fr 1fr 1fr 1fr",
          gap: 14,
          marginBottom: 18,
          alignItems: "stretch",
        }}
        className="metric-grid"
      >
        <US.Glass
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            minWidth: 180,
          }}
        >
          <div style={{ textAlign: "center" }}>
            <US.Radial
              value={d.score}
              sub="pontuação"
              size={130}
              color={ASS.green}
            />
            <div
              style={{
                fontSize: 11,
                color: ASS.inkMute,
                marginTop: 8,
                fontWeight: 600,
                letterSpacing: "0.04em",
                textTransform: "uppercase",
              }}
            >
              Excelente
            </div>
          </div>
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Defeitos identificados"
            value={`${totalFound}/${totalDef}`}
            sub={`${Math.round((totalFound / totalDef) * 100)}% de acerto`}
            icon="check"
            accent={ASS.ok}
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Mal identificados"
            value={totalMisId}
            sub="defeito errado"
            icon="alert"
            accent={ASS.warn}
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Não identificados"
            value={totalMissed}
            sub="defeitos perdidos"
            icon="x"
            accent={ASS.danger}
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Cobertura média"
            value={`${avgCoverage}%`}
            sub={`${d.zones.length} zonas`}
            icon="layers"
          />
        </US.Glass>
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 16,
          marginBottom: 18,
        }}
        className="two-col"
      >
        <US.Glass>
          <div style={{ marginBottom: 16 }}>
            <h3
              style={{
                margin: 0,
                fontSize: 15,
                fontWeight: 600,
                color: ASS.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Defeitos por categoria
            </h3>
            <p style={{ margin: "2px 0 0", fontSize: 12, color: ASS.inkSoft }}>
              Itens identificados / mal identificados / perdidos
            </p>
          </div>
          <US.StackedBar rows={d.defects} />
        </US.Glass>

        <US.Glass>
          <div style={{ marginBottom: 16 }}>
            <h3
              style={{
                margin: 0,
                fontSize: 15,
                fontWeight: 600,
                color: ASS.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Cobertura por zona
            </h3>
            <p style={{ margin: "2px 0 0", fontSize: 12, color: ASS.inkSoft }}>
              % da zona efetivamente inspecionada
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {d.zones.map((z, i) => (
              <div key={i}>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    fontSize: 13,
                    marginBottom: 4,
                  }}
                >
                  <span style={{ color: ASS.ink, fontWeight: 500 }}>
                    {z.zone}
                  </span>
                  <span
                    style={{
                      fontVariantNumeric: "tabular-nums",
                      fontWeight: 600,
                      color:
                        z.covered >= 95
                          ? ASS.ok
                          : z.covered >= 85
                            ? ASS.ink
                            : ASS.warn,
                    }}
                  >
                    {z.covered}%
                  </span>
                </div>
                <div
                  style={{
                    height: 8,
                    background: "rgba(0,0,0,0.05)",
                    borderRadius: 4,
                    overflow: "hidden",
                    display: "flex",
                  }}
                >
                  <div
                    style={{
                      width: `${z.covered}%`,
                      background:
                        z.covered >= 95
                          ? ASS.ok
                          : z.covered >= 85
                            ? ASS.green
                            : ASS.warn,
                    }}
                  />
                  <div
                    style={{
                      width: `${z.missed}%`,
                      background: "rgba(184,51,31,0.3)",
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        </US.Glass>
      </div>

      <US.Glass>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 14,
          }}
        >
          <div>
            <h3
              style={{
                margin: 0,
                fontSize: 15,
                fontWeight: 600,
                color: ASS.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Linha do tempo da sessão
            </h3>
            <p style={{ margin: "2px 0 0", fontSize: 12, color: ASS.inkSoft }}>
              Eventos registrados durante a inspeção
            </p>
          </div>
          <div
            style={{
              display: "flex",
              gap: 14,
              fontSize: 11,
              color: ASS.inkSoft,
            }}
          >
            <span
              style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
            >
              <span
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: "50%",
                  background: ASS.ok,
                }}
              />
              Acerto
            </span>
            <span
              style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
            >
              <span
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: "50%",
                  background: ASS.warn,
                }}
              />
              Mal id.
            </span>
            <span
              style={{ display: "inline-flex", alignItems: "center", gap: 6 }}
            >
              <span
                style={{
                  width: 8,
                  height: 8,
                  borderRadius: "50%",
                  background: ASS.danger,
                }}
              />
              Perdido
            </span>
          </div>
        </div>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 0,
            position: "relative",
          }}
        >
          <div
            style={{
              position: "absolute",
              left: 54,
              top: 14,
              bottom: 14,
              width: 1,
              background: "rgba(0,0,0,0.08)",
            }}
          />
          {d.events.map((e, i) => {
            const color =
              e.type === "found"
                ? ASS.ok
                : e.type === "misId"
                  ? ASS.warn
                  : ASS.danger;
            return (
              <div
                key={i}
                style={{
                  display: "grid",
                  gridTemplateColumns: "56px 16px 1fr auto",
                  gap: 10,
                  padding: "10px 0",
                  borderBottom:
                    i < d.events.length - 1
                      ? "1px solid rgba(0,0,0,0.04)"
                      : "none",
                  alignItems: "center",
                }}
              >
                <span
                  style={{
                    fontFamily: "ui-monospace, Menlo, monospace",
                    fontSize: 12,
                    color: ASS.inkSoft,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {e.t}
                </span>
                <span
                  style={{
                    width: 10,
                    height: 10,
                    borderRadius: "50%",
                    background: color,
                    border: "2px solid #fff",
                    boxShadow: "0 0 0 1px rgba(0,0,0,0.08)",
                    position: "relative",
                    zIndex: 1,
                    justifySelf: "center",
                  }}
                />
                <span style={{ fontSize: 13, color: ASS.ink }}>{e.label}</span>
                <US.Badge tone="neutral" size="sm">
                  {e.zone}
                </US.Badge>
              </div>
            );
          })}
        </div>
      </US.Glass>
    </>
  );
};

const SessionsList = ({ onOpenSession }) => (
  <>
    <PHS
      title="Minhas Sessões"
      subtitle="Histórico completo de simulações realizadas no app de treinamento."
    />
    <US.Glass>
      <US.Table
        onRowClick={(r) => onOpenSession(r.id)}
        columns={[
          {
            key: "id",
            label: "ID",
            render: (r) => (
              <span
                style={{
                  fontFamily: "ui-monospace, Menlo, monospace",
                  fontSize: 12,
                  color: ASS.inkSoft,
                }}
              >
                {r.id}
              </span>
            ),
          },
          { key: "date", label: "Data" },
          { key: "duration", label: "Duração" },
          {
            key: "found",
            label: "Acertos",
            align: "center",
            render: (r) => (
              <span style={{ color: ASS.ok, fontWeight: 600 }}>{r.found}</span>
            ),
          },
          {
            key: "missed",
            label: "Perdidos",
            align: "center",
            render: (r) => (
              <span style={{ color: ASS.danger, fontWeight: 600 }}>
                {r.missed}
              </span>
            ),
          },
          {
            key: "coverage",
            label: "Cobertura",
            render: (r) => `${r.coverage}%`,
          },
          {
            key: "score",
            label: "Nota",
            align: "right",
            render: (r) => (
              <b
                style={{
                  fontSize: 15,
                  color:
                    r.score >= 85 ? ASS.ok : r.score >= 70 ? ASS.ink : ASS.warn,
                }}
              >
                {r.score}
              </b>
            ),
          },
        ]}
        rows={MS.SESSIONS}
      />
    </US.Glass>
  </>
);

// Student "Minhas Turmas" — list of classes the student is in (read-only)
const StudentClasses = ({ onOpenClass }) => {
  const my = MS.CLASSES.filter(
    (c) =>
      MS.STUDENT_USER &&
      MS.STUDENTS.find((s) => s.id === MS.STUDENT_USER.id).classes.includes(
        c.id,
      ),
  );
  return (
    <>
      <PHS
        title="Minhas Turmas"
        subtitle="Turmas em que você está matriculado e seu desempenho em cada uma."
      />
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(2, 1fr)",
          gap: 16,
        }}
        className="two-col"
      >
        {my.map((c) => (
          <US.Glass
            key={c.id}
            style={{ cursor: "pointer" }}
            onClick={() => onOpenClass(c.id)}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "flex-start",
                marginBottom: 14,
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <div
                  style={{
                    display: "flex",
                    gap: 8,
                    alignItems: "center",
                    marginBottom: 6,
                  }}
                >
                  <US.Badge tone="primary" size="sm">
                    {c.id}
                  </US.Badge>
                  {c.status === "active" && (
                    <US.Badge tone="green" size="sm">
                      Ativa
                    </US.Badge>
                  )}
                  {c.status === "closing" && (
                    <US.Badge tone="gold" size="sm">
                      Encerrando
                    </US.Badge>
                  )}
                </div>
                <h3
                  style={{
                    margin: "0 0 4px",
                    fontSize: 16,
                    fontWeight: 600,
                    color: ASS.ink,
                    fontFamily: '"Plus Jakarta Sans", sans-serif',
                  }}
                >
                  {c.name}
                </h3>
                <div style={{ fontSize: 12, color: ASS.inkSoft }}>
                  Professor(a): {c.teacherName}
                </div>
              </div>
              <US.Icon name="chevron" size={16} />
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr 1fr",
                gap: 14,
                padding: "12px 0",
                borderTop: "1px solid rgba(0,0,0,0.06)",
                borderBottom: "1px solid rgba(0,0,0,0.06)",
                marginBottom: 12,
              }}
            >
              <div>
                <div
                  style={{
                    fontSize: 10,
                    color: ASS.inkMute,
                    fontWeight: 600,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Início
                </div>
                <div
                  style={{
                    fontSize: 13,
                    color: ASS.ink,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {c.startDate}
                </div>
              </div>
              <div>
                <div
                  style={{
                    fontSize: 10,
                    color: ASS.inkMute,
                    fontWeight: 600,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Término
                </div>
                <div
                  style={{
                    fontSize: 13,
                    color: ASS.ink,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {c.endDate}
                </div>
              </div>
              <div>
                <div
                  style={{
                    fontSize: 10,
                    color: ASS.inkMute,
                    fontWeight: 600,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Sua média
                </div>
                <div
                  style={{
                    fontSize: 13,
                    color: ASS.ok,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                    fontWeight: 700,
                  }}
                >
                  {c.avgScore + (c.id === "T-2026-A" ? 2 : -3)}%
                </div>
              </div>
            </div>
            <div
              style={{
                fontSize: 12,
                color: ASS.inkSoft,
                display: "flex",
                justifyContent: "space-between",
              }}
            >
              <span>
                Você completou:{" "}
                <b style={{ color: ASS.ink }}>6 de 8 atividades</b>
              </span>
              <span style={{ color: ASS.green, fontWeight: 600 }}>
                Ver turma →
              </span>
            </div>
          </US.Glass>
        ))}
      </div>
    </>
  );
};

// Read-only class view for student — shows class info, dates, classmate list (no PII drilling), own analytics for that class
const StudentClassView = ({ classId, onBack, onOpenSession }) => {
  const c = MS.CLASSES.find((x) => x.id === classId);
  const classmates = MS.STUDENTS.filter((s) => s.classes.includes(classId));
  const me = MS.STUDENT_USER.id;

  return (
    <>
      <PHS
        breadcrumb={[
          { label: "Minhas Turmas", onClick: onBack },
          { label: c.id },
        ]}
        title={c.name}
        subtitle={`${c.teacherName} · ${c.startDate} → ${c.endDate}`}
      />

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 14,
          marginBottom: 18,
        }}
        className="metric-grid"
      >
        <US.Glass>
          <US.Metric
            label="Sua média na turma"
            value="86%"
            delta={3}
            icon="target"
            accent={ASS.green}
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Suas sessões"
            value="6"
            sub="nesta turma"
            icon="session"
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Média da turma"
            value={`${c.avgScore}%`}
            sub="referência geral"
            icon="chart"
          />
        </US.Glass>
        <US.Glass>
          <US.Metric
            label="Encerra em"
            value="29 dias"
            sub={c.endDate}
            icon="clock"
            accent={ASS.gold}
          />
        </US.Glass>
      </div>

      <div
        style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}
        className="two-col"
      >
        <US.Glass>
          <h3
            style={{
              margin: "0 0 14px",
              fontSize: 15,
              fontWeight: 600,
              color: ASS.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Sua evolução nesta turma
          </h3>
          <US.LineChart
            data={[
              { value: 72 },
              { value: 78 },
              { value: 81 },
              { value: 85 },
              { value: 84 },
              { value: 89 },
            ]}
            height={170}
          />
        </US.Glass>
        <US.Glass>
          <h3
            style={{
              margin: "0 0 14px",
              fontSize: 15,
              fontWeight: 600,
              color: ASS.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Colegas de turma
          </h3>
          <p
            style={{ margin: "-8px 0 12px", fontSize: 11, color: ASS.inkMute }}
          >
            Os dados individuais dos colegas são privados.
          </p>
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: 8,
              maxHeight: 280,
              overflowY: "auto",
            }}
          >
            {classmates.map((s) => (
              <div
                key={s.id}
                style={{
                  display: "flex",
                  gap: 10,
                  alignItems: "center",
                  padding: "7px 8px",
                  borderRadius: 6,
                  background:
                    s.id === me ? "rgba(0,78,45,0.08)" : "transparent",
                }}
              >
                <US.Avatar name={s.name} role="student" size={26} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      fontSize: 12,
                      fontWeight: 500,
                      color: ASS.ink,
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}
                  >
                    {s.name}
                    {s.id === me && (
                      <span
                        style={{
                          color: ASS.green,
                          marginLeft: 6,
                          fontSize: 10,
                          fontWeight: 700,
                        }}
                      >
                        · VOCÊ
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: 10, color: ASS.inkMute }}>{s.id}</div>
                </div>
              </div>
            ))}
          </div>
        </US.Glass>
      </div>

      <US.Glass style={{ marginTop: 16 }}>
        <h3
          style={{
            margin: "0 0 14px",
            fontSize: 15,
            fontWeight: 600,
            color: ASS.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
          }}
        >
          Suas sessões — somente {c.id}
        </h3>
        <US.Table
          onRowClick={(r) => onOpenSession && onOpenSession(r.id)}
          columns={[
            {
              key: "id",
              label: "ID",
              render: (r) => (
                <span
                  style={{
                    fontFamily: "ui-monospace, Menlo, monospace",
                    fontSize: 12,
                    color: ASS.inkSoft,
                  }}
                >
                  {r.id}
                </span>
              ),
            },
            { key: "date", label: "Data" },
            { key: "duration", label: "Duração" },
            {
              key: "found",
              label: "Acertos",
              align: "center",
              render: (r) => (
                <span style={{ color: ASS.ok, fontWeight: 600 }}>
                  {r.found}
                </span>
              ),
            },
            {
              key: "missed",
              label: "Perdidos",
              align: "center",
              render: (r) => (
                <span style={{ color: ASS.danger, fontWeight: 600 }}>
                  {r.missed}
                </span>
              ),
            },
            {
              key: "score",
              label: "Nota",
              align: "right",
              render: (r) => (
                <b
                  style={{
                    fontSize: 15,
                    color: r.score >= 85 ? ASS.ok : ASS.ink,
                  }}
                >
                  {r.score}
                </b>
              ),
            },
          ]}
          rows={MS.SESSIONS.slice(0, 4)}
        />
      </US.Glass>
    </>
  );
};

window.StudentViews = {
  StudentOverview,
  StudentDetail,
  StudentPanel,
  SessionDetail,
  SessionsList,
  StudentClasses,
  StudentClassView,
};
