// app.jsx — Root app: routing (URL + state), tweaks, layout, SEO hooks.

const {
  useState: useStateA,
  useEffect: useEffectA,
  useLayoutEffect: useLayoutEffectA,
  useCallback: useCallbackA,
} = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  portfolioLayout: "uniform",
}/*EDITMODE-END*/;

const ROUTE_TO_PATH = {
  home: "/",
  services: "/services",
  portfolio: "/portfolio",
  about: "/about",
  contact: "/contact",
  blog: "/blog",
};

const PATH_TO_ROUTE = {
  "/": "home",
  "/services": "services",
  "/portfolio": "portfolio",
  "/about": "about",
  "/contact": "contact",
  "/blog": "blog",
};

function pathFromLocation() {
  let p = window.location.pathname || "/";
  if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
  return p || "/";
}

function routeFromPath(p) {
  return PATH_TO_ROUTE[p] || "home";
}

function App() {
  const [route, setRouteState] = useStateA(() =>
    typeof window !== "undefined" ? routeFromPath(pathFromLocation()) : "home"
  );
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [pageKey, setPageKey] = useStateA(0);
  const [lightbox, setLightbox] = useStateA(null);

  useEffectA(() => {
    setPageKey((k) => k + 1);
  }, [route]);

  const closeLightbox = useCallbackA(() => setLightbox(null), []);
  const moveLightbox = useCallbackA((direction) => {
    setLightbox((prev) => {
      if (!prev || prev.mediaType !== "image" || !Array.isArray(prev.gallery) || prev.gallery.length < 2) return prev;
      const currentIndex =
        typeof prev.index === "number" && prev.index >= 0
          ? prev.index
          : prev.gallery.findIndex((g) => g.src === prev.src);
      const len = prev.gallery.length;
      const nextIndex = ((currentIndex >= 0 ? currentIndex : 0) + direction + len) % len;
      const next = prev.gallery[nextIndex];
      if (!next || !next.src) return prev;
      return { ...prev, src: next.src, alt: next.alt || "", index: nextIndex };
    });
  }, []);

  useLayoutEffectA(() => {
    window.semOpenLightbox = (src, alt, options = {}) => {
      if (!src) return;
      const rawGallery = Array.isArray(options.gallery) ? options.gallery : [];
      const normalizedGallery = rawGallery
        .map((entry) => {
          if (!entry) return null;
          if (typeof entry === "string") return { src: entry, alt: "" };
          if (entry.src) return { src: entry.src, alt: entry.alt || "" };
          return null;
        })
        .filter(Boolean);
      let gallery = normalizedGallery;
      if (!gallery.some((g) => g.src === src)) gallery = [{ src, alt: alt || "" }, ...gallery];
      const index = Math.max(
        0,
        gallery.findIndex((g) => g.src === src)
      );
      setLightbox({
        mediaType: "image",
        src,
        alt: alt || "",
        gallery: gallery.length > 1 ? gallery : null,
        index,
      });
    };
    window.semOpenMedia = (media) => {
      if (!media || !media.src) return;
      setLightbox({
        mediaType: media.mediaType || "image",
        src: media.src,
        alt: media.alt || "",
        poster: media.poster || "",
        gallery: null,
        index: 0,
      });
    };
    return () => {
      delete window.semOpenLightbox;
      delete window.semOpenMedia;
    };
  }, []);

  const setRoute = useCallbackA((next) => {
    const path = ROUTE_TO_PATH[next] || "/";
    if (typeof window !== "undefined") {
      window.history.pushState({ route: next }, "", path);
      window.scrollTo({ top: 0 });
    }
    setRouteState(next);
  }, []);

  useEffectA(() => {
    const onPop = () => {
      setRouteState(routeFromPath(pathFromLocation()));
      window.scrollTo({ top: 0 });
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  useEffectA(() => {
    if (typeof window.injectLocalBusinessJsonLd === "function") {
      window.injectLocalBusinessJsonLd();
    }
    if (typeof window.initSemAnalytics === "function") {
      window.initSemAnalytics();
    }
  }, []);

  useEffectA(() => {
    if (typeof window.applyRouteMeta === "function") window.applyRouteMeta(route);
    if (typeof window.semTrackPageView === "function") window.semTrackPageView(route);
  }, [route]);

  let page;
  if (route === "home") page = <HomePage setRoute={setRoute} />;
  else if (route === "services") page = <ServicesPage setRoute={setRoute} />;
  else if (route === "portfolio") page = <PortfolioPage setRoute={setRoute} />;
  else if (route === "about") page = <AboutPage setRoute={setRoute} />;
  else if (route === "contact") page = <ContactPage />;
  else if (route === "blog") page = <BlogPage setRoute={setRoute} />;
  else page = <HomePage setRoute={setRoute} />;

  const LightboxCmp = typeof window !== "undefined" && typeof window.MediaLightbox === "function"
    ? window.MediaLightbox
    : typeof window !== "undefined" && typeof window.ImageLightbox === "function"
    ? window.ImageLightbox
    : null;
  const lightboxNode =
    lightbox && LightboxCmp && typeof document !== "undefined"
      ? (
          <LightboxCmp
            mediaType={lightbox.mediaType || "image"}
            src={lightbox.src}
            alt={lightbox.alt}
            poster={lightbox.poster}
            canNavigate={Boolean(lightbox.mediaType === "image" && lightbox.gallery && lightbox.gallery.length > 1)}
            onPrev={() => moveLightbox(-1)}
            onNext={() => moveLightbox(1)}
            onClose={closeLightbox}
          />
        )
      : null;

  return (
    <React.Fragment>
      <Nav route={route} setRoute={setRoute} />
      <div key={pageKey} className="sem-page-fade">
        {page}
      </div>
      <Footer setRoute={setRoute} />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Portfolio" />
        <TweakRadio
          label="Layout"
          value={t.portfolioLayout}
          options={["uniform"]}
          onChange={(v) => setTweak("portfolioLayout", v)}
        />
      </TweaksPanel>
      {lightboxNode ? ReactDOM.createPortal(lightboxNode, document.body) : null}
    </React.Fragment>
  );
}

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