// Main app — wires sections, Tweaks panel, theme switching, and scroll reveal.

const { useState, useEffect, useRef } = React;

// Reveal-on-scroll: any element with .reveal fades up once visible.
function useRevealOnScroll() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.is-in)");
    if (!els.length) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

// Subtle parallax on hero photo + section labels (scroll-driven).
function useScrollParallax() {
  useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        document.querySelectorAll("[data-parallax]").forEach((el) => {
          const speed = parseFloat(el.dataset.parallax || "0.05");
          el.style.transform = `translate3d(0, ${(-y * speed).toFixed(1)}px, 0)`;
        });
        raf = 0;
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
}

// Top progress bar — slim line tracking page scroll.
function ScrollProgress() {
  const ref = useRef(null);
  useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement.scrollHeight - window.innerHeight;
      const p = h > 0 ? window.scrollY / h : 0;
      if (ref.current) ref.current.style.transform = `scaleX(${p})`;
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div className="scroll-progress" ref={ref} />;
}

// Top nav — minimal, sticky.
function TopNav() {
  return (
    <header className="topnav">
      <div className="topnav-left">
        <img src="assets/logo.png" alt="" className="topnav-logo" />
        <span className="topnav-name">Carlos Bezerra</span>
        <span className="topnav-rule" />
        <span className="topnav-meta">Diagnóstico Patrimonial</span>
      </div>
      <nav className="topnav-right">
        <a href="https://wa.me/5511995370742?text=Ol%C3%A1%20Carlos%2C%20vim%20pela%20landing%20page%20e%20quero%20saber%20mais%20sobre%20o%20Diagn%C3%B3stico%20Patrimonial." target="_blank" rel="noopener noreferrer" className="topnav-link">Agendar</a>
      </nav>
    </header>
  );
}

// ─── Tweaks panel ────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "clinico",
  "reveal_animations": true,
  "show_scroll_progress": true
}/*EDITMODE-END*/;

function ThemeSwatch({ themeKey, active, onClick }) {
  const t = THEMES[themeKey];
  const s = t.vars;
  return (
    <button
      className={`theme-swatch ${active ? "is-active" : ""}`}
      onClick={onClick}
      aria-pressed={active}
    >
      <div className="theme-swatch-card" style={{ background: s["--bg"], color: s["--fg"] }}>
        <div className="theme-swatch-row">
          <span style={{ background: s["--fg"], width: 22, height: 6, display: "inline-block" }} />
          <span style={{ background: s["--accent"], width: 8, height: 8, borderRadius: "50%", display: "inline-block" }} />
        </div>
        <div className="theme-swatch-row" style={{ marginTop: 6 }}>
          <span style={{ background: s["--fg-muted"], width: 36, height: 3, display: "inline-block" }} />
        </div>
        <div className="theme-swatch-row" style={{ marginTop: 4 }}>
          <span style={{ background: s["--fg-muted"], width: 28, height: 3, display: "inline-block" }} />
        </div>
        <div className="theme-swatch-name" style={{ fontFamily: s["--font-display"], color: s["--fg"], fontStyle: themeKey === "clinico" ? "normal" : "italic" }}>
          {t.name}
        </div>
      </div>
      <div className="theme-swatch-blurb">{t.blurb}</div>
    </button>
  );
}

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

  useEffect(() => {
    applyTheme(tweaks.theme);
  }, [tweaks.theme]);

  useEffect(() => {
    document.documentElement.dataset.reveal = tweaks.reveal_animations ? "on" : "off";
  }, [tweaks.reveal_animations]);

  useRevealOnScroll();
  useScrollParallax();

  return (
    <>
      {tweaks.show_scroll_progress && <ScrollProgress />}
      <TopNav />
      <main>
        <Hero />
        <Product />
        <Insight />
        <About />
        <Testimonials />
        <ForWho />
        <FinalCTA />
        <FAQ />
      </main>
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection title="Direção estética">
          <div className="tw-themes">
            {Object.keys(THEMES).map((k) => (
              <ThemeSwatch
                key={k}
                themeKey={k}
                active={tweaks.theme === k}
                onClick={() => setTweak("theme", k)}
              />
            ))}
          </div>
        </TweakSection>
        <TweakSection title="Movimento">
          <TweakToggle
            label="Animações de scroll (fade-up)"
            value={tweaks.reveal_animations}
            onChange={(v) => setTweak("reveal_animations", v)}
          />
          <TweakToggle
            label="Indicador de progresso no topo"
            value={tweaks.show_scroll_progress}
            onChange={(v) => setTweak("show_scroll_progress", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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