/* global React, ReactDOM, window, RankingPage */
// Klax-Stadtradeln-Dashboard — sport-only Produktionsmodus.
// Laedt data/current.json, schreibt die Werte in window.KLAX_* (wie der
// Design-Prototyp es erwartete) und mountet dann <RankingPage variant="sport">.
// Tweaks-Panel und replayKey-Mechanik entfallen in Produktion.

const TWEAKS = {
  bikeMode: "classic",
  speed: 1,
  showRank: true,
  compact: false,
  replayKey: 0,
};

const ACTION_DATES = {
  // Klax-Stadtradeln Berlin 2026 — fest verdrahtet, Design-Vorgabe
  startDate: "2026-05-20",
  endDate: "2026-06-09",
};

function LoadingScreen({ message }) {
  return (
    <div
      style={{
        minHeight: "100vh",
        display: "grid",
        placeItems: "center",
        padding: "40px",
        fontFamily: "'Space Grotesk', system-ui, sans-serif",
        color: "#0a1208",
        background: "#f4f6f1",
      }}
    >
      <div style={{ textAlign: "center" }}>
        <div
          style={{
            fontFamily: "'Archivo Black', system-ui, sans-serif",
            fontSize: "clamp(28px, 5vw, 44px)",
            letterSpacing: "-0.02em",
            textTransform: "uppercase",
          }}
        >
          Klassen-Ranking
        </div>
        <div
          style={{
            marginTop: 16,
            fontSize: 14,
            color: "#536154",
            letterSpacing: "0.04em",
          }}
        >
          {message}
        </div>
      </div>
    </div>
  );
}

function App() {
  const [state, setState] = React.useState({ status: "loading" });

  React.useEffect(() => {
    const url = "./data/current.json?t=" + Date.now();
    fetch(url, { cache: "no-store" })
      .then((r) => {
        if (!r.ok) throw new Error("HTTP " + r.status);
        return r.json();
      })
      .then((d) => {
        window.KLAX_ACTION = {
          school: d.school,
          city: d.kommune,
          startDate: ACTION_DATES.startDate,
          endDate: ACTION_DATES.endDate,
        };
        window.KLAX_CLASSES = (d.teams || [])
          .filter((t) => t && t.km_total != null)
          .map((t) => ({ name: t.name, km: t.km_total }));
        window.KLAX_SCRAPED_AT = d.scraped_at;
        if (window.KLAX_CLASSES.length === 0) {
          setState({ status: "empty" });
          return;
        }
        setState({ status: "ready" });
      })
      .catch((e) => setState({ status: "error", message: String(e.message || e) }));
  }, []);

  if (state.status === "loading") return <LoadingScreen message="Lädt Daten …" />;
  if (state.status === "empty") return <LoadingScreen message="Noch keine Klassen-Daten vorhanden." />;
  if (state.status === "error")
    return <LoadingScreen message={"Konnte Daten nicht laden: " + state.message} />;
  return <RankingPage variant="sport" tweaks={TWEAKS} />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
