// Routeur applicatif minimaliste — hashrouter pour permettre les liens partageables
const { TopBar, ToastProvider } = window.UI;
const { ScreenListeRecettes, ScreenEditRecette, ScreenFaconnages, ScreenIncorporations, ScreenArticles } = window.Screens;

function parseHash() {
  const h = window.location.hash.replace(/^#/, "");
  if (!h || h === "/") return { name: "recettes" };
  const parts = h.split("/").filter(Boolean);
  if (parts[0] === "recette" && parts[1]) return { name: "recette", id: parts[1] };
  if (parts[0] === "faconnages") return { name: "faconnages" };
  if (parts[0] === "incorporations") return { name: "incorporations" };
  if (parts[0] === "articles") return { name: "articles" };
  return { name: "recettes" };
}

function routeToHash(route) {
  if (route.name === "recettes") return "#/";
  if (route.name === "recette")  return `#/recette/${route.id}`;
  return `#/${route.name}`;
}

function App() {
  const [route, setRoute] = React.useState(parseHash());

  React.useEffect(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const goRoute = (r) => {
    const h = routeToHash(r);
    if (window.location.hash !== h) window.location.hash = h;
    else setRoute(r);
  };

  let screen = null;
  if (route.name === "recettes")        screen = <ScreenListeRecettes goRoute={goRoute} />;
  else if (route.name === "recette")    screen = <ScreenEditRecette recetteId={route.id} goRoute={goRoute} />;
  else if (route.name === "faconnages") screen = <ScreenFaconnages />;
  else if (route.name === "incorporations") screen = <ScreenIncorporations />;
  else if (route.name === "articles")   screen = <ScreenArticles />;

  return (
    <ToastProvider>
      <div className="min-h-full">
        <TopBar route={route} goRoute={goRoute} />
        {screen}
        <footer className="max-w-6xl mx-auto px-6 py-8 text-xs text-[var(--ink-faint)] text-center">
          La Mie Dorée Ariégeoise · Référentiel recettes ·{" "}
          <a href="/docs" className="underline-offset-2 hover:underline" target="_blank" rel="noreferrer">API Swagger</a>
        </footer>
      </div>
    </ToastProvider>
  );
}

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