/* Standings — season points grid. Drivers & Constructors, season selector. */
const { useState: useSt, useMemo: useStMemo, useEffect: useStEffect } = React;

const CELL_MODE_KEY = "fd.standings.cellMode";
function loadCellMode() {
  try { return localStorage.getItem(CELL_MODE_KEY) === "position" ? "position" : "points"; }
  catch { return "points"; }
}

function Segmented({ value, options, onChange }) {
  return (
    <div style={{ display: "inline-flex", background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 10, padding: 3, gap: 2 }}>
      {options.map(o => {
        const on = o.value === value;
        return (
          <button key={o.value} onClick={() => onChange(o.value)} style={{ cursor: "pointer", border: "none",
            fontFamily: "var(--mono)", fontSize: 11.5, letterSpacing: ".1em", textTransform: "uppercase", fontWeight: 600,
            padding: "8px 14px", borderRadius: 8, transition: "all .15s",
            background: on ? "var(--accent)" : "transparent", color: on ? "#fff" : "var(--ink-3)" }}>{o.label}</button>
        );
      })}
    </div>
  );
}

function Legend() {
  const items = [["Win", "var(--accent)"], ["Podium", "color-mix(in srgb, var(--ink) 22%, transparent)"], ["Pole (P)", "var(--warn)"], ["Fastest Lap (F)", "#a855f7"], ["DNF", "transparent"]];
  return (
    <div style={{ display: "flex", gap: 18, flexWrap: "wrap", marginTop: 18 }}>
      {items.map(([lab, c]) => (
        <span key={lab} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: ".08em", color: "var(--ink-3)", textTransform: "uppercase" }}>
          <span style={{ width: 13, height: 13, borderRadius: 3, background: c, border: c === "transparent" ? "1px solid var(--line)" : "none" }} />{lab}
        </span>
      ))}
    </div>
  );
}

function cellStyle(o, mode) {
  // o = {pts, pos, dnf}; mode = "points" | "position" (controls displayed text only)
  let bg = "transparent", color = "var(--ink-2)", weight = 500;
  if (o.dnf) return { bg, color: "var(--ink-4)", weight, txt: "DNF", small: true };
  if (o.pos === 1) { bg = "color-mix(in srgb, var(--accent) 26%, transparent)"; color = "var(--ink)"; weight = 800; }
  else if (o.pos <= 3) { bg = "color-mix(in srgb, var(--ink) 9%, transparent)"; color = "var(--ink)"; weight = 700; }
  else if (o.pts > 0) { color = "var(--ink)"; weight = 600; }
  const txt = mode === "position" ? (o.pos ? "P" + o.pos : "–") : (o.pts > 0 ? o.pts : "–");
  return { bg, color, weight, txt, small: false };
}

function DriversGrid({ sid, mode }) {
  const FD = window.FD;
  const sd = FD.seasonData[sid];
  const rounds = sd.byRound;
  const grid = {};
  rounds.forEach(rd => rd.order.forEach(o => { (grid[o.num] = grid[o.num] || {})[rd.rd] = { pts: o.pts, pos: o.pos, dnf: o.dnf, pole: rd.pole === o.num, fastest: !!o.fastest }; }));
  const isS6 = sid === FD.currentSid;
  return (
    <div style={{ overflowX: "auto", border: "1px solid var(--line)", borderRadius: 14, background: "var(--panel)" }}>
      <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 720 }}>
        <thead>
          <tr style={{ borderBottom: "1px solid var(--line)" }}>
            <th style={{ ...thBase, width: 40, textAlign: "center" }}>#</th>
            <th style={{ ...thBase, textAlign: "left", minWidth: 180, position: "sticky", left: 0, background: "var(--panel)", zIndex: 2 }}>Driver</th>
            {rounds.map(rd => (
              <th key={rd.rd} style={{ ...thBase, textAlign: "center", width: 46 }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                  {isS6 && <Flag code={FD.races[rd.rd - 1].country} w={18} />}
                  <span>R{rd.rd}</span>
                </div>
              </th>
            ))}
            <th style={{ ...thBase, textAlign: "right", width: 64, color: "var(--ink-2)", position: "sticky", right: 0, background: "var(--panel)", zIndex: 2 }}>Pts</th>
          </tr>
        </thead>
        <tbody>
          {sd.ranked.map((row, i) => {
            const dr = FD.driverByNum[row.num];
            const team = FD.teamById[FD.driverTeam(row.num, sid)];
            return (
              <tr key={row.num} className="fd-grow" style={{ borderBottom: "1px solid var(--line-soft)", cursor: "pointer" }}
                onClick={() => location.href = `driver.html?d=${row.num}`}
                onMouseEnter={e => e.currentTarget.style.background = "color-mix(in srgb, var(--ink) 4%, transparent)"}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <td style={{ ...tdBase, textAlign: "center" }}><span className="display" style={{ fontSize: 19, color: i === 0 ? "var(--accent)" : "var(--ink-3)" }}>{i + 1}</span></td>
                <td style={{ ...tdBase, textAlign: "left", position: "sticky", left: 0, background: "var(--panel)", zIndex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                    <span style={{ width: 4, height: 30, borderRadius: 2, background: team.color, flex: "none" }} />
                    <Avatar driver={dr} size={32} ring={false} />
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontFamily: "var(--ui)", fontWeight: 700, fontSize: 14.5, color: "var(--ink)", whiteSpace: "nowrap" }}>{dr.username}</div>
                      <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-4)", letterSpacing: ".06em" }}>{dr.code} · {team.code} · #{dr.num}</div>
                    </div>
                  </div>
                </td>
                {rounds.map(rd => {
                  const o = grid[row.num][rd.rd];
                  if (!o) return <td key={rd.rd} style={{ ...tdBase, textAlign: "center", color: "var(--ink-4)", fontFamily: "var(--mono)", fontSize: 12 }}>·</td>;
                  const cs = cellStyle(o, mode);
                  return (
                    <td key={rd.rd} style={{ ...tdBase, textAlign: "center", padding: 0 }} title={o.dnf ? "DNF" : `P${o.pos} · ${o.pts} pts${o.pole ? " · Pole" : ""}${o.fastest ? " · Fastest Lap" : ""}`}>
                      <div style={{ margin: "4px 3px", padding: "8px 0", borderRadius: 7, background: cs.bg, position: "relative",
                        fontFamily: "var(--mono)", fontVariantNumeric: "tabular-nums", fontWeight: cs.weight,
                        fontSize: cs.small ? 9 : 14, color: cs.color }}>
                        {cs.txt}
                        {o.pole && <span style={{ position: "absolute", top: 1, right: 3, fontSize: 7.5, color: "var(--warn)", fontWeight: 700 }}>P</span>}
                        {o.fastest && <span style={{ position: "absolute", top: 1, left: 3, fontSize: 7.5, color: "#a855f7", fontWeight: 700 }}>F</span>}
                      </div>
                    </td>
                  );
                })}
                <td style={{ ...tdBase, textAlign: "right", position: "sticky", right: 0, background: "var(--panel)", zIndex: 1 }}>
                  <AnimatedNumber value={row.points} duration={900} className="display" style={{ fontSize: 22, color: "var(--ink)" }} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function ConstructorsGrid({ sid }) {
  const FD = window.FD;
  const sd = FD.seasonData[sid];
  const rounds = sd.byRound;
  const standings = FD.teamStandings(sid).filter(t => t.roster.length);
  // team points per round
  const teamRound = (teamId, rd) => rd.order.filter(o => FD.driverTeam(o.num, sid) === teamId).reduce((a, o) => a + o.pts, 0);
  const isS6 = sid === FD.currentSid;
  return (
    <div style={{ overflowX: "auto", border: "1px solid var(--line)", borderRadius: 14, background: "var(--panel)" }}>
      <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 720 }}>
        <thead>
          <tr style={{ borderBottom: "1px solid var(--line)" }}>
            <th style={{ ...thBase, width: 40, textAlign: "center" }}>#</th>
            <th style={{ ...thBase, textAlign: "left", minWidth: 180, position: "sticky", left: 0, background: "var(--panel)", zIndex: 2 }}>Constructor</th>
            {rounds.map(rd => (
              <th key={rd.rd} style={{ ...thBase, textAlign: "center", width: 46 }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                  {isS6 && <Flag code={FD.races[rd.rd - 1].country} w={18} />}<span>R{rd.rd}</span>
                </div>
              </th>
            ))}
            <th style={{ ...thBase, textAlign: "right", width: 64, color: "var(--ink-2)", position: "sticky", right: 0, background: "var(--panel)", zIndex: 2 }}>Pts</th>
          </tr>
        </thead>
        <tbody>
          {standings.map((t, i) => (
            <tr key={t.id} className="fd-grow" style={{ borderBottom: "1px solid var(--line-soft)", cursor: "pointer" }}
              onClick={() => location.href = `team.html?t=${t.id}`}
              onMouseEnter={e => e.currentTarget.style.background = "color-mix(in srgb, var(--ink) 4%, transparent)"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <td style={{ ...tdBase, textAlign: "center" }}><span className="display" style={{ fontSize: 19, color: i === 0 ? "var(--accent)" : "var(--ink-3)" }}>{i + 1}</span></td>
              <td style={{ ...tdBase, textAlign: "left", position: "sticky", left: 0, background: "var(--panel)", zIndex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                  <TeamLogo team={t} size={26} />
                  <span className="display" style={{ fontSize: 20, color: "var(--ink)", whiteSpace: "nowrap" }}>{t.name}</span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-4)" }}>{t.code}</span>
                </div>
              </td>
              {rounds.map(rd => {
                const pts = teamRound(t.id, rd);
                return (
                  <td key={rd.rd} style={{ ...tdBase, textAlign: "center", fontFamily: "var(--mono)", fontVariantNumeric: "tabular-nums",
                    fontSize: 13, color: pts > 0 ? "var(--ink)" : "var(--ink-4)", fontWeight: pts >= 25 ? 700 : 500 }}>{pts > 0 ? pts : "–"}</td>
                );
              })}
              <td style={{ ...tdBase, textAlign: "right", position: "sticky", right: 0, background: "var(--panel)", zIndex: 1 }}>
                <AnimatedNumber value={t.points} duration={900} className="display" style={{ fontSize: 22, color: "var(--ink)" }} />
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

const thBase = { fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)", fontWeight: 500, padding: "13px 8px" };
const tdBase = { padding: "9px 8px", verticalAlign: "middle" };

function StandingsPage() {
  const FD = window.FD;
  const [sid, setSid] = useSt(FD.currentSid);
  const [tab, setTab] = useSt("drivers");
  const [cellMode, setCellMode] = useSt(loadCellMode);
  useStEffect(() => { try { localStorage.setItem(CELL_MODE_KEY, cellMode); } catch {} }, [cellMode]);
  const season = FD.seasons.find(s => s.id === sid);
  return (
    <div style={{ maxWidth: 1280, margin: "0 auto", padding: "48px 36px 90px" }}>
      <PageHead kicker={`${season.label} · ${season.status === "live" ? `Round ${season.completed} of ${season.rounds}` : "Final"}`} title="Standings"
        right={
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            <Segmented value={sid} onChange={setSid} options={FD.seasons.map(s => ({ value: s.id, label: s.label.replace("Season ", "S") }))} />
            <Segmented value={tab} onChange={setTab} options={[{ value: "drivers", label: "Drivers" }, { value: "constructors", label: "Teams" }]} />
            {tab === "drivers" && <Segmented value={cellMode} onChange={setCellMode} options={[{ value: "points", label: "Points" }, { value: "position", label: "Position" }]} />}
          </div>
        } />
      <div key={sid + tab}>
        {tab === "drivers" ? <DriversGrid sid={sid} mode={cellMode} /> : <ConstructorsGrid sid={sid} />}
      </div>
      <Legend />
      <p style={{ fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-4)", marginTop: 22, maxWidth: "70ch", lineHeight: 1.5 }}>
        Each cell shows {tab === "drivers" && cellMode === "position" ? "the finishing position" : "points scored"} that round. {season.status === "live" ? `${season.rounds - season.completed} rounds remain this season.` : "Season complete."} Click any row for the full profile.
      </p>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<SiteChrome active="standings"><StandingsPage /></SiteChrome>);
