// standings.jsx — Championship standings + race results
const { useState: useStS, useEffect: useStE } = React;

const PTS_SCALE = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1];

function calcPoints(position, fastestLap, dnf, dsq) {
  if (dnf || dsq || !position) return 0;
  const base = PTS_SCALE[position - 1] || 0;
  return base + (fastestLap ? 1 : 0);
}

/* ── Medal colors ── */
function PosBadge({ pos }) {
  const colors = { 1: "#FFD700", 2: "#C0C0C8", 3: "#CD7F32" };
  const bg = colors[pos] || "var(--panel2)";
  const ink = pos <= 3 ? "#0a0a0a" : "var(--text)";
  return (
    <div style={{ width: 28, height: 28, borderRadius: 4, background: bg, color: ink, display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--display)", fontWeight: 700, fontSize: 13 }}>
      {pos}
    </div>
  );
}

/* ── Championship Standings ── */
function ChampionshipTab({ results, races }) {
  const { t } = useT();
  const raceMap = {};
  races.forEach(r => { raceMap[r.id] = r; });
  const completedRaceIds = [...new Set(results.map(r => r.race_id))];
  const completedRaces = completedRaceIds
    .map(id => raceMap[id] || { id, name: id, round: 0 })
    .sort((a, b) => (a.round || 0) - (b.round || 0));

  /* group by pilot */
  const drivers = {};
  results.forEach(r => {
    if (!drivers[r.pilot_name]) {
      drivers[r.pilot_name] = {
        name: r.pilot_name, car_number: r.car_number, car: r.car,
        team: r.team_name, points: 0, wins: 0, podiums: 0,
        races: 0, fastestLaps: 0, byRace: {}
      };
    }
    const d = drivers[r.pilot_name];
    d.points += r.points || 0;
    d.races += 1;
    if (r.position === 1) d.wins += 1;
    if (r.position <= 3 && !r.dnf && !r.dsq) d.podiums += 1;
    if (r.fastest_lap) d.fastestLaps += 1;
    d.byRace[r.race_id] = { pos: r.position, pts: r.points, fl: r.fastest_lap, dnf: r.dnf, dsq: r.dsq };
  });

  const standings = Object.values(drivers).sort((a, b) => b.points - a.points || b.wins - a.wins);

  if (standings.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "60px 20px", color: "var(--muted)", fontFamily: "var(--mono)", fontSize: 14 }}>
        {t("standings.empty")}
      </div>
    );
  }

  const thS = { padding: "10px 12px", textAlign: "left", fontFamily: "var(--mono)", fontSize: "10px", letterSpacing: "0.12em", color: "var(--muted)", fontWeight: 400, whiteSpace: "nowrap", borderBottom: "1px solid var(--line)" };
  const tdS = { padding: "12px 12px", verticalAlign: "middle", borderBottom: "1px solid rgba(255,255,255,0.04)" };

  return (
    <div style={{ overflowX: "auto" }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead>
          <tr style={{ background: "var(--panel)" }}>
            <th style={{ ...thS, width: 40 }}>P</th>
            <th style={{ ...thS }}>{t("standings.col.driver")}</th>
            <th style={{ ...thS }}>{t("standings.col.car")}</th>
            <th style={{ ...thS, textAlign: "center" }}>{t("standings.col.races")}</th>
            <th style={{ ...thS, textAlign: "center" }}>{t("standings.col.wins")}</th>
            <th style={{ ...thS, textAlign: "center" }}>{t("standings.col.podiums")}</th>
            <th style={{ ...thS, textAlign: "center" }}>FL</th>
            {completedRaces.map(r => (
              <th key={r.id} style={{ ...thS, textAlign: "center" }}>RND {String(r.round).padStart(2,"00")}</th>
            ))}
            <th style={{ ...thS, textAlign: "right", color: "var(--accent)", fontSize: 12 }}>PTS</th>
          </tr>
        </thead>
        <tbody>
          {standings.map((d, i) => (
            <tr key={d.name} style={{ background: i === 0 ? "rgba(255,215,0,0.04)" : "transparent" }}>
              <td style={{ ...tdS, paddingLeft: 8 }}><PosBadge pos={i + 1} /></td>
              <td style={{ ...tdS }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{d.name}</div>
                {d.team && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{d.team}</div>}
              </td>
              <td style={{ ...tdS }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {d.car_number && <span style={{ fontFamily: "var(--display)", fontWeight: 700, color: "var(--accent)", fontSize: 15 }}>#{d.car_number}</span>}
                  <span style={{ fontSize: 11, color: "var(--muted)" }}>{d.car}</span>
                </div>
              </td>
              <td style={{ ...tdS, textAlign: "center", fontFamily: "var(--mono)" }}>{d.races}</td>
              <td style={{ ...tdS, textAlign: "center", fontFamily: "var(--mono)", color: d.wins > 0 ? "#FFD700" : "var(--muted)" }}>{d.wins}</td>
              <td style={{ ...tdS, textAlign: "center", fontFamily: "var(--mono)" }}>{d.podiums}</td>
              <td style={{ ...tdS, textAlign: "center", fontFamily: "var(--mono)", color: d.fastestLaps > 0 ? "#b44fff" : "var(--muted)" }}>{d.fastestLaps > 0 ? "⬤" : "—"}</td>
              {completedRaces.map(r => {
                const br = d.byRace[r.id];
                return (
                  <td key={r.id} style={{ ...tdS, textAlign: "center", fontFamily: "var(--mono)", fontSize: 12 }}>
                    {br ? (
                      <span style={{ color: br.dnf || br.dsq ? "var(--accent)" : br.pts > 0 ? "var(--text)" : "var(--muted)" }}>
                        {br.dnf ? "DNF" : br.dsq ? "DSQ" : br.pos ? `P${br.pos}` : "—"}
                        {br.fl && <span style={{ color: "#b44fff", marginLeft: 2 }}>●</span>}
                        {br.pts > 0 && <div style={{ fontSize: 10, color: "var(--muted)" }}>{br.pts}p</div>}
                      </span>
                    ) : <span style={{ color: "var(--faint)" }}>—</span>}
                  </td>
                );
              })}
              <td style={{ ...tdS, textAlign: "right", fontFamily: "var(--display)", fontWeight: 700, fontSize: 20, color: "var(--accent)" }}>
                {d.points}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <div style={{ padding: "12px 12px", fontFamily: "var(--mono)", fontSize: 11, color: "var(--faint)", display: "flex", gap: 20 }}>
        <span><span style={{ color: "#b44fff" }}>●</span> Fastest lap (+1 pt)</span>
        <span><span style={{ color: "#FFD700" }}>P1</span> = {t("standings.legend.win")}</span>
        <span>{t("standings.legend.pts")}</span>
      </div>
    </div>
  );
}

/* ── Race Results ── */
function RaceResultsTab({ results, races }) {
  const { t } = useT();
  const completedRaceIds = [...new Set(results.map(r => r.race_id))];
  const raceMap = {};
  races.forEach(r => { raceMap[r.id] = r; });
  // Fallback: if race details aren't loaded yet, still show the round using a placeholder
  const completedRaces = completedRaceIds
    .map(id => raceMap[id] || { id, name: id, round: 0, laps: null, durMin: null })
    .sort((a, b) => (a.round || 0) - (b.round || 0));

  const [selRace, setSelRace] = useStS(completedRaces[0]?.id || null);

  if (completedRaces.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "60px 20px", color: "var(--muted)", fontFamily: "var(--mono)", fontSize: 14 }}>
        {t("standings.noRounds")}
      </div>
    );
  }

  const raceResults = results.filter(r => r.race_id === selRace).sort((a, b) => {
    if (a.dnf || a.dsq) return 1;
    if (b.dnf || b.dsq) return -1;
    return (a.position || 99) - (b.position || 99);
  });

  const race = raceMap[selRace];

  const thS = { padding: "10px 12px", textAlign: "left", fontFamily: "var(--mono)", fontSize: "10px", letterSpacing: "0.12em", color: "var(--muted)", fontWeight: 400, borderBottom: "1px solid var(--line)" };
  const tdS = { padding: "12px 12px", verticalAlign: "middle", borderBottom: "1px solid rgba(255,255,255,0.04)" };

  return (
    <div>
      {/* Race selector */}
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
        {completedRaces.map(r => (
          <button key={r.id} onClick={() => setSelRace(r.id)}
            style={{ padding: "6px 14px", fontFamily: "var(--mono)", fontSize: 11, cursor: "pointer", border: "1px solid", borderRadius: 4,
              background: selRace === r.id ? "var(--accent)" : "var(--panel)",
              color: selRace === r.id ? "var(--accent-ink)" : "var(--text)",
              borderColor: selRace === r.id ? "var(--accent)" : "var(--line)" }}>
            RND {String(r.round).padStart(2,"0")} · {r.name}
          </button>
        ))}
      </div>

      {/* Race header */}
      {race && (
        <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 16, padding: "14px 16px", background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 4 }}>
          <div style={{ fontFamily: "var(--display)", fontSize: 22, fontWeight: 700, letterSpacing: 2 }}>
            {race.round ? race.name.toUpperCase() : "ROUND"}
          </div>
          {race.round > 0 && (
            <div style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>
              RND {String(race.round).padStart(2,"0")}{race.laps ? ` · ${race.laps} ${t("standings.laps")}` : ""}{race.durMin ? ` · ${race.durMin} MIN` : ""}
            </div>
          )}
        </div>
      )}

      {/* Results table */}
      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead>
            <tr style={{ background: "var(--panel)" }}>
              <th style={{ ...thS, width: 40 }}>POS</th>
              <th style={{ ...thS, width: 50 }}>#</th>
              <th style={{ ...thS }}>{t("standings.col.driver")}</th>
              <th style={{ ...thS }}>{t("standings.col.car")}</th>
              <th style={{ ...thS }}>{t("standings.col.team")}</th>
              <th style={{ ...thS, textAlign: "center" }}>FL</th>
              <th style={{ ...thS, textAlign: "right" }}>PTS</th>
            </tr>
          </thead>
          <tbody>
            {raceResults.map((r, i) => (
              <tr key={r.id} style={{ background: i === 0 ? "rgba(255,215,0,0.04)" : "transparent" }}>
                <td style={{ ...tdS, paddingLeft: 8 }}>
                  {r.dnf ? <span style={{ color: "var(--accent)", fontFamily: "var(--mono)", fontSize: 11 }}>DNF</span>
                    : r.dsq ? <span style={{ color: "var(--accent)", fontFamily: "var(--mono)", fontSize: 11 }}>DSQ</span>
                    : <PosBadge pos={r.position} />}
                </td>
                <td style={{ ...tdS, fontFamily: "var(--display)", fontWeight: 700, color: "var(--accent)", fontSize: 16 }}>
                  {r.car_number ? `#${r.car_number}` : "—"}
                </td>
                <td style={{ ...tdS, fontWeight: 600 }}>{r.pilot_name}</td>
                <td style={{ ...tdS, color: "var(--muted)", fontSize: 12 }}>{r.car || "—"}</td>
                <td style={{ ...tdS, color: "var(--muted)", fontSize: 12 }}>{r.team_name || "—"}</td>
                <td style={{ ...tdS, textAlign: "center" }}>
                  {r.fastest_lap && <span style={{ color: "#b44fff", fontSize: 16 }}>⬤</span>}
                </td>
                <td style={{ ...tdS, textAlign: "right", fontFamily: "var(--display)", fontWeight: 700, fontSize: 18, color: r.points > 0 ? "var(--accent)" : "var(--muted)" }}>
                  {r.points || 0}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ── Main Standings Page ── */
function StandingsPage({ races }) {
  const [results, setResults] = useStS([]);
  const [loading, setLoading] = useStS(true);
  const [activeTab, setActiveTab] = useStS("championship");

  useStE(() => {
    async function load() {
      if (!window.sbClient) { setLoading(false); return; }
      const { data } = await window.sbClient.from('race_results').select('*').order('race_id').order('position');
      setResults(data || []);
      setLoading(false);
    }
    load();
  }, []);

  const { t } = useT();

  const tabBtn = (id, label) => (
    <button onClick={() => setActiveTab(id)} style={{
      padding: "10px 24px", fontFamily: "var(--display)", fontSize: 14, fontWeight: 700,
      letterSpacing: "1px", cursor: "pointer", border: "none", borderBottom: "3px solid",
      background: "transparent",
      color: activeTab === id ? "var(--accent)" : "var(--muted)",
      borderBottomColor: activeTab === id ? "var(--accent)" : "transparent",
      transition: "all .2s"
    }}>{label}</button>
  );

  return (
    <div>
      <section className="section wrap" style={{ paddingBottom: 20 }}>
        <span className="eyebrow">IRON GT SERIES · {SEASON.year}</span>
        <h1 className="display" style={{ fontSize: "clamp(40px,6vw,80px)", marginTop: 16 }}>{t("standings.title")}</h1>
        <p className="lead" style={{ maxWidth: 540, marginTop: 12, color: "var(--muted)", fontSize: 17 }}>
          {t("standings.lead")}
        </p>
      </section>

      <section className="wrap" style={{ paddingBottom: 80 }}>
        {/* Tab bar */}
        <div style={{ display: "flex", borderBottom: "1px solid var(--line)", marginBottom: 24, gap: 4 }}>
          {tabBtn("championship", t("standings.tab.general"))}
          {tabBtn("results", t("standings.tab.rounds"))}
        </div>

        {loading ? (
          <div style={{ textAlign: "center", padding: 60, fontFamily: "var(--mono)", color: "var(--muted)" }}>{t("standings.loading")}</div>
        ) : (
          <div style={{ background: "var(--panel)", border: "1px solid var(--line)", borderRadius: 4, overflow: "hidden" }}>
            {activeTab === "championship" && <ChampionshipTab results={results} races={races} />}
            {activeTab === "results" && <RaceResultsTab results={results} races={races} />}
          </div>
        )}
      </section>
    </div>
  );
}

Object.assign(window, { StandingsPage });
