/* App — composición, tema, acento, animaciones de scroll, panel de Tweaks */
(function () {
  const { useEffect, useRef, useState } = React;

  /* Hero definitivo: variación C (Inmersivo) */
  const HERO_VARIANT = "C";

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "theme": "light",
    "accent": ["#d17e1a", "#e99d23"]
  }/*EDITMODE-END*/;

  function useReveal() {
    useEffect(() => {
      const els = Array.from(document.querySelectorAll(".reveal:not(.in)"));
      const revealAll = () => els.forEach((e) => e.classList.add("in"));
      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { revealAll(); return; }
      let io;
      if ("IntersectionObserver" in window) {
        io = new IntersectionObserver((ents) => {
          ents.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); } });
        }, { threshold: 0.12, rootMargin: "0px 0px -6% 0px" });
        els.forEach((e) => io.observe(e));
      } else { revealAll(); }
      // Safety net: never leave content hidden if scroll/observer doesn't fire.
      const t = setTimeout(revealAll, 2200);
      return () => { clearTimeout(t); if (io) io.disconnect(); };
    }, []);
  }

  function App() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const data = window.HEMEL;

    // tema
    useEffect(() => {
      document.documentElement.dataset.theme = t.theme === "dark" ? "dark" : "light";
    }, [t.theme]);

    // acento
    useEffect(() => {
      const acc = Array.isArray(t.accent) ? t.accent : [t.accent, t.accent];
      document.documentElement.style.setProperty("--accent", acc[0]);
      document.documentElement.style.setProperty("--accent-2", acc[1] || acc[0]);
    }, [t.accent]);

    useReveal();

    const toggleTheme = () => setTweak("theme", t.theme === "dark" ? "light" : "dark");

    return (
      <React.Fragment>
        <Navbar data={data} theme={t.theme} onToggleTheme={toggleTheme} heroVariant={HERO_VARIANT} />
        <main>
          <Hero data={data} variant={HERO_VARIANT} />
          <Nosotros data={data} />
          <Servicios data={data} />
          <Cobertura data={data} />
          <Blog data={data} />
          <Contacto data={data} />
        </main>
        <Footer data={data} />

        <TweaksPanel>
          <TweakSection label="Tema" />
          <TweakRadio
            label="Modo"
            value={t.theme}
            options={[{ value: "light", label: "Claro" }, { value: "dark", label: "Oscuro" }]}
            onChange={(v) => setTweak("theme", v)}
          />
          <TweakColor
            label="Acento"
            value={t.accent}
            options={[
              ["#d17e1a", "#e99d23"],
              ["#b45a12", "#d17e1a"],
              ["#c2410c", "#ea7a3c"],
              ["#a16207", "#d4a017"],
            ]}
            onChange={(v) => setTweak("accent", v)}
          />
        </TweaksPanel>
      </React.Fragment>
    );
  }

  window.HemelApp = App;
})();
