/* Aelune — main app */
const { useEffect: useEfApp } = React;

function AelunesApp() {
  // Scroll-reveal observer — robust to React re-renders
  useEfApp(() => {
    if (!("IntersectionObserver" in window)) {
      document.querySelectorAll(".reveal").forEach(el => el.classList.add("in"));
      return;
    }

    // Track elements that have already been revealed so React re-renders can't un-reveal them
    const revealed = new WeakSet();

    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          revealed.add(e.target);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: "0px 0px -4% 0px" });

    // Auto-stagger: assign --reveal-delay to children of [data-stagger] groups
    const stagger = (root) => {
      root.querySelectorAll("[data-stagger]").forEach(group => {
        const step = parseInt(group.dataset.stagger, 10) || 90;
        const base = parseInt(group.dataset.staggerBase, 10) || 0;
        const kids = group.querySelectorAll(":scope > .reveal, :scope > * > .reveal");
        kids.forEach((el, i) => {
          if (!el.style.getPropertyValue("--reveal-delay")) {
            el.style.setProperty("--reveal-delay", (base + i * step) + "ms");
          }
        });
      });
    };

    const scan = (root) => {
      stagger(root === document ? document.body : root);
      const scope = root === document ? document : root;
      scope.querySelectorAll(".reveal").forEach(el => {
        if (revealed.has(el)) {
          // React re-rendered and stripped .in — restore it
          if (!el.classList.contains("in")) el.classList.add("in");
        } else if (!el.classList.contains("in")) {
          io.observe(el);
        }
      });
    };

    scan(document);

    // Watch the DOM for React renders that add new .reveal elements or strip .in
    const mo = new MutationObserver((mutations) => {
      let dirty = false;
      for (const m of mutations) {
        if (m.type === "childList" && (m.addedNodes.length || m.removedNodes.length)) { dirty = true; break; }
        if (m.type === "attributes" && m.target instanceof Element) {
          if (revealed.has(m.target) && m.target.classList.contains("reveal") && !m.target.classList.contains("in")) {
            m.target.classList.add("in");
          }
        }
      }
      if (dirty) scan(document);
    });
    mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class"] });

    return () => { io.disconnect(); mo.disconnect(); };
  }, []);

  return (
    <>
      <Header />
      <main>
        <Hero />
        <About />
        <How />
        <Agents />
        <Features />
        <Roadmap />
        <CTAStrip />
        <FAQ />
      </main>
      <SiteFooter />
    </>
  );
}

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