// matches.jsx — lista de partidos por día + detalle de partido + carga rápida por jugador. Exported to window.
const { useState: useStateM } = React;

function statusOf(m, state) {
  if (m.archived) return { label: "Finalizado", cls: "st-final" };
  if (window.isFinal(m, state)) return { label: "Final", cls: "st-final" };
  const r = window.resultFor(m, state);
  if (r && (r.h != null || r.a != null)) return { label: "En curso", cls: "st-live" };
  return { label: "Por jugar", cls: "st-soon" };
}

function shortDate(d) {
  const parts = String(d || "").split("-").map(Number);
  if (parts.length !== 3 || parts.some(Number.isNaN)) return d;
  return `${parts[2]}/${parts[1]}`;
}

function MatchCard({ m, state, onOpen }) {
  const st = statusOf(m, state);
  const r = window.resultFor(m, state);
  const H = window.TEAMS[m.home], A = window.TEAMS[m.away];
  const hasScore = r && r.h != null && r.a != null;
  const nPreds = state.preds && state.preds[m.id] ? Object.keys(state.preds[m.id]).length : 0;
  return (
    <button className="mcard" onClick={() => onOpen(m.id)}>
      <div className="mcard-top">
        <span className="mc-group">P{m.num} · Grupo {m.group}</span>
        <span className={"st-chip " + st.cls}>{st.label}</span>
      </div>
      <div className="mcard-body">
        <div className="mc-team mc-home">
          <window.Flag code={m.home} size={30} />
          <span className="mc-name">{H.name}</span>
        </div>
        <div className="mc-center">
          {hasScore
            ? <div className="mc-score">{r.h}<i>:</i>{r.a}</div>
            : <div className="mc-vs">vs</div>}
          <div className="mc-time">{m.kickoff}</div>
        </div>
        <div className="mc-team mc-away">
          <window.Flag code={m.away} size={30} />
          <span className="mc-name">{A.name}</span>
        </div>
      </div>
      <div className="mcard-foot">
        <span className="mc-venue">{m.venue}</span>
        <span>{nPreds} pronósticos</span>
        <span className="mc-open">Abrir <window.Icon name="chevron" size={15} stroke={2.6} /></span>
      </div>
    </button>
  );
}

const GROUP_LETTERS = Object.keys(window.GROUP_TEAMS);

function MatchListMode({ state, onOpen }) {
  const [filter, setFilter] = useStateM("today");
  let list = window.MATCHES;
  if (filter === "today") list = list.filter((m) => m.day === window.TODAY);
  else if (filter !== "all") list = list.filter((m) => m.group === filter);
  const days = [...new Set(list.map((m) => m.day))];
  const todayCount = window.MATCHES.filter((m) => m.day === window.TODAY).length;

  return (
    <>
      <div className="filterbar compact-filter">
        <button className={"fpill" + (filter === "today" ? " on" : "")} onClick={() => setFilter("today")}>Hoy{todayCount ? " · " + todayCount : ""}</button>
        <button className={"fpill" + (filter === "all" ? " on" : "")} onClick={() => setFilter("all")}>Todos</button>
        {GROUP_LETTERS.map((g) => (
          <button key={g} className={"fpill" + (filter === g ? " on" : "")} onClick={() => setFilter(g)}>{g}</button>
        ))}
      </div>
      <div className="days">
        {days.length === 0 && <div className="empty-day">No hay partidos hoy. Toca “Todos” o una letra de grupo.</div>}
        {days.map((d) => (
          <div key={d} className="day-block">
            <div className="day-label"><span>{window.dayLabel(d)}</span></div>
            {list.filter((m) => m.day === d).map((m) => (
              <MatchCard key={m.id} m={m} state={state} onOpen={onOpen} />
            ))}
          </div>
        ))}
      </div>
    </>
  );
}

function PlayerPredRow({ m, player, state, setPred, onOpen }) {
  const pred = ((state.preds || {})[m.id] && (state.preds || {})[m.id][player.id]) || {};
  const H = window.TEAMS[m.home], A = window.TEAMS[m.away];
  const isComplete = pred.h != null && pred.a != null;
  return (
    <div className={"quick-row" + (isComplete ? " is-complete" : "") }>
      <div className="quick-main-line">
        <window.Flag code={m.home} size={24} />
        <window.ScoreStepper value={pred.h ?? null} compact onChange={(v) => setPred(m.id, player.id, "h", v)} />
        <span className="quick-vs">VS.</span>
        <window.ScoreStepper value={pred.a ?? null} compact onChange={(v) => setPred(m.id, player.id, "a", v)} />
        <window.Flag code={m.away} size={24} />
      </div>
      <button className="quick-open-row" onClick={() => onOpen(m.id)}>
        P{m.num} · {H.name} vs. {A.name} · {m.kickoff}
      </button>
    </div>
  );
}

function PlayerEntryMode({ state, setPred, onOpen }) {
  const days = [...new Set(window.MATCHES.map((m) => m.day))];
  const defaultDay = days.includes(window.TODAY) ? window.TODAY : days.find((d) => window.MATCHES.some((m) => m.day === d && !window.isFinal(m, state))) || days[0];
  const [day, setDay] = useStateM(defaultDay);
  const [playerId, setPlayerId] = useStateM(window.PLAYERS[0].id);
  const player = window.PLAYERS.find((p) => p.id === playerId) || window.PLAYERS[0];
  const dayMatches = window.MATCHES.filter((m) => m.day === day);
  const completed = dayMatches.filter((m) => {
    const pred = ((state.preds || {})[m.id] && (state.preds || {})[m.id][player.id]) || {};
    return pred.h != null && pred.a != null;
  }).length;

  return (
    <div className="quick-entry">
      <div className="filterbar personbar">
        {window.PLAYERS.map((p) => (
          <button key={p.id} className={"fpill" + (playerId === p.id ? " on" : "")} onClick={() => setPlayerId(p.id)}>{p.name}</button>
        ))}
      </div>
      <div className="filterbar compact-filter daybar">
        {days.map((d) => (
          <button key={d} className={"fpill" + (day === d ? " on" : "")} onClick={() => setDay(d)}>{d === window.TODAY ? "Hoy" : shortDate(d)}</button>
        ))}
      </div>

      <div className="quick-card">
        <div className="quick-head">
          <div>
            <span className="qh-name">{player.full || player.name}</span>
            <h2>Juego para {day === window.TODAY ? "hoy" : "el día"} {shortDate(day)}</h2>
          </div>
          <span className="qh-count">{completed}/{dayMatches.length}</span>
        </div>
        <div className="quick-note">Anota todos los pronósticos de una persona en una sola pantalla, como los envían por WhatsApp.</div>
        <div className="quick-list">
          {dayMatches.map((m) => (
            <PlayerPredRow key={m.id} m={m} player={player} state={state} setPred={setPred} onOpen={onOpen} />
          ))}
        </div>
        <div className="quick-foot">Guardado automático en este dispositivo.</div>
      </div>
    </div>
  );
}

function MatchesScreen({ state, setPred, onOpen }) {
  const [mode, setMode] = useStateM("player");
  return (
    <div className="screen">
      <div className="hero hero-blue">
        <window.Eyebrow color="rgba(255,255,255,.7)">Horario de Venezuela · 72 partidos</window.Eyebrow>
        <h1 className="hero-title">Partidos</h1>
        <div className="seg seg-top matches-mode">
          <button className={"seg-btn" + (mode === "player" ? " on" : "")} onClick={() => setMode("player")}>Por persona</button>
          <button className={"seg-btn" + (mode === "match" ? " on" : "")} onClick={() => setMode("match")}>Por partido</button>
        </div>
      </div>
      {mode === "player"
        ? <PlayerEntryMode state={state} setPred={setPred} onOpen={onOpen} />
        : <MatchListMode state={state} onOpen={onOpen} />}
    </div>
  );
}

function MatchDetail({ matchId, state, scoring, setResult, setPred, onClose }) {
  const m = window.MATCHES.find((x) => x.id === matchId);
  const H = window.TEAMS[m.home], A = window.TEAMS[m.away];
  const r = window.resultFor(m, state) || {};
  const final = window.isFinal(m, state);
  const locked = m.archived;

  const draftH = r.h, draftA = r.a;

  return (
    <div className="detail">
      <div className="detail-top">
        <button className="back" onClick={onClose} aria-label="Volver">
          <window.Icon name="chevron" size={22} style={{ transform: "rotate(180deg)" }} />
        </button>
        <div className="detail-top-mid">P{m.num} · Grupo {m.group} · {window.dayLabel(m.day)}</div>
        <div style={{ width: 38 }}></div>
      </div>

      <div className="detail-match">
        <div className="dm-team">
          <window.Flag code={m.home} size={46} />
          <span>{H.name}</span>
          {H.prov && <em className="dm-prov">{H.hint}</em>}
        </div>
        <div className="dm-score">
          {final || (r.h != null && r.a != null)
            ? <div className="dm-num">{r.h ?? "–"}<i>:</i>{r.a ?? "–"}</div>
            : <div className="dm-vs">VS</div>}
          <div className={"dm-status " + statusOf(m, state).cls}>{statusOf(m, state).label}</div>
        </div>
        <div className="dm-team">
          <window.Flag code={m.away} size={46} />
          <span>{A.name}</span>
          {A.prov && <em className="dm-prov">{A.hint}</em>}
        </div>
      </div>

      <div className="match-meta">
        <span><window.Icon name="calendar" size={15} /> {m.kickoff}</span>
        <span><window.Icon name="pin" size={15} /> {m.venue}</span>
      </div>

      {/* Resultado real */}
      <div className="result-box">
        <div className="rb-head">
          <window.Icon name="whistle" size={18} />
          <span>Resultado real</span>
          {locked && <span className="locked"><window.Icon name="lock" size={14} /> archivado</span>}
        </div>
        {locked ? (
          <div className="rb-locked">Partido archivado · {r.h}-{r.a}. Sus puntos base ya están en el acumulado.</div>
        ) : (
          <>
            <div className="rb-steppers">
              <div className="rb-side">
                <window.Flag code={m.home} size={24} />
                <window.ScoreStepper value={draftH ?? null}
                  onChange={(v) => setResult(m.id, { ...r, h: v })} accent="var(--blue-ink)" />
              </div>
              <span className="rb-x">:</span>
              <div className="rb-side">
                <window.ScoreStepper value={draftA ?? null}
                  onChange={(v) => setResult(m.id, { ...r, a: v })} accent="var(--blue-ink)" />
                <window.Flag code={m.away} size={24} />
              </div>
            </div>
            <button
              className={"rb-final" + (final ? " on" : "")}
              disabled={r.h == null || r.a == null}
              onClick={() => setResult(m.id, { ...r, final: !final })}>
              {final ? <><window.Icon name="check" size={18} /> Marcado como final — toca para reabrir</> : "Marcar como final y calcular puntos"}
            </button>
          </>
        )}
      </div>

      {/* Pronósticos por jugador */}
      <div className="pred-box">
        <div className="pb-head">
          <span>Pronósticos · {window.PLAYERS.length} jugadores</span>
          {final && <span className="pb-hint">puntos calculados</span>}
        </div>
        <div className="pred-list">
          {window.PLAYERS.map((p) => {
            const pred = ((state.preds || {})[m.id] && (state.preds || {})[m.id][p.id]) || {};
            const oc = final ? window.matchOutcome(pred, r) : null;
            const pts = final ? window.matchPoints(pred, r, scoring) : null;
            return (
              <div key={p.id} className={"pred-row" + (oc ? " oc-" + oc : "")}>
                <div className="pr-name">
                  {p.name}{p.padrino && <em className="padrino">padrino</em>}
                </div>
                <div className="pr-inputs">
                  <window.ScoreStepper value={pred.h ?? null} compact
                    onChange={(v) => setPred(m.id, p.id, "h", v)} />
                  <span className="pr-x">:</span>
                  <window.ScoreStepper value={pred.a ?? null} compact
                    onChange={(v) => setPred(m.id, p.id, "a", v)} />
                </div>
                <window.PtsChip outcome={oc} pts={pts} />
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MatchesScreen, MatchDetail });
