import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom/client";
import { SectionStack } from "./app/SectionStack";
import { DeskSection } from "./desk/DeskSection";

const isDeskRoute = (): boolean => {
  if (typeof window === "undefined") return false;
  const p = window.location.pathname.toLowerCase();
  const h = window.location.hash.toLowerCase();
  const s = window.location.search.toLowerCase();
  return (
    p === "/desk" ||
    p.startsWith("/desk/") ||
    p.endsWith("/desk") ||
    h === "#desk" ||
    h.startsWith("#/desk") ||
    s.includes("view=desk")
  );
};

const AppRouter: React.FC = () => {
  const [isDesk, setIsDesk] = useState<boolean>(() => isDeskRoute());

  useEffect(() => {
    const onLocationChange = () => {
      setIsDesk(isDeskRoute());
    };
    window.addEventListener("popstate", onLocationChange);
    window.addEventListener("hashchange", onLocationChange);
    return () => {
      window.removeEventListener("popstate", onLocationChange);
      window.removeEventListener("hashchange", onLocationChange);
    };
  }, []);

  if (isDesk) {
    return <DeskSection />;
  }

  return <SectionStack />;
};

const rootElement = document.getElementById("root");
if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <AppRouter />
    </React.StrictMode>
  );
}
