/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSelect, TweakToggle,
   Nav, Hero, StatsStrip, Outcomes, Services, WhyThisWorks, About, Faq, Booking, FinalCta, Footer, Lenis */

const { useEffect, useRef } = React;

function useLenis() {
  useEffect(() => {
    if (typeof Lenis === "undefined") return;
    const lenis = new Lenis({
      lerp: 0.115,                         // higher = snappier (was 0.092)
      duration: 0.9,                       // for scrollTo() (was 1.1)
      easing: (t) => 1 - Math.pow(1 - t, 4),  // smooth quart-out
      smoothWheel: true,
      smoothTouch: false,
      touchMultiplier: 1.2,
      wheelMultiplier: 0.95,
      syncTouch: false,
    });
    window.__lenis = lenis;

    let rafId;
    function raf(time) {
      lenis.raf(time);
      rafId = requestAnimationFrame(raf);
    }
    rafId = requestAnimationFrame(raf);

    // Route in-page anchor clicks through Lenis (excluding cal.com etc.)
    const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
    const anchorHandler = (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute("href");
      if (href.length < 2) return;
      const el = document.querySelector(href);
      if (!el) return;
      e.preventDefault();
      lenis.scrollTo(el, { offset: -70, duration: 1.5, easing: easeInOutCubic });
    };
    document.addEventListener("click", anchorHandler);

    return () => {
      cancelAnimationFrame(rafId);
      document.removeEventListener("click", anchorHandler);
      lenis.destroy();
      delete window.__lenis;
    };
  }, []);
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "cream",
  "density": "comfortable",
  "accent": "none",
  "hero": "standard"
}/*EDITMODE-END*/;

const THEMES = {
  cream:   { "--bg": "#F6F4EF", "--bg-2": "#EEEAE1", "--ink": "#0F0F0F" },
  off:     { "--bg": "#FAFAF7", "--bg-2": "#F1F0EB", "--ink": "#0E0E10" },
  dark:    {}, /* handled by data-theme attribute */
};

const ACCENTS = {
  none:   null,
  sage:   "#3A6B4F",
  amber:  "#C99A2E",
  coral:  "#D9614A",
  blue:   "#2A5BD9",
};

function ScrollReveal() {
  useEffect(() => {
    const els = [...document.querySelectorAll(".reveal")];
    // Reveal once an element's top rises into the lower-middle of the viewport.
    const reveal = () => {
      const trigger = window.innerHeight * 0.82;
      els.forEach((el) => {
        if (el.getAttribute("data-visible") === "true") return;
        if (el.getBoundingClientRect().top < trigger) {
          el.setAttribute("data-visible", "true");
        }
      });
    };
    reveal();
    window.addEventListener("scroll", reveal, { passive: true });
    window.addEventListener("resize", reveal);

    // Hook Lenis if/when it's ready (its effect may run after this one).
    let lenis = null;
    const attach = () => {
      if (!lenis && window.__lenis) {
        lenis = window.__lenis;
        lenis.on("scroll", reveal);
      }
    };
    attach();
    const poll = setInterval(attach, 120);
    setTimeout(() => clearInterval(poll), 2000);

    return () => {
      window.removeEventListener("scroll", reveal);
      window.removeEventListener("resize", reveal);
      if (lenis) lenis.off("scroll", reveal);
      clearInterval(poll);
    };
  }, []);
  return null;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useLenis();

  // Apply theme attribute + accent CSS variable to <html>
  useEffect(() => {
    const html = document.documentElement;
    html.setAttribute("data-theme", t.theme);
    html.setAttribute("data-density", t.density);
    html.setAttribute("data-hero", t.hero);
    const accentHex = ACCENTS[t.accent];
    if (accentHex) {
      html.style.setProperty("--accent", accentHex);
      document.body.classList.add("accent-halo");
    } else {
      html.style.removeProperty("--accent");
      document.body.classList.remove("accent-halo");
    }
  }, [t.theme, t.density, t.accent, t.hero]);

  const onBook = () => {
    const el = document.getElementById("book");
    if (!el) return;
    if (window.__lenis) {
      window.__lenis.scrollTo(el, { offset: -70 });
    } else {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };
  const onWork = () => {
    const el = document.getElementById("outcomes");
    if (!el) return;
    if (window.__lenis) {
      const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
      window.__lenis.scrollTo(el, { offset: -70, duration: 1.5, easing: easeInOutCubic });
    } else {
      const top = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <React.Fragment>
      <Nav onBook={onBook} />

      <main>
        <div className="reveal" data-visible="true">
          <Hero variant={t.hero} onBook={onBook} onWork={onWork} />
        </div>
        <div className="reveal"><Outcomes /></div>
        <div className="reveal"><About onBook={onBook} /></div>
        <div className="reveal"><Services /></div>
        <div className="reveal"><WhyThisWorks /></div>
        <div className="reveal"><Faq /></div>
        <div className="reveal"><Booking /></div>
        <div className="reveal"><FinalCta onBook={onBook} /></div>
      </main>
      <Footer />

      <ScrollReveal />

      <TweaksPanel>
        <TweakSection label="Theme" />
        <TweakRadio
          label="Background"
          value={t.theme}
          options={["cream", "off", "dark"]}
          onChange={(v) => setTweak("theme", v)}
        />
        <TweakRadio
          label="Density"
          value={t.density}
          options={["comfortable", "compact"]}
          onChange={(v) => setTweak("density", v)}
        />

        <TweakSection label="Accent" />
        <TweakSelect
          label="Color"
          value={t.accent}
          options={[
            { value: "none",  label: "None (mono)" },
            { value: "sage",  label: "Sage" },
            { value: "amber", label: "Amber" },
            { value: "coral", label: "Coral" },
            { value: "blue",  label: "Blue" },
          ]}
          onChange={(v) => setTweak("accent", v)}
        />

        <TweakSection label="Hero variant" />
        <TweakSelect
          label="Treatment"
          value={t.hero}
          options={[
            { value: "standard", label: "Standard" },
            { value: "display",  label: "Display oversized" },
            { value: "marquee",  label: "Marquee strip" },
          ]}
          onChange={(v) => setTweak("hero", v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

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