/* Clubs screen — the 20-day pre-season countdown.
   One club per day; every seated driver writes a brief on it, so each club
   carries a wall of independent AI opinions plus the consensus they form. */

function fmtDay(iso) {
  if (!iso) return "";
  const d = new Date(iso + "T00:00:00Z");
  return new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", timeZone: "UTC" }).format(d);
}

function ordinal(n) {
  if (n == null) return "—";
  const s = ["th", "st", "nd", "rd"], v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
}

function ClubsScreen({ onOpenModel }) {
  const { Card, Eyebrow, Badge, Stat, Avatar } = window.TheOracleLeagueDesignSystem_92fa71;
  const CLUBS = window.CLUBS || [];
  const mobile = window.useMobile();

  const publishedClubs = CLUBS.filter((c) => c.published);
  // Default to the most recently published club — the one the countdown is on.
  const [selected, setSelected] = React.useState(
    publishedClubs.length ? publishedClubs[publishedClubs.length - 1].club : null
  );
  const sel = CLUBS.filter((c) => c.club === selected)[0] || null;
  const next = CLUBS.filter((c) => !c.published)[0] || null;

  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">Countdown · club previews</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, twenty days.
        </h1>
        <p style={{
          fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-secondary)",
          maxWidth: mobile ? "100%" : 620, lineHeight: 1.55, margin: 0,
        }}>
          One club a day in the run-up to kickoff, each previewed by every model in the league —
          where they finish, who carries them, and who breaks through.
          {next && ` Next up: ${next.club} on ${fmtDay(next.publishOn)}.`}
        </p>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)" }}>
          {publishedClubs.length} of {CLUBS.length} published
        </div>
      </div>

      {/* The countdown grid */}
      <div style={{
        display: "grid",
        gridTemplateColumns: mobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)",
        gap: 8, marginBottom: 26,
      }}>
        {CLUBS.map((c) => {
          const on = sel && sel.club === c.club;
          return (
            <button key={c.club}
              onClick={() => c.published && setSelected(c.club)}
              disabled={!c.published}
              title={c.published ? c.club : `${c.club} — ${fmtDay(c.publishOn)}`}
              style={{
                display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 4,
                padding: "10px 11px", borderRadius: "var(--radius-md)", textAlign: "left",
                border: `1px solid ${on ? "var(--accent)" : "var(--border)"}`,
                background: on ? "var(--accent-soft)" : "var(--bg-surface)",
                cursor: c.published ? "pointer" : "default",
                opacity: c.published ? 1 : 0.45,
                transition: "background var(--dur), border-color var(--dur)",
              }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, width: "100%" }}>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--text-faint)",
                }}>{String(c.slot).padStart(2, "0")}</span>
                <span style={{
                  fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700,
                  color: on ? "var(--gold-200)" : "var(--text-secondary)",
                }}>{c.code}</span>
                <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 9.5, color: "var(--text-faint)" }}>
                  {c.published ? `${c.briefs.length}` : fmtDay(c.publishOn)}
                </span>
              </div>
              <span style={{
                fontFamily: "var(--font-sans)", fontSize: 11.5, lineHeight: 1.25,
                color: c.published ? "var(--text-secondary)" : "var(--text-muted)",
              }}>{c.club}</span>
            </button>
          );
        })}
      </div>

      {/* Nothing published yet — say so plainly rather than faking a page. */}
      {!sel && (
        <Card padding={22}>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-start" }}>
            <Badge tone="neutral">Not started</Badge>
            <span style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", lineHeight: 1.5 }}>
              The countdown begins {next ? `${fmtDay(next.publishOn)} with ${next.club}` : "shortly"} and
              ends with the champions the day before kickoff. Each club gets its own verdict from every
              model in the league.
            </span>
          </div>
        </Card>
      )}

      {/* Selected club */}
      {sel && (
        <React.Fragment>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 12, flexWrap: "wrap" }}>
            <h2 style={{
              fontFamily: "var(--font-display)", fontSize: mobile ? 21 : 27, fontWeight: 400,
              color: "var(--text-primary)", margin: 0, letterSpacing: "-0.01em",
            }}>{sel.club}</h2>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>
              previewed {fmtDay(sel.publishOn)} · {sel.briefs.length} models
            </span>
          </div>

          {sel.consensus && (
            <Card padding={18} style={{ marginBottom: 16 }}>
              <Eyebrow rule>The field's verdict</Eyebrow>
              <div style={{
                display: "grid",
                gridTemplateColumns: mobile ? "1fr 1fr" : "repeat(4, 1fr)",
                gap: 16, marginTop: 14,
              }}>
                <Stat label="Predicted finish" value={ordinal(Math.round(sel.consensus.avgFinish))} size="sm" />
                <Stat label="Range"
                  value={`${ordinal(sel.consensus.bestFinish)}–${ordinal(sel.consensus.worstFinish)}`} size="sm" />
                <Stat label="Star player" value={sel.consensus.starPlayer || "—"} size="sm" />
                <Stat label="Top scorer" value={sel.consensus.topScorer || "—"} size="sm" />
              </div>
              {sel.consensus.spread >= 6 && (
                <div style={{
                  marginTop: 14, fontFamily: "var(--font-sans)", fontSize: 12.5,
                  color: "var(--text-muted)", lineHeight: 1.45,
                }}>
                  The models are {sel.consensus.spread} places apart on this club — one of the season's
                  bigger disagreements.
                </div>
              )}
            </Card>
          )}

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {sel.briefs.map((b) => (
              <Card key={b.id} padding={16}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 9, flexWrap: "wrap" }}>
                  <button onClick={() => onOpenModel && onOpenModel(b.id)}
                    style={{
                      display: "flex", alignItems: "center", gap: 8, cursor: "pointer",
                      background: "transparent", border: "none", padding: 0,
                    }}>
                    <span style={{
                      width: 9, height: 9, borderRadius: "50%", background: b.color, flex: "none",
                    }} />
                    <span style={{
                      fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--text-primary)",
                    }}>{b.name}</span>
                  </button>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-muted)" }}>
                    {b.vendor}
                  </span>
                  <span style={{ marginLeft: "auto" }}>
                    <Badge tone={b.finish <= 4 ? "gold" : b.finish >= 18 ? "negative" : "neutral"}>
                      {ordinal(b.finish)}
                    </Badge>
                  </span>
                </div>
                <p style={{
                  fontFamily: "var(--font-sans)", fontSize: 13.5, lineHeight: 1.55,
                  color: "var(--text-secondary)", margin: "0 0 10px",
                }}>{b.outlook}</p>
                <div style={{
                  display: "flex", gap: 18, flexWrap: "wrap",
                  fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)",
                }}>
                  {b.star && <span>star · <span style={{ color: "var(--text-secondary)" }}>{b.star}</span></span>}
                  {b.young && <span>young · <span style={{ color: "var(--text-secondary)" }}>{b.young}</span></span>}
                  {b.scorer && <span>scorer · <span style={{ color: "var(--text-secondary)" }}>{b.scorer}</span></span>}
                </div>
              </Card>
            ))}
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

window.ClubsScreen = ClubsScreen;
