// groups.jsx — pantalla "Mundial": tablas de grupos, clasificados y cuadro automático. → window
const { useState: useStateG } = React;

function TeamCell({ code, size = 22 }) {
  const t = window.TEAMS[code];
  return (<><window.Flag code={code} size={size} /><span className="gt-name">{t ? t.name : code}</span></>);
}

function GroupMini({ g, state, thirdsQ }) {
  const table = window.groupTable(g, state);
  const complete = window.groupComplete(g, state);
  const finals = window.MATCHES.filter((m) => m.group === g && window.isFinal(m, state)).length;
  return (
    <div className="gtable">
      <div className="gt-head gt-head-g">
        <span className="gh-letter">Grupo {g}</span>
        <span className="gt-r">PJ</span><span className="gt-r">DG</span><span className="gt-r">Pts</span>
      </div>
      {table.map((t, i) => {
        const thirdQual = i === 2 && thirdsQ[t.code];
        return (
          <div key={t.code} className={"gt-row" + (i < 2 ? " qualify" : thirdQual ? " third-q" : "")}>
            <span className="gt-pos">{i + 1}</span>
            <TeamCell code={t.code} />
            <span className="gt-r">{t.pj}</span>
            <span className="gt-r">{t.dg > 0 ? "+" + t.dg : t.dg}</span>
            <span className="gt-r gt-pts">{t.pts}</span>
          </div>
        );
      })}
      <div className="gt-foot">{complete ? "Grupo cerrado ✓" : finals + "/6 jugados"}</div>
    </div>
  );
}

function ThirdsPanel({ state }) {
  const ts = window.thirdsRanking(state);
  return (
    <div className="thirds">
      <div className="thirds-head">
        <span>Mejores terceros</span><span className="thirds-sub">clasifican 8 de 12</span>
      </div>
      {ts.map((t) => (
        <div key={t.group} className={"third-row" + (t.qualifies ? " q" : "")}>
          <span className="third-rank">{t.rank}</span>
          <span className="third-grp">{t.group}</span>
          <TeamCell code={t.code} size={20} />
          <span className="third-pts">{t.complete ? t.pts + " pts" : "—"}</span>
          {t.qualifies ? <span className="third-tag">Clasifica</span> : <span className="third-tag out">Fuera</span>}
        </div>
      ))}
      <p className="thirds-note">El orden final se confirma al terminar los 12 grupos (puntos · dif. de gol · goles a favor).</p>
    </div>
  );
}

function GroupsView({ state }) {
  const T = window.tournamentState(state);
  const thirdsQ = {};
  T.thirds.forEach((t) => { if (t.qualifies) thirdsQ[t.code] = true; });
  const decided = Object.values(T.groups).filter((x) => x.complete).length;
  return (
    <div className="mundial-body">
      <div className="qual-banner">
        <div><b>{decided}</b><span>grupos cerrados</span></div>
        <div className="qb-sep"></div>
        <div><b className="qb-green"></b><span>1º y 2º clasifican</span></div>
        <div><b className="qb-amber"></b><span>mejor 3º</span></div>
      </div>
      <div className="groups-grid">
        {Object.keys(window.GROUP_TEAMS).map((g) => (
          <GroupMini key={g} g={g} state={state} thirdsQ={thirdsQ} />
        ))}
      </div>
      <ThirdsPanel state={state} />
    </div>
  );
}

const ROUNDS = [
  { id: "r32", label: "16avos", n: 16, prefix: "r32" },
  { id: "r16", label: "8vos", n: 8, prefix: "r16" },
  { id: "qf", label: "4tos", n: 4, prefix: "qf" },
  { id: "sf", label: "Semis", n: 2, prefix: "sf" },
  { id: "third", label: "3º", n: 1, prefix: "third" },
  { id: "final", label: "Final", n: 1, prefix: "final" },
];

function KoSide({ slot, picked, canPick, onPick }) {
  const t = slot.code ? window.TEAMS[slot.code] : null;
  return (
    <button className={"ko-side" + (picked ? " win" : "") + (canPick ? " can" : "")}
      disabled={!canPick} onClick={onPick}>
      {t
        ? <><window.Flag code={slot.code} size={22} /><span>{t.name}</span></>
        : <span className="ko-tbd">{slot.label}</span>}
    </button>
  );
}

function BracketView({ state, setKoWinner }) {
  const [round, setRound] = useStateG("r32");
  const { matches, T } = window.buildBracket(state);
  const rd = ROUNDS.find((r) => r.id === round);
  const keys = (round === "final" || round === "third") ? [round] : Array.from({ length: rd.n }, (_, i) => rd.prefix + "-" + (i + 1));

  return (
    <div className="mundial-body">
      <div className="seg seg-rounds">
        {ROUNDS.map((r) => (
          <button key={r.id} className={"seg-btn" + (round === r.id ? " on" : "")} onClick={() => setRound(r.id)}>{r.label}</button>
        ))}
      </div>
      <p className="ko-help">
        {T.allComplete
          ? "El cuadro ya se llenó con los clasificados de grupos. Toca al equipo que avanza para simular las rondas."
          : "El cuadro se llenará automáticamente cuando terminen los grupos. Mientras tanto verás los cupos pendientes."}
      </p>
      <div className="ko-list">
        {keys.map((k) => {
          const m = matches[k];
          const pick = (state.koWinners || {})[k];
          const canPick = !!(m.home.code && m.away.code);
          return (
            <div key={k} className={"ko-match" + (round === "final" ? " ko-final" : round === "third" ? " ko-third" : "")}>
              <span className="ko-num">P{m.num}</span>
              <div className="ko-sides">
                <KoSide slot={m.home} picked={pick === "home"} canPick={canPick} onPick={() => setKoWinner(k, "home")} />
                <KoSide slot={m.away} picked={pick === "away"} canPick={canPick} onPick={() => setKoWinner(k, "away")} />
              </div>
            </div>
          );
        })}
      </div>
      {round === "final" && (() => {
        const f = matches["final"]; const pick = (state.koWinners || {}).final;
        const champ = pick === "home" ? f.home.code : pick === "away" ? f.away.code : null;
        return champ ? (
          <div className="champ"><window.Icon name="trophy" size={26} /><div><span>Campeón del Mundo</span><b>{window.TEAMS[champ].flag} {window.TEAMS[champ].name}</b></div></div>
        ) : null;
      })()}
    </div>
  );
}

function MundialScreen({ state, setKoWinner }) {
  const [view, setView] = useStateG("grupos");
  return (
    <div className="screen">
      <div className="hero hero-ink">
        <window.Eyebrow color="rgba(255,255,255,.7)">Clasificación automática</window.Eyebrow>
        <h1 className="hero-title">Mundial 26</h1>
        <div className="seg seg-top">
          <button className={"seg-btn" + (view === "grupos" ? " on" : "")} onClick={() => setView("grupos")}>Grupos</button>
          <button className={"seg-btn" + (view === "cuadro" ? " on" : "")} onClick={() => setView("cuadro")}>Eliminatorias</button>
        </div>
      </div>
      {view === "grupos" ? <GroupsView state={state} /> : <BracketView state={state} setKoWinner={setKoWinner} />}
    </div>
  );
}

Object.assign(window, { MundialScreen });
