// Boot React — préchauffe l'API avant de rendre la page.
// Chaque page enregistre son composant dans window.PAGES[<routeKey>] puis
// ce bootstrap fait :
//   1. petit splash de loading dans #app
//   2. window.API.preload(page, id) → remplit window.USERS / PROJECTS / ...
//   3. ReactDOM.createRoot(...).render(<App />) (rendu sync, data déjà là)
//
// L'avantage : les composants des pages restent synchrones, ils
// continuent à lire window.X comme avant.

window.PAGES = window.PAGES || {};
window.AppUI = {
  notice(message) {
    window.dispatchEvent(new CustomEvent("app:notice", { detail: { message } }));
  },
};

function App() {
  const route = {
    page: window.AppRouter.currentPage(),
    id:   window.AppRouter.currentId(),
  };
  const setRoute = window.AppRouter.navigate;

  // `tick` change à chaque `window.API.refresh()` → on remonte la page
  // via `key={tick}`. C'est plus simple que de propager du state à
  // travers tous les composants existants.
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const onRefresh = () => setTick((t) => t + 1);
    window.addEventListener("app:refresh", onRefresh);
    return () => window.removeEventListener("app:refresh", onRefresh);
  }, []);

  const PageComponent = window.PAGES[route.page] || window.PAGES.dashboard;

  return (
    <div className="app">
      <Sidebar route={route} setRoute={setRoute} key={`sb-${tick}`} />
      <main className="main" data-screen-label={route.page}>
        <PageComponent setRoute={setRoute} id={route.id} key={`pg-${tick}`} />
      </main>
      <ToastHost />
    </div>
  );
}

function ToastHost() {
  const [notice, setNotice] = React.useState(null);

  React.useEffect(() => {
    let timer = null;
    const onNotice = (event) => {
      setNotice(event.detail);
      window.clearTimeout(timer);
      timer = window.setTimeout(() => setNotice(null), 2800);
    };
    window.addEventListener("app:notice", onNotice);
    return () => {
      window.clearTimeout(timer);
      window.removeEventListener("app:notice", onNotice);
    };
  }, []);

  if (!notice) return null;
  return (
    <div style={{
      position: "fixed",
      right: 24,
      bottom: 24,
      zIndex: 50,
      maxWidth: 360,
      padding: "11px 14px",
      borderRadius: 8,
      border: "1px solid var(--border)",
      background: "var(--surface)",
      color: "var(--fg)",
      boxShadow: "0 16px 40px rgba(0,0,0,.28)",
      fontSize: 12.5,
    }}>
      {notice.message}
    </div>
  );
}

function LoadingShell({ label }) {
  return (
    <div style={{
      position: "fixed", inset: 0,
      display: "grid", placeItems: "center",
      background: "var(--bg, #1a1d22)", color: "var(--fg-3, #888)",
      fontFamily: "var(--font-sans, system-ui)", fontSize: 13,
    }}>
      <div style={{ textAlign: "center" }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          border: "2px solid var(--border, #2c313a)",
          borderTopColor: "var(--accent, #7ad9a3)",
          margin: "0 auto 14px",
          animation: "twk-spin 0.7s linear infinite",
        }} />
        <div>{label}</div>
        <style>{`@keyframes twk-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    </div>
  );
}

function ErrorShell({ error }) {
  return (
    <div style={{
      position: "fixed", inset: 0,
      display: "grid", placeItems: "center",
      background: "var(--bg, #1a1d22)", color: "var(--fg, #eee)",
      fontFamily: "var(--font-sans, system-ui)", fontSize: 13, padding: 24,
    }}>
      <div style={{ maxWidth: 520, textAlign: "center" }}>
        <div style={{ fontSize: 22, marginBottom: 8 }}>⚠️ Données indisponibles</div>
        <div style={{ color: "var(--fg-3)", marginBottom: 16 }}>
          Le serveur API n'a pas pu être joint, ou la base de données ne répond pas.
        </div>
        <pre style={{
          background: "var(--surface, #22262e)", padding: 12, borderRadius: 6,
          textAlign: "left", overflow: "auto", fontSize: 11.5,
        }}>{String(error?.message || error)}</pre>
        <div style={{ marginTop: 16, fontSize: 11.5, color: "var(--fg-4)" }}>
          Lancer le backend : <code>npm run dev</code>
        </div>
      </div>
    </div>
  );
}

async function start() {
  const root = ReactDOM.createRoot(document.getElementById("app"));

  // 1. Splash pendant le fetch
  root.render(<LoadingShell label="Chargement…" />);

  try {
    const page = window.AppRouter.currentPage();
    const id   = window.AppRouter.currentId();
    await window.API.preload(page, id);
  } catch (e) {
    console.error(e);
    root.render(<ErrorShell error={e} />);
    return;
  }

  // 2. Rendu réel
  root.render(<App />);
}

start();
