// Classes management — list, create, detail with roster + per-student extension
const { useState: useStateCl } = React;
const UC = window.UI;
const AC = UC.A;
const MC = window.MOCK;
const { PageHeader: PHC } = window.Shell;

const ClassesList = ({ role, onOpen }) => {
  const [showCreate, setShowCreate] = useStateCl(false);
  const [filter, setFilter] = useStateCl("active");
  const [form, setForm] = useStateCl({ id: "", name: "", teacher_id: "", start_date: "", end_date: "" });
  const [formErr, setFormErr] = useStateCl("");
  const [busy, setBusy] = useStateCl(false);

  const submitCreate = async () => {
    setFormErr("");
    if (!form.id.trim() || !form.name.trim() || !form.start_date || !form.end_date) {
      setFormErr("Preencha identificador, nome e datas."); return;
    }
    if (role === "admin" && !form.teacher_id.trim()) {
      setFormErr("Selecione um professor responsável."); return;
    }
    setBusy(true);
    try {
      const payload = {
        id: form.id.trim().toUpperCase(),
        name: form.name.trim(),
        start_date: form.start_date,
        end_date: form.end_date,
      };
      if (role === "admin") payload.teacher_id = form.teacher_id.trim().toUpperCase();
      await window.API.createClass(payload);
      setShowCreate(false);
      setForm({ id: "", name: "", teacher_id: "", start_date: "", end_date: "" });
      await window.__refresh();
    } catch (e) {
      if (e.status === 409) setFormErr("Já existe uma turma com esse identificador.");
      else if (e.status === 400) setFormErr("Dados inválidos. Verifique o professor e as datas.");
      else setFormErr("Erro ao criar a turma.");
    } finally { setBusy(false); }
  };

  const filtered = MC.CLASSES.filter((c) =>
    filter === "all"
      ? true
      : filter === "active"
        ? c.status !== "closed"
        : c.status === "closed",
  );

  return (
    <>
      <PHC
        title={role === "admin" ? "Turmas" : "Minhas Turmas"}
        subtitle="Crie turmas, defina períodos e gerencie a lista de alunos."
        actions={[
          <UC.Button
            key="c"
            variant="gold"
            icon="plus"
            onClick={() => setShowCreate(true)}
          >
            Nova turma
          </UC.Button>,
        ]}
      />

      <div
        style={{
          marginBottom: 14,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <UC.Segmented
          value={filter}
          onChange={setFilter}
          options={[
            { value: "active", label: "Ativas" },
            { value: "closed", label: "Encerradas" },
            { value: "all", label: "Todas" },
          ]}
        />
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(2, 1fr)",
          gap: 16,
        }}
        className="two-col"
      >
        {filtered.map((c) => (
          <UC.Glass
            key={c.id}
            style={{ cursor: "pointer" }}
            onClick={() => onOpen(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,
                  }}
                >
                  <UC.Badge tone="primary" size="sm">
                    {c.id}
                  </UC.Badge>
                  {c.status === "active" && (
                    <UC.Badge tone="green" size="sm">
                      Ativa
                    </UC.Badge>
                  )}
                  {c.status === "closing" && (
                    <UC.Badge tone="gold" size="sm">
                      Encerrando
                    </UC.Badge>
                  )}
                  {c.status === "closed" && (
                    <UC.Badge tone="neutral" size="sm">
                      Encerrada
                    </UC.Badge>
                  )}
                </div>
                <h3
                  style={{
                    margin: "0 0 4px",
                    fontSize: 16,
                    fontWeight: 600,
                    color: AC.ink,
                    fontFamily: '"Plus Jakarta Sans", sans-serif',
                    letterSpacing: "-0.01em",
                  }}
                >
                  {c.name}
                </h3>
                <div style={{ fontSize: 12, color: AC.inkSoft }}>
                  {c.teacherName}
                </div>
              </div>
              <UC.Icon name="chevron" size={16} />
            </div>
            <div
              style={{
                display: "flex",
                gap: 18,
                paddingTop: 14,
                borderTop: "1px solid rgba(0,0,0,0.06)",
                fontSize: 12,
              }}
            >
              <div>
                <div
                  style={{
                    color: AC.inkMute,
                    fontWeight: 600,
                    fontSize: 10,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Período
                </div>
                <div
                  style={{
                    color: AC.ink,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {c.startDate.slice(5)} → {c.endDate.slice(5)}
                </div>
              </div>
              <div>
                <div
                  style={{
                    color: AC.inkMute,
                    fontWeight: 600,
                    fontSize: 10,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Alunos
                </div>
                <div
                  style={{
                    color: AC.ink,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {c.students}
                </div>
              </div>
              <div>
                <div
                  style={{
                    color: AC.inkMute,
                    fontWeight: 600,
                    fontSize: 10,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Média
                </div>
                <div
                  style={{
                    color: AC.ok,
                    marginTop: 3,
                    fontVariantNumeric: "tabular-nums",
                    fontWeight: 600,
                  }}
                >
                  {c.avgScore}%
                </div>
              </div>
              <div style={{ flex: 1, marginLeft: "auto" }}>
                <div
                  style={{
                    color: AC.inkMute,
                    fontWeight: 600,
                    fontSize: 10,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  Progresso
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    marginTop: 5,
                  }}
                >
                  <div
                    style={{
                      flex: 1,
                      height: 5,
                      background: "rgba(0,0,0,0.07)",
                      borderRadius: 3,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        width: `${c.completion}%`,
                        height: "100%",
                        background: AC.green,
                      }}
                    />
                  </div>
                  <span
                    style={{
                      fontVariantNumeric: "tabular-nums",
                      color: AC.ink,
                      fontWeight: 600,
                    }}
                  >
                    {c.completion}%
                  </span>
                </div>
              </div>
            </div>
          </UC.Glass>
        ))}
      </div>

      <UC.Modal
        open={showCreate}
        onClose={() => setShowCreate(false)}
        title="Criar nova turma"
        width={580}
        footer={
          <>
            <UC.Button variant="ghost" onClick={() => setShowCreate(false)} disabled={busy}>
              Cancelar
            </UC.Button>
            <UC.Button onClick={submitCreate} icon="check" disabled={busy}>
              {busy ? "Criando…" : "Criar turma"}
            </UC.Button>
          </>
        }
      >
        <div
          style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}
        >
          <div style={{ gridColumn: "span 2" }}>
            <UC.Input
              label="Nome da turma"
              placeholder="ex: Inspeção Visual de Tubulações — Turma D"
              value={form.name}
              onChange={(e) => setForm({ ...form, name: e.target.value })}
            />
          </div>
          <UC.Input
            label="Identificador"
            placeholder="T-2026-D"
            hint="Único — não pode ser alterado depois"
            value={form.id}
            onChange={(e) => setForm({ ...form, id: e.target.value })}
          />
          {role === "admin" ? (
            <UC.Input
              label="Professor responsável"
              placeholder="ex: PR000418"
              hint="Matrícula do professor"
              value={form.teacher_id}
              onChange={(e) => setForm({ ...form, teacher_id: e.target.value })}
            />
          ) : (
            <UC.Input
              label="Professor responsável"
              value="Você"
              disabled
              hint="Você é o professor desta turma"
            />
          )}
          <UC.Input
            label="Data de início"
            type="date"
            icon="calendar"
            value={form.start_date}
            onChange={(e) => setForm({ ...form, start_date: e.target.value })}
          />
          <UC.Input
            label="Data de término"
            type="date"
            icon="calendar"
            value={form.end_date}
            onChange={(e) => setForm({ ...form, end_date: e.target.value })}
          />
          {formErr && (
            <div style={{ gridColumn: "span 2", padding: 10, background: "rgba(184,51,31,0.08)", border: "1px solid rgba(184,51,31,0.2)", borderRadius: 8, fontSize: 13, color: AC.danger }}>
              {formErr}
            </div>
          )}
          <div style={{ gridColumn: "span 2" }}>
            <div
              style={{
                padding: 12,
                background: "rgba(221,160,3,0.08)",
                border: "1px dashed rgba(221,160,3,0.4)",
                borderRadius: 8,
                fontSize: 12,
                color: AC.inkSoft,
                lineHeight: 1.5,
                display: "flex",
                gap: 10,
                alignItems: "flex-start",
              }}
            >
              <div style={{ color: "#7a5a00" }}>
                <UC.Icon name="info" size={16} />
              </div>
              <div>
                Os alunos serão adicionados após a criação. Use a tela de
                detalhe da turma para gerenciar a lista de alunos e definir
                prazos individuais (extensões).
              </div>
            </div>
          </div>
        </div>
      </UC.Modal>
    </>
  );
};

const ClassDetail = ({ id, onBack, onOpenStudent }) => {
  const c = MC.CLASSES.find((x) => x.id === id);
  // Prefer the freshly fetched per-class enrollment (with custom_end_date) when available
  const enrolledList = (MC._classStudents && MC._classStudents[id]) || null;
  const studentsInClass = enrolledList || MC.STUDENTS.filter((s) => (s.classes || []).includes(id));
  const enrolledIds = new Set(studentsInClass.map((s) => s.id));
  const [tab, setTab] = useStateCl("roster");
  const [showAdd, setShowAdd] = useStateCl(false);
  const [extending, setExtending] = useStateCl(null);
  const [extDate, setExtDate] = useStateCl("");
  const [extBusy, setExtBusy] = useStateCl(false);
  const [selectedAdd, setSelectedAdd] = useStateCl(new Set());
  const [searchAdd, setSearchAdd] = useStateCl("");
  const [addBusy, setAddBusy] = useStateCl(false);
  const [addErr, setAddErr] = useStateCl("");

  // Settings form state — initialised from current class.
  // Re-syncs whenever the user opens a different class (id change).
  const [settings, setSettings] = useStateCl({ name: "", start_date: "", end_date: "" });
  const [settingsBusy, setSettingsBusy] = useStateCl(false);
  const [settingsMsg, setSettingsMsg] = useStateCl(null);
  React.useEffect(() => {
    if (!c) return;
    setSettings({ name: c.name || "", start_date: c.startDate || "", end_date: c.endDate || "" });
    setSettingsMsg(null);
  }, [id, c?.name, c?.startDate, c?.endDate]);

  const settingsDirty = c && (
    settings.name !== c.name ||
    settings.start_date !== c.startDate ||
    settings.end_date !== c.endDate
  );

  const submitSettings = async () => {
    if (!settingsDirty) return;
    setSettingsBusy(true);
    setSettingsMsg(null);
    try {
      await window.API.updateClass(id, {
        name: settings.name.trim(),
        start_date: settings.start_date,
        end_date: settings.end_date,
      });
      await window.__refresh();
      setSettingsMsg({ type: "ok", text: "Alterações salvas." });
    } catch (e) {
      setSettingsMsg({ type: "err", text: "Erro ao salvar alterações." });
    } finally { setSettingsBusy(false); }
  };

  const submitAddStudents = async () => {
    setAddErr("");
    if (selectedAdd.size === 0) { setAddErr("Selecione ao menos um aluno."); return; }
    setAddBusy(true);
    try {
      for (const sid of selectedAdd) {
        try { await window.API.addStudentToClass(id, sid); } catch (e) { /* skip duplicates */ }
      }
      setShowAdd(false);
      setSelectedAdd(new Set());
      setSearchAdd("");
      await window.__refresh();
      // Refresh the per-class roster too
      try {
        const r = await window.API.listClassStudents(id);
        MC._classStudents = MC._classStudents || {};
        MC._classStudents[id] = r.students;
      } catch (_) {}
    } catch (e) {
      setAddErr("Erro ao adicionar alunos.");
    } finally { setAddBusy(false); }
  };

  const submitExtension = async () => {
    if (!extending) return;
    setExtBusy(true);
    try {
      await window.API.setStudentExtension(id, extending.id, extDate || null);
      setExtending(null);
      setExtDate("");
      await window.__refresh();
      try {
        const r = await window.API.listClassStudents(id);
        MC._classStudents = MC._classStudents || {};
        MC._classStudents[id] = r.students;
      } catch (_) {}
    } catch (e) {
      alert("Erro ao salvar a extensão.");
    } finally { setExtBusy(false); }
  };

  const removeStudent = async (studentId) => {
    if (!window.confirm("Remover este aluno da turma?")) return;
    try {
      await window.API.removeStudentFromClass(id, studentId);
      await window.__refresh();
      try {
        const r = await window.API.listClassStudents(id);
        MC._classStudents = MC._classStudents || {};
        MC._classStudents[id] = r.students;
      } catch (_) {}
    } catch (e) {
      alert("Erro ao remover aluno.");
    }
  };

  if (!c) return null;

  return (
    <>
      <PHC
        breadcrumb={[{ label: "Turmas", onClick: onBack }, { label: c.id }]}
        title={c.name}
        subtitle={`${c.teacherName} · ${c.startDate} → ${c.endDate}`}
        actions={[
          <UC.Button key="e" variant="ghost" icon="edit" onClick={() => setTab("settings")}>
            Editar turma
          </UC.Button>,
          <UC.Button
            key="a"
            variant="gold"
            icon="plus"
            onClick={() => setShowAdd(true)}
          >
            Adicionar alunos
          </UC.Button>,
        ]}
      />

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 14,
          marginBottom: 18,
        }}
        className="metric-grid"
      >
        <UC.Glass>
          <UC.Metric label="Alunos" value={c.students} icon="users" />
        </UC.Glass>
        <UC.Glass>
          <UC.Metric
            label="Média da turma"
            value={`${c.avgScore}%`}
            icon="chart"
            accent={AC.green}
          />
        </UC.Glass>
        <UC.Glass>
          <UC.Metric
            label="Progresso"
            value={`${c.completion}%`}
            sub={`${Math.round((c.students * c.completion) / 100)} de ${c.students} concluíram`}
            icon="target"
          />
        </UC.Glass>
        <UC.Glass>
          <UC.Metric
            label="Dias restantes"
            value="29"
            sub={`Encerra em ${c.endDate}`}
            icon="clock"
            accent={AC.gold}
          />
        </UC.Glass>
      </div>

      <div style={{ marginBottom: 14 }}>
        <UC.Segmented
          value={tab}
          onChange={setTab}
          options={[
            { value: "roster", label: "Lista de alunos" },
            { value: "analytics", label: "Estatísticas" },
            { value: "settings", label: "Configurações" },
          ]}
        />
      </div>

      {tab === "roster" && (
        <UC.Glass>
          <UC.Table
            columns={[
              {
                key: "name",
                label: "Aluno",
                render: (r) => (
                  <div
                    style={{
                      display: "flex",
                      gap: 10,
                      alignItems: "center",
                      cursor: onOpenStudent ? "pointer" : "default",
                    }}
                    onClick={() => onOpenStudent && onOpenStudent(r.id)}
                  >
                    <UC.Avatar name={r.name} role="student" size={28} />
                    <div>
                      <div
                        style={{
                          fontWeight: 500,
                          color: onOpenStudent ? AC.green : AC.ink,
                        }}
                      >
                        {r.name}
                      </div>
                      <div style={{ fontSize: 11, color: AC.inkMute }}>
                        {r.id}
                      </div>
                    </div>
                  </div>
                ),
              },
              {
                key: "sessions",
                label: "Sessões",
                align: "center",
                render: (r) => (
                  <span style={{ fontVariantNumeric: "tabular-nums" }}>
                    {r.sessions}
                  </span>
                ),
              },
              {
                key: "lastSession",
                label: "Última sessão",
                render: (r) => (
                  <span style={{ fontSize: 12, color: AC.inkSoft }}>
                    {r.lastSession}
                  </span>
                ),
              },
              {
                key: "avgScore",
                label: "Média",
                align: "right",
                render: (r) => (
                  <b
                    style={{
                      color:
                        r.avgScore >= 85
                          ? AC.ok
                          : r.avgScore >= 70
                            ? AC.ink
                            : AC.warn,
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {r.avgScore}%
                  </b>
                ),
              },
              {
                key: "deadline",
                label: "Prazo individual",
                render: (r) =>
                  r.customEndDate ? (
                    <UC.Badge tone="gold">→ {r.customEndDate} (estendido)</UC.Badge>
                  ) : r.status === "extension" ? (
                    <UC.Badge tone="gold">estendido</UC.Badge>
                  ) : (
                    <span style={{ fontSize: 12, color: AC.inkMute }}>
                      Padrão da turma
                    </span>
                  ),
              },
              {
                key: "actions",
                label: "",
                align: "right",
                render: (r) => (
                  <div
                    style={{
                      display: "flex",
                      gap: 4,
                      justifyContent: "flex-end",
                    }}
                  >
                    <button
                      title="Estender prazo"
                      onClick={() => { setExtending(r); setExtDate(r.customEndDate || ""); }}
                      style={{
                        background: "rgba(221,160,3,0.12)",
                        border: "none",
                        cursor: "pointer",
                        color: "#7a5a00",
                        padding: "4px 8px",
                        fontSize: 11,
                        fontWeight: 600,
                        borderRadius: 6,
                        fontFamily: "inherit",
                      }}
                    >
                      + prazo
                    </button>
                    <button
                      title="Ver detalhes"
                      onClick={() => onOpenStudent && onOpenStudent(r.id)}
                      style={{
                        background: "none",
                        border: "none",
                        cursor: "pointer",
                        color: AC.inkSoft,
                        padding: 6,
                      }}
                    >
                      <UC.Icon name="eye" size={16} />
                    </button>
                    <button
                      title="Remover da turma"
                      onClick={() => removeStudent(r.id)}
                      style={{
                        background: "none",
                        border: "none",
                        cursor: "pointer",
                        color: AC.danger,
                        padding: 6,
                      }}
                    >
                      <UC.Icon name="x" size={16} />
                    </button>
                  </div>
                ),
              },
            ]}
            rows={studentsInClass}
          />
        </UC.Glass>
      )}

      {tab === "analytics" && (
        <div
          style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}
          className="two-col"
        >
          <UC.Glass>
            <h3
              style={{
                margin: "0 0 14px",
                fontSize: 15,
                fontWeight: 600,
                color: AC.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Distribuição de notas — turma
            </h3>
            <UC.BarChart
              data={[
                { label: "<60", value: 1 },
                { label: "60-69", value: 2 },
                { label: "70-79", value: 4 },
                { label: "80-89", value: 5 },
                { label: "90+", value: 2 },
              ]}
              height={180}
            />
          </UC.Glass>
          <UC.Glass>
            <h3
              style={{
                margin: "0 0 14px",
                fontSize: 15,
                fontWeight: 600,
                color: AC.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Defeitos mais perdidos
            </h3>
            <UC.StackedBar
              rows={[
                {
                  type: "Trinca em Solda",
                  found: 38,
                  misId: 6,
                  missed: 14,
                  total: 58,
                },
                {
                  type: "Vazamento Sutil",
                  found: 42,
                  misId: 3,
                  missed: 11,
                  total: 56,
                },
                {
                  type: "Corrosão Sob Iso.",
                  found: 51,
                  misId: 5,
                  missed: 7,
                  total: 63,
                },
              ]}
            />
          </UC.Glass>
          <UC.Glass style={{ gridColumn: "span 2" }}>
            <h3
              style={{
                margin: "0 0 14px",
                fontSize: 15,
                fontWeight: 600,
                color: AC.ink,
                fontFamily: '"Plus Jakarta Sans", sans-serif',
              }}
            >
              Cobertura média por zona — turma
            </h3>
            <UC.StackedBar
              rows={((MC.SESSION_DETAIL && MC.SESSION_DETAIL.zones) || []).map((z) => ({
                type: z.zone,
                found: z.covered,
                misId: 0,
                missed: z.missed,
                total: 100,
              }))}
              showLegend={false}
            />
          </UC.Glass>
        </div>
      )}

      {tab === "settings" && (
        <UC.Glass>
          <h3
            style={{
              margin: "0 0 16px",
              fontSize: 15,
              fontWeight: 600,
              color: AC.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Configurações da turma
          </h3>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 14,
              maxWidth: 600,
            }}
          >
            <UC.Input
              label="Nome"
              value={settings.name}
              onChange={(e) => setSettings({ ...settings, name: e.target.value })}
            />
            <UC.Input label="Identificador" value={c.id} disabled readOnly />
            <UC.Input
              label="Data de início"
              type="date"
              value={settings.start_date}
              onChange={(e) => setSettings({ ...settings, start_date: e.target.value })}
            />
            <UC.Input
              label="Data de término"
              type="date"
              value={settings.end_date}
              onChange={(e) => setSettings({ ...settings, end_date: e.target.value })}
            />
            <UC.Input
              label="Professor"
              value={c.teacherName}
              disabled
              readOnly
              hint="Para reatribuir, contate o administrador"
              style={{ gridColumn: "span 2" }}
            />
          </div>
          {settingsMsg && (
            <div style={{
              marginTop: 14, padding: 10,
              background: settingsMsg.type === "ok" ? "rgba(47,122,61,0.08)" : "rgba(184,51,31,0.08)",
              border: `1px solid ${settingsMsg.type === "ok" ? "rgba(47,122,61,0.25)" : "rgba(184,51,31,0.2)"}`,
              borderRadius: 8, fontSize: 13,
              color: settingsMsg.type === "ok" ? AC.ok : AC.danger,
            }}>{settingsMsg.text}</div>
          )}
          <div style={{ marginTop: 18, display: "flex", gap: 10 }}>
            <UC.Button icon="check" onClick={submitSettings} disabled={!settingsDirty || settingsBusy}>
              {settingsBusy ? "Salvando…" : "Salvar alterações"}
            </UC.Button>
          </div>
        </UC.Glass>
      )}

      <UC.Modal
        open={!!extending}
        onClose={() => { setExtending(null); setExtDate(""); }}
        title={extending ? `Estender prazo — ${extending.name}` : ""}
        footer={
          <>
            <UC.Button variant="ghost" onClick={() => { setExtending(null); setExtDate(""); }} disabled={extBusy}>
              Cancelar
            </UC.Button>
            <UC.Button onClick={submitExtension} icon="check" disabled={extBusy}>
              {extBusy ? "Salvando…" : extDate ? "Aplicar extensão" : "Remover extensão"}
            </UC.Button>
          </>
        }
      >
        <p style={{ margin: "0 0 16px", fontSize: 13, color: AC.inkSoft }}>
          Defina uma data limite individual para este aluno. Ele poderá acessar
          o app de treinamento e completar a atividade até a nova data, mesmo
          que a turma tenha encerrado. Deixe em branco para remover a extensão.
        </p>
        <div
          style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}
        >
          <UC.Input
            label="Prazo padrão da turma"
            value={c?.endDate || ""}
            disabled
            readOnly
          />
          <UC.Input
            label="Novo prazo individual"
            type="date"
            icon="calendar"
            value={extDate}
            onChange={(e) => setExtDate(e.target.value)}
          />
        </div>
      </UC.Modal>

      <UC.Modal
        open={showAdd}
        onClose={() => setShowAdd(false)}
        title="Adicionar alunos à turma"
        width={560}
        footer={
          <>
            <UC.Button variant="ghost" onClick={() => setShowAdd(false)} disabled={addBusy}>
              Cancelar
            </UC.Button>
            <UC.Button onClick={submitAddStudents} icon="check" disabled={addBusy || selectedAdd.size === 0}>
              {addBusy
                ? "Adicionando…"
                : selectedAdd.size === 0
                  ? "Adicionar alunos"
                  : selectedAdd.size === 1
                    ? "Adicionar 1 aluno"
                    : `Adicionar ${selectedAdd.size} alunos`}
            </UC.Button>
          </>
        }
      >
        <UC.Input
          icon="search"
          placeholder="Buscar aluno por nome ou matrícula…"
          value={searchAdd}
          onChange={(e) => setSearchAdd(e.target.value)}
          style={{ marginBottom: 14 }}
        />
        {addErr && (
          <div style={{ marginBottom: 12, padding: 10, background: "rgba(184,51,31,0.08)", border: "1px solid rgba(184,51,31,0.2)", borderRadius: 8, fontSize: 13, color: AC.danger }}>
            {addErr}
          </div>
        )}
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 6,
            maxHeight: 340,
            overflowY: "auto",
          }}
        >
          {(() => {
            // Source list: prefer the full institutional student list (admin/teacher).
            // Falls back to MC.STUDENTS if _allStudents wasn't hydrated for some reason.
            const sourceList = (MC._allStudents && MC._allStudents.length > 0) ? MC._allStudents : MC.STUDENTS;
            const candidates = sourceList.filter((s) => !enrolledIds.has(s.id))
              .filter((s) =>
                !searchAdd ||
                s.name.toLowerCase().includes(searchAdd.toLowerCase()) ||
                s.id.toLowerCase().includes(searchAdd.toLowerCase())
              );
            if (candidates.length === 0) {
              return (
                <div style={{ padding: 18, textAlign: "center", fontSize: 13, color: AC.inkMute }}>
                  {searchAdd ? "Nenhum aluno encontrado." : "Nenhum aluno disponível para adicionar."}
                </div>
              );
            }
            return candidates.slice(0, 50).map((s) => {
              const checked = selectedAdd.has(s.id);
              const inOthers = (s.classes || []).length;
              return (
                <label
                  key={s.id}
                  style={{
                    display: "flex",
                    gap: 12,
                    alignItems: "center",
                    padding: "10px 12px",
                    background: checked ? "rgba(0,78,45,0.08)" : "#f5f7f5",
                    borderRadius: 8,
                    cursor: "pointer",
                    border: "1px solid rgba(0,0,0,0.05)",
                  }}
                >
                  <input
                    type="checkbox"
                    checked={checked}
                    onChange={(e) => {
                      const next = new Set(selectedAdd);
                      if (e.target.checked) next.add(s.id);
                      else next.delete(s.id);
                      setSelectedAdd(next);
                    }}
                    style={{ accentColor: AC.green }}
                  />
                  <UC.Avatar name={s.name} role="student" size={28} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: AC.ink }}>
                      {s.name}
                    </div>
                    <div style={{ fontSize: 11, color: AC.inkMute }}>
                      {s.id} · {inOthers === 0 ? "sem turmas" : inOthers === 1 ? "1 turma" : `${inOthers} turmas`}
                    </div>
                  </div>
                </label>
              );
            });
          })()}
        </div>
      </UC.Modal>
    </>
  );
};

window.ClassViews = { ClassesList, ClassDetail };
