/* Census screen — the models' frozen forecast of the whole season.
   Every driver ranks all 20 clubs; champion, Champions League places and
   relegation are derived from those orderings, never stated separately. */

function CensusScreen({ onOpenModel }) {
  const { Card, Eyebrow, Badge, Stat } = window.TheOracleLeagueDesignSystem_92fa71;
  const CENSUS = window.CENSUS;
  const comp = window.COMPETITION || {};
  const mobile = window.useMobile();

  const [period, setPeriod] = React.useState(CENSUS ? CENSUS.defaultPeriod : null);

  // Nothing forecast yet — say when it happens rather than render an empty shell.
  if (!CENSUS) {
    return (
      <div style={{ padding: mobile ? "16px 16px" : "28px 32px", maxWidth: 720 }}>
        <Eyebrow tone="gold">Season census</Eyebrow>
        <h1 style={{
          fontFamily: "var(--font-display)", fontSize: mobile ? 26 : 38, fontWeight: 400,
          letterSpacing: "-0.02em", color: "var(--text-primary)", lineHeight: 1.12, margin: "12px 0 14px",
        }}>
          Twenty clubs, ranked by every model.
        </h1>
        <Card padding={20}>
          <Badge tone="neutral">Not yet taken</Badge>
          <p style={{
            fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)",
            lineHeight: 1.55, margin: "10px 0 0",
          }}>
            Before a ball is kicked, every model predicts the final table from first to last,
            plus the season's top scorer and one bold call. Those forecasts are frozen for the
            year and scored against reality in May — and re-taken each month, so you can watch
            the models change their minds.
          </p>
        </Card>
      </div>
    );
  }

  const data = CENSUS.byPeriod[period] || CENSUS.byPeriod[CENSUS.defaultPeriod];
  const { table, models, topScorers } = data;
  const nModels = models.length;
  const champions = {};
  models.forEach((m) => { if (m.champion) champions[m.champion] = (champions[m.champion] || 0) + 1; });
  const championList = Object.keys(champions)
    .map((c) => ({ club: c, votes: champions[c] }))
    .sort((a, b) => b.votes - a.votes);
  const mostDivisive = [...table].sort((a, b) => b.spread - a.spread)[0];
  const periodLabel = (p) => (p === "preseason" ? "Pre-season" : p);

  return (
    <div style={{ padding: mobile ? "16px 16px" : "28px 32px", maxWidth: 980 }}>
      {/* Hero */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 22 }}>
        <Eyebrow tone="gold">Season census · {periodLabel(period)}</Eyebrow>
        <h1 style={{
          fontFamily: "var(--font-display)", fontSize: mobile ? 26 : 38, fontWeight: 400,
          letterSpacing: "-0.02em", color: "var(--text-primary)", lineHeight: 1.12, margin: 0,
        }}>
          Twenty clubs, ranked by every model.
        </h1>
        <p style={{
          fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-secondary)",
          maxWidth: mobile ? "100%" : 640, lineHeight: 1.55, margin: 0,
        }}>
          {nModels} models each ranked all {table.length} clubs from first to last. The table below is
          their average — the range shows how far apart they are.
          {mostDivisive && mostDivisive.spread > 0 &&
            ` They disagree most about ${mostDivisive.club}, placed anywhere from ${mostDivisive.best}th to ${mostDivisive.worst}th.`}
        </p>
        {CENSUS.periods.length > 1 && (
          <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 2 }}>
            {CENSUS.periods.map((p) => {
              const on = p === period;
              return (
                <button key={p} onClick={() => setPeriod(p)}
                  style={{
                    padding: "5px 11px", borderRadius: "var(--radius-pill)", cursor: "pointer",
                    border: `1px solid ${on ? "var(--accent)" : "var(--border)"}`,
                    background: on ? "var(--accent-soft)" : "transparent",
                    color: on ? "var(--text-primary)" : "var(--text-secondary)",
                    fontFamily: "var(--font-mono)", fontSize: 11,
                  }}>{periodLabel(p)}</button>
              );
            })}
          </div>
        )}
      </div>

      {/* Headline picks */}
      <div style={{
        display: "grid", gridTemplateColumns: mobile ? "1fr" : "1.25fr 1fr", gap: 16, marginBottom: 22,
      }}>
        <Card padding={18}>
          <Eyebrow rule>Title picks</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: 13 }}>
            {championList.map((c) => (
              <div key={c.club} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{
                  fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-primary)", minWidth: 0,
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1,
                }}>{c.club}</span>
                <div style={{
                  width: 90, height: 6, borderRadius: 3, background: "var(--bg-hover)", overflow: "hidden", flex: "none",
                }}>
                  <div style={{ width: `${(c.votes / nModels) * 100}%`, height: "100%", background: "var(--accent)" }} />
                </div>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)",
                  minWidth: 44, textAlign: "right", flex: "none",
                }}>{c.votes}/{nModels}</span>
              </div>
            ))}
          </div>
        </Card>

        <Card padding={18}>
          <Eyebrow rule>Golden Boot picks</Eyebrow>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 13 }}>
            {topScorers.length === 0 && (
              <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-muted)" }}>—</span>
            )}
            {topScorers.slice(0, 6).map((s) => (
              <div key={s.player} style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)", flex: 1 }}>
                  {s.player}
                </span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)" }}>
                  {s.votes}
                </span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Consensus table */}
      <Eyebrow rule>The consensus table</Eyebrow>
      <Card padding={6} style={{ marginTop: 12, marginBottom: 22 }}>
        <div style={{ display: "flex", flexDirection: "column" }}>
          {table.map((r, i) => {
            const pos = i + 1;
            const zone = pos <= 4 ? "cl" : pos > table.length - 3 ? "rel" : null;
            const edge = zone === "cl" ? "var(--accent)" : zone === "rel" ? "var(--negative)" : "transparent";
            return (
              <div key={r.club} style={{
                display: "flex", alignItems: "center", gap: mobile ? 8 : 12,
                padding: mobile ? "9px 8px" : "10px 12px",
                borderBottom: i === table.length - 1 ? "none" : "1px solid var(--border)",
                borderLeft: `2px solid ${edge}`,
              }}>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)",
                  minWidth: 20, textAlign: "right", flex: "none",
                }}>{pos}</span>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700,
                  color: "var(--text-secondary)", minWidth: 34, flex: "none",
                }}>{r.code}</span>
                {!mobile && (
                  <span style={{
                    fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-primary)",
                    flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                  }}>{r.club}</span>
                )}
                {mobile && <span style={{ flex: 1 }} />}
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)",
                  minWidth: 62, textAlign: "right", flex: "none",
                }} title="range across models">{r.best}–{r.worst}</span>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)",
                  minWidth: 38, textAlign: "right", flex: "none",
                }} title="average predicted position">{r.avg.toFixed(1)}</span>
                {!mobile && (
                  <span style={{ minWidth: 74, textAlign: "right", flex: "none" }}>
                    {r.championVotes > 0 && <Badge tone="gold">{r.championVotes} title</Badge>}
                    {r.championVotes === 0 && r.relegationVotes > 0 &&
                      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-faint)" }}>
                        {r.relegationVotes} down
                      </span>}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </Card>

      {/* Bold calls */}
      <Eyebrow rule>Bold calls</Eyebrow>
      <div style={{ display: "flex", flexDirection: "column", gap: 9, marginTop: 12 }}>
        {models.filter((m) => m.boldCall).map((m) => (
          <Card key={m.id} padding={14}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <button onClick={() => onOpenModel && onOpenModel(m.id)}
                style={{
                  display: "flex", alignItems: "center", gap: 7, cursor: "pointer",
                  background: "transparent", border: "none", padding: 0,
                }}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: m.color, flex: "none" }} />
                <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, color: "var(--text-primary)" }}>
                  {m.name}
                </span>
              </button>
              <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-faint)" }}>
                {m.champion}
              </span>
            </div>
            <p style={{
              fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.5,
              color: "var(--text-secondary)", margin: 0,
            }}>{m.boldCall}</p>
          </Card>
        ))}
      </div>
    </div>
  );
}

window.CensusScreen = CensusScreen;
