// ============================================================
// App router + mounting
// ============================================================

const { Header: AppHeader } = window.OwithuComponents;
const { HomePage } = window.OwithuHome;
const { IndustryPage } = window.OwithuIndustry;
const { CollectionsPage } = window.OwithuCollections;
const { CollectionDetailPage, AboutPage, OfertaPage } = window.OwithuPages;
const { useState: aUseState, useEffect: aUseEffect } = React;

const ROUTE_NAMES = ["home", "restaurante", "cafenele", "hoteluri", "colectii", "despre", "oferta"];

function App() {
  const [route, setRoute] = aUseState("home");
  const [detailSlug, setDetailSlug] = aUseState(null);

  // Hash routing
  aUseEffect(() => {
    const parse = () => {
      const hash = window.location.hash.replace(/^#/, "") || "home";
      if (hash.startsWith("colectie/")) {
        const slug = hash.split("/")[1];
        setDetailSlug(slug);
        setRoute("colectie");
      } else if (ROUTE_NAMES.includes(hash)) {
        setRoute(hash);
        setDetailSlug(null);
      } else {
        setRoute("home");
        setDetailSlug(null);
      }
      window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
    };
    parse();
    window.addEventListener("hashchange", parse);
    return () => window.removeEventListener("hashchange", parse);
  }, []);

  const navigate = (r) => {
    window.location.hash = r;
  };

  let pageContent;
  let darkHeader = false;
  let activeRoute = route;
  switch (route) {
    case "home":
      pageContent = <HomePage navigate={navigate} />;
      activeRoute = "home";
      break;
    case "restaurante":
    case "cafenele":
    case "hoteluri":
      pageContent = <IndustryPage slug={route} navigate={navigate} />;
      break;
    case "colectii":
      pageContent = <CollectionsPage navigate={navigate} />;
      break;
    case "colectie":
      pageContent = <CollectionDetailPage slug={detailSlug} navigate={navigate} />;
      activeRoute = "colectii";
      break;
    case "despre":
      pageContent = <AboutPage navigate={navigate} />;
      break;
    case "oferta":
      pageContent = <OfertaPage navigate={navigate} />;
      break;
    default:
      pageContent = <HomePage navigate={navigate} />;
  }

  return (
    <React.Fragment>
      <AppHeader route={activeRoute} navigate={navigate} dark={darkHeader} />
      {pageContent}
    </React.Fragment>
  );
}

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