// Classes — école overview. Desktop version: filters bar + 3-stat header + class cards grid.

function Classes({ onOpenClass }) {
  const { CLASSES, TEACHERS } = window.SCOLIA;
  const tById = Object.fromEntries(TEACHERS.map(tc => [tc.id, tc]));
  const { toast, t } = useApp();
  const [q, setQ] = React.useState("");
  const [filter, setFilter] = React.useState("all");
  const [sort, setSort] = React.useState("niveau");
  const visible = CLASSES.filter(c =>
    (filter==="all" ||
      (filter==="maternelle" && c.code==="Mate") ||
      (filter==="cycle2" && ["CP","CE1","CE2"].includes(c.code))) &&
    c.name.toLowerCase().includes(q.toLowerCase())
  );

  const FILTERS = [
    { k: "all",        l: t("tab_all")        },
    { k: "maternelle", l: t("tab_maternelle") },
    { k: "cycle2",     l: t("tab_cycle2")     },
    { k: "cycle3",     l: t("tab_cycle3")     },
  ];

  const SORTS = [
    { k: "niveau",    l: t("sort_niveau")    },
    { k: "effectif",  l: t("sort_effectif")  },
    { k: "presence",  l: t("sort_presence")  },
    { k: "nom",       l: t("sort_nom")       },
  ];

  const sortLabel = SORTS.find(s => s.k === sort)?.l || t("sort_niveau");

  return (
    <div>
      <Topbar
        left={
          <div>
            <div className="eyebrow">{t("classes_eyebrow")}</div>
            <h1 className="h1" style={{marginTop: 6}}>École Tournesol</h1>
          </div>
        }
        right={
          <>
            <div className="search" style={{maxWidth: 260}}>
              <Icons.Search size={16}/>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder={t("classes_search_ph")}/>
            </div>
            <DropMenu trigger={<button className="btn"><Icons.Filter size={16}/>{t("classes_filters")}</button>} items={[
              {icon: Icons.Check, label: "Avec retards",      onClick: () => toast("Filtre: avec retards")},
              {icon: Icons.Check, label: "Avec absents",      onClick: () => toast("Filtre: avec absents")},
              {icon: Icons.Check, label: "Observations 7j",   onClick: () => toast("Filtre: observations 7j")},
              "-",
              {icon: Icons.X,     label: "Réinitialiser",     onClick: () => toast("Filtres réinitialisés")},
            ]}/>
            <button className="btn btn-primary" onClick={() => toast("Création d'une nouvelle classe")}><Icons.Plus size={16}/>{t("classes_new")}</button>
          </>
        }
      />

      <div className="row gap-4" style={{marginBottom: 24}}>
        <Stat label={t("stat_classes")} value="4" sub="2 cycles"/>
        <Stat label={t("stat_eleves")}  value="26" sub="+2 ce mois"/>
        <Stat label={t("stat_presents_today")} value="58%" valueColor="var(--warn)" sub="15 sur 26"/>
        <Stat label={t("stat_obs_7j")} value="12" sub="↑ 4 vs semaine -1"/>
      </div>

      <div className="row" style={{justifyContent:"space-between", alignItems:"center", marginBottom: 16}}>
        <div className="tabs">
          {FILTERS.map(f => (
            <button key={f.k} className={filter===f.k?"active":""} onClick={() => setFilter(f.k)}>{f.l}</button>
          ))}
        </div>
        <div className="row gap-3" style={{alignItems: "center"}}>
          <span className="meta">{t("sort_by")}</span>
          <DropMenu trigger={<button className="btn">{sortLabel} <Icons.ChevD size={14}/></button>} items={
            SORTS.map(s => ({label: s.l, onClick: () => setSort(s.k)}))
          }/>
        </div>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 20}}>
        {visible.map(c => {
          const tch = tById[c.teacher];
          const tot = c.students;
          const pct = (n) => `${(n / tot * 100).toFixed(0)}%`;
          return (
            <button key={c.id} className="card card-pad"
                    onClick={() => onOpenClass(c.id)}
                    style={{textAlign: "left", cursor: "pointer", transition: "border-color .12s ease, transform .12s ease"}}
                    onMouseEnter={e => e.currentTarget.style.borderColor = "var(--border-strong)"}
                    onMouseLeave={e => e.currentTarget.style.borderColor = "var(--border)"}>
              <div className="row" style={{justifyContent: "space-between", alignItems: "flex-start"}}>
                <div className="row gap-3" style={{alignItems: "center"}}>
                  <div style={{
                    width: 56, height: 56, borderRadius: 14,
                    background: "var(--brand-soft)", color: "var(--brand-ink)",
                    display: "grid", placeItems: "center",
                    fontWeight: 800, fontSize: 14, letterSpacing: "-0.01em"
                  }}>{c.code}</div>
                  <div>
                    <div style={{fontWeight: 800, color: "var(--ink)", fontSize: 18}}>{c.name}</div>
                    <div className="row gap-2" style={{alignItems: "center", marginTop: 4}}>
                      <Photo src={tch.img} size={20}/>
                      <span className="meta">{tch.name}</span>
                    </div>
                  </div>
                </div>
                <Icons.ChevR size={18} style={{color: "var(--ink-5)", marginTop: 10}}/>
              </div>

              <div style={{marginTop: 20, marginBottom: 12}}>
                <div className="row" style={{justifyContent: "space-between", marginBottom: 6, alignItems: "baseline"}}>
                  <div className="eyebrow">{t("presence_du_jour")}</div>
                  <div className="tnum" style={{fontWeight: 700, color: "var(--ink)"}}>{c.present}/{c.students}</div>
                </div>
                <div className="pbar" style={{height: 10}}>
                  <div className="ok"   style={{width: pct(c.present)}}/>
                  <div className="warn" style={{width: pct(c.late)}}/>
                  <div className="bad"  style={{width: pct(c.absent)}}/>
                </div>
              </div>

              <div className="row gap-2">
                <span className="chip brand"><span className="chip-dot"/> {c.present} {t("chip_presents")}</span>
                {c.late   > 0 && <span className="chip warn">  <span className="chip-dot"/> {c.late} {t("chip_retards")}</span>}
                {c.absent > 0 && <span className="chip danger"><span className="chip-dot"/> {c.absent} {t("chip_absents")}</span>}
              </div>

              <div className="divider" style={{margin: "18px 0 12px"}}/>
              <div className="row" style={{justifyContent: "space-between", alignItems: "center"}}>
                <div className="row gap-4">
                  <Tiny label={t("stat_eleves")} value={c.students}/>
                  <Tiny label={t("obs_7j_tiny")} value={c.id === "ce1" ? 4 : c.id === "ce2" ? 2 : 1}/>
                  <Tiny label={t("conv_tiny")}   value={0}/>
                </div>
                <div className="row gap-2" onClick={e => e.stopPropagation()}>
                  <button className="btn btn-ghost" onClick={() => toast("Message à " + tch.first)}><Icons.Msg size={14}/>{t("message_btn")}</button>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Stat({ label, value, sub, valueColor }) {
  return (
    <div className="card card-pad" style={{flex: 1}}>
      <div className="eyebrow">{label}</div>
      <div className="display" style={{fontSize: 36, marginTop: 6, color: valueColor || "var(--ink)"}}>{value}</div>
      <div className="meta" style={{marginTop: 4}}>{sub}</div>
    </div>
  );
}

function Tiny({label, value}) {
  return (
    <div>
      <div className="meta" style={{fontSize: 11.5, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase"}}>{label}</div>
      <div className="tnum" style={{fontWeight: 800, color: "var(--ink)", fontSize: 17, marginTop: 2}}>{value}</div>
    </div>
  );
}

window.Classes = Classes;
window.Stat = Stat;
