// Main app
const { useState: useS, useEffect: useE } = React;

function App() {
  const [open, setOpen] = useS(false);
  const [tweaks, setTweaks] = useS(window.__TWEAKS__);
  const [tweaksVisible, setTweaksVisible] = useS(false);

  useE(() => {
    const onMsg = (e) => {
      if (!e.data || !e.data.type) return;
      if (e.data.type === "__activate_edit_mode") setTweaksVisible(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksVisible(false);
    };
    window.addEventListener("message", onMsg);
    if (window.parent !== window) { // __edit_mode_available__guard

      window.parent.postMessage({ type: "__edit_mode_available" }, "*");

    }
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // Scroll to a #section on load (e.g. arriving at index.html#reviews from the
  // nav on another page). The page renders via in-browser Babel and has heavy
  // scroll-driven sections, so the target both appears late AND keeps moving as
  // layout settles. Wait until its position is stable across two samples, then
  // scroll once.
  useE(() => {
    const id = (window.location.hash || "").slice(1);
    if (!id) return;
    let tries = 0, lastTop = null, timer;
    const step = () => {
      const el = document.getElementById(id);
      if (el) {
        const top = Math.round(el.getBoundingClientRect().top + window.scrollY);
        if (top === lastTop) {
          window.scrollTo({ top: Math.max(0, top - 90), behavior: "smooth" });
          return;
        }
        lastTop = top;
      }
      if (tries++ < 60) timer = setTimeout(step, 100);
    };
    timer = setTimeout(step, 120);
    return () => clearTimeout(timer);
  }, []);

  const openWizard = () => setOpen(true);

  return (
    <>
      <Nav onInquire={openWizard} />
      <Hero onInquire={openWizard} ctaPrimary={tweaks.ctaPrimary} ctaPromise={tweaks.ctaPromise} />
      <TrustBar />
      <Gallery />
      <Services onInquire={openWizard} />
      <Proof />
      <TrustedBy />
      <FinalCTA onInquire={openWizard} ctaPrimary={tweaks.ctaPrimary} ctaPromise={tweaks.ctaPromise} />
      <Footer />
      <InquiryWizard open={open} onClose={() => setOpen(false)} ctaPromise={tweaks.ctaPromise} />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={tweaksVisible} />
      <VideoModal />
    </>
  );
}

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