import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import Login from "./components/Login";
import { hydrateStore } from "./store/useAppStore";
import { BACKEND } from "./lib/storage";
import { apiStatus } from "./lib/api";
import "./styles.css";

type Phase = "loading" | "login" | "ready";

function Root() {
  const [phase, setPhase] = useState<Phase>("loading");

  useEffect(() => {
    (async () => {
      if (BACKEND === "php") {
        const authed = await apiStatus();
        if (!authed) {
          setPhase("login");
          return;
        }
      }
      await hydrateStore();
      setPhase("ready");
    })();
  }, []);

  if (phase === "loading") {
    return (
      <div className="login-screen">
        <div className="login-logo">
          <span className="logo-flame">🔥</span> Hearth
        </div>
      </div>
    );
  }

  if (phase === "login") {
    return (
      <Login
        onSuccess={async () => {
          await hydrateStore();
          setPhase("ready");
        }}
      />
    );
  }

  return <App />;
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <Root />
  </React.StrictMode>
);

// Register the service worker so Hearth is installable and works offline.
// Only in the built web app (not the Tauri desktop app, not dev).
if (BACKEND !== "tauri" && import.meta.env.PROD && "serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("sw.js").catch((e) => console.error("SW registration failed:", e));
  });
}
