// App — main composer with Tweaks panel.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero": "split",
  "palette": "liquidBrand",
  "typography": "modernBold",
  "density": "compact",
  "animations": true
}/*EDITMODE-END*/;

// Scroll-triggered fade-ins for any element with .ls-fade
function useScrollReveal() {
  React.useEffect(() => {
    if (typeof IntersectionObserver === "undefined") return;
    const els = document.querySelectorAll(".ls-fade");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("is-visible");
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: "0px 0px 0px 0px", threshold: 0 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// Sidebar section navigation — frosted glass panel, visible on any background
function SectionNav({ t }) {
  const { pal, typo } = t;
  const [active, setActive] = React.useState(0);
  const SECTIONS_NAV = [
    { id: "inicio",         label: "Inicio" },
    { id: "equipamiento",   label: "Soluciones" },
    { id: "industrias",     label: "Sectores" },
    { id: "contacto",       label: "Contacto" },
  ];
  React.useEffect(() => {
    const els = SECTIONS_NAV.map(s => document.getElementById(s.id)).filter(Boolean);
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const idx = els.indexOf(e.target);
          if (idx !== -1) setActive(idx);
        }
      });
    }, { threshold: 0.4 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);
  const scrollTo = (id) => document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  return (
    <nav aria-label="Secciones" className="ls-section-nav" style={{
      position: "fixed", right: 16, top: "50%", transform: "translateY(-50%)",
      zIndex: 45, display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-end",
    }}>
      {SECTIONS_NAV.map((s, i) => (
        <button key={s.id} onClick={() => scrollTo(s.id)} title={s.label}
          style={{ display: "flex", alignItems: "center", gap: 8, background: "none", border: "none", cursor: "pointer", padding: "3px 0" }}
        >
          <span style={{
            fontFamily: typo.mono, fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase",
            color: "#fff",
            textShadow: "0 1px 6px rgba(0,0,0,0.9), 0 0 16px rgba(0,0,0,0.6)",
            opacity: active === i ? 1 : 0,
            transition: "opacity .3s ease", whiteSpace: "nowrap",
          }}>{s.label}</span>
          <span style={{
            width: active === i ? 9 : 6,
            height: active === i ? 9 : 6,
            borderRadius: "50%", flexShrink: 0,
            background: active === i ? pal.accent : "#fff",
            boxShadow: active === i
              ? `0 0 10px ${pal.accent}aa, 0 1px 4px rgba(0,0,0,0.5)`
              : "0 1px 5px rgba(0,0,0,0.55), 0 0 0 1px rgba(0,0,0,0.15)",
            transition: "all .35s cubic-bezier(.2,.6,.2,1)",
          }} />
        </button>
      ))}
    </nav>
  );
}

// Floating WhatsApp CTA — appears only after scrolling past the hero
// so it doesn't cover the hero marquee / stats on mobile.
function MobileCTA() {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => {
      const hero = document.getElementById("inicio");
      const threshold = hero ? hero.offsetHeight - 120 : 600;
      setVisible(window.scrollY > threshold);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);
  return (
    <a className="ls-mobile-cta"
       href="https://wa.me/5492612455281?text=Hola%2C%20quiero%20cotizar%20un%20env%C3%ADo."
       target="_blank" rel="noopener"
       aria-label="Cotizar por WhatsApp"
       aria-hidden={!visible}
       onClick={() => window.va?.('event', { name: 'click_cotizar', data: { source: 'mobile_cta' } })}
       style={{
         opacity: visible ? 1 : 0,
         transform: visible ? "translateY(0)" : "translateY(120%)",
         pointerEvents: visible ? "auto" : "none",
         transition: "opacity .35s ease, transform .35s cubic-bezier(.2,.6,.2,1)",
       }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1s-.8.9-1 1.1c-.2.2-.4.2-.7.1-.3-.1-1.3-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5l-.9-2.2c-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.1.2 2.1 3.3 5.2 4.6.7.3 1.3.5 1.7.6.7.2 1.4.2 1.9.1.6-.1 1.7-.7 2-1.4.2-.7.2-1.3.2-1.4 0-.1-.3-.2-.5-.4zM12 2C6.5 2 2 6.5 2 12c0 1.7.5 3.4 1.3 4.8L2 22l5.4-1.3c1.4.8 3 1.2 4.6 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/>
      </svg>
      Cotizar por WhatsApp
    </a>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = React.useState("es");
  useScrollReveal();

  const theme = React.useMemo(() => ({
    pal: PALETTES[t.palette] || PALETTES.liquidBrand,
    typo: TYPE_PAIRINGS[t.typography] || TYPE_PAIRINGS.editorial,
    dens: DENSITY[t.density] || DENSITY.aireado,
  }), [t.palette, t.typography, t.density]);

  const HeroComponent = (HERO_VARIANTS[t.hero] || HERO_VARIANTS.fullbleed).Component;

  return (
    <LangContext.Provider value={{ lang, setLang }}>
      <style>{`
        body { margin: 0; background: ${theme.pal.bg}; }
        @keyframes ls-kb { 0% { transform: scale(1.0); } 100% { transform: scale(1.08); } }
        ::selection { background: ${theme.pal.accent}; color: ${theme.pal.inverseInk}; }
      `}</style>

      <Nav t={theme} />
      <span id="top" style={{ position: "absolute", top: 0 }} aria-hidden="true"></span>
      <HeroComponent t={theme} anim={t.animations} />
      <Equipment t={theme} />
      <Industries t={theme} />
      <Contact t={theme} />
      <Footer t={theme} />
      <MobileCTA />
      <SectionNav t={theme} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero">
          <TweakSelect
            label="Variante"
            value={t.hero}
            options={Object.entries(HERO_VARIANTS).map(([k, v]) => ({ value: k, label: v.name }))}
            onChange={(v) => setTweak("hero", v)}
          />
        </TweakSection>

        <TweakSection label="Estilo">
          <TweakSelect
            label="Paleta"
            value={t.palette}
            options={Object.entries(PALETTES).map(([k, v]) => ({ value: k, label: v.name }))}
            onChange={(v) => setTweak("palette", v)}
          />
          <TweakSelect
            label="Tipografía"
            value={t.typography}
            options={Object.entries(TYPE_PAIRINGS).map(([k, v]) => ({ value: k, label: v.name }))}
            onChange={(v) => setTweak("typography", v)}
          />
          <TweakRadio
            label="Densidad"
            value={t.density}
            options={[
              { value: "compact", label: "Compacto" },
              { value: "aireado", label: "Aireado" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
          <TweakToggle
            label="Animaciones"
            value={t.animations}
            onChange={(v) => setTweak("animations", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </LangContext.Provider>
  );
}

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