/* global React */
const { useState, useEffect, useRef, useMemo } = React;

/* ============================================================
   Hooks & primitives
   ============================================================ */

// IntersectionObserver hook → returns [ref, isInView]
function useInView(opts = {}) {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setInView(true);
          io.unobserve(el);
        }
      },
      { threshold: opts.threshold ?? 0.18, rootMargin: opts.rootMargin ?? "0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return [ref, inView];
}

// BlurText — word-by-word reveal with 3-step blur keyframes
function BlurText({ text, className = "", delay = 0, stagger = 90, as = "span", emphRange = null }) {
  const [ref, inView] = useInView({ threshold: 0.1 });
  const words = useMemo(() => text.split(" "), [text]);
  const Tag = as;
  return (
    <Tag ref={ref} className={"blur-text " + className}>
      {words.map((w, i) => {
        const isEmph = emphRange && i >= emphRange[0] && i <= emphRange[1];
        return (
          <span
            key={i}
            className={"blur-word" + (inView ? " show" : "")}
            style={{
              transitionDelay: `${delay + i * stagger}ms`,
              fontStyle: isEmph ? "italic" : undefined,
              color: isEmph ? "var(--anb-devesa-gold-soft)" : undefined, fontWeight: "300"
            }}>
            
            {w}
          </span>);

      })}
    </Tag>);

}

// FadeIn — generic entrance wrapper
function FadeIn({ children, delay = 0, className = "", as: Tag = "div", style }) {
  const [ref, inView] = useInView({ threshold: 0.15 });
  return (
    <Tag
      ref={ref}
      className={"fade-in " + (inView ? "show " : "") + className}
      style={{ ...style, transitionDelay: `${delay}ms` }}>
      
      {children}
    </Tag>);

}

// CountUp — counter animation, power2.out feel
function CountUp({ to, suffix = "", prefix = "", duration = 1800, decimals = 0 }) {
  const [ref, inView] = useInView({ threshold: 0.3 });
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!inView) return;
    let start = null;
    const ease = (t) => 1 - Math.pow(1 - t, 2.4); // power2.out
    let raf;
    const step = (ts) => {
      if (!start) start = ts;
      const t = Math.min(1, (ts - start) / duration);
      setVal(to * ease(t));
      if (t < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [inView, to, duration]);
  const display = decimals === 0 ? Math.round(val) : val.toFixed(decimals);
  return (
    <span ref={ref}>
      {prefix}{display.toLocaleString("es-AR")}{suffix}
    </span>);

}

/* ============================================================
   Scene chrome — bg + scrim + grain
   ============================================================ */

function SceneBg({ src, video = null, poster = null, kenburns = true, scrim = "bottom", vignette = false, gradient = null }) {
  const useVideo = !!video;
  return (
    <div className={"scene-bg" + (kenburns && !useVideo ? " kenburns" : "")}>
      {gradient ?
      <div className="gradient-bg" style={{ background: gradient }} /> :
      useVideo ?
      <video
        className="scene-bg-video"
        src={video}
        poster={poster || src}
        autoPlay
        muted
        loop
        playsInline
        preload="auto"
      /> :
      <img src={src} alt="" />
      }
      {scrim === "bottom" && <div className="scrim-bottom" />}
      {scrim === "left" && <div className="scrim-left" />}
      {scrim === "diag" && <div className="scrim-diag" />}
      {vignette && <div className="vignette" />}
      <div className="grain" />
    </div>);

}

/* ============================================================
   Header — floating pill + dropdowns + lang switcher
   ============================================================ */

const NAV = [
{
  label: "Marcas",
  items: [
  { label: "Devesa", desc: "Marca insignia · WSC 2025", href: "#devesa" },
  { label: "ANB · Argentine Beef", desc: "Para volumen", href: "#anb" },
  { label: "Cyan", desc: "Próximamente · 2026", href: "#cyan" }]

},
{
  label: "Unidades",
  items: [
  { label: "Planta de Rendering", desc: "Harina de hueso + cebo líquido", href: "#rendering" },
  { label: "Cueros salados", desc: "Wet salted hides export", href: "#cueros" }]

},
{
  label: "El holding",
  items: [
  { label: "Historia", desc: "Dos familias · cien años", href: "#historia" },
  { label: "Cadena de valor", desc: "70-80% materia prima propia", href: "#cadena" },
  { label: "Calidad", desc: "BRC · SMETA · Halal · NATO", href: "#calidad" },
  { label: "Sostenibilidad", desc: "", href: "#sost" },
  { label: "Mercados", desc: "14+ países activos", href: "#mercados" },
  { label: "Equipo", desc: "", href: "#equipo" },
  { label: "Denuncias", desc: "Canal de compliance", href: "#denuncias" }]

}];


function Header() {
  const [open, setOpen] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const [lang, setLang] = useState("ES");
  const [langOpen, setLangOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const onClick = (e) => {
      if (!e.target.closest(".anb-nav-item") && !e.target.closest(".anb-lang-toggle") && !e.target.closest(".anb-lang-panel")) {
        setOpen(null);
        setLangOpen(false);
      }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  return (
    <header className={"anb-header" + (scrolled ? " scrolled" : "")} style={{ fontWeight: "200" }}>
      <a href="#hero" className="anb-header-logo" aria-label="Azul Natural Beef">
        <img src="assets/logos/azulnaturalbeef-text-white.png" alt="Azul Natural Beef" />
      </a>
      <nav className="anb-nav">
        {NAV.map((g) =>
        <div
          key={g.label}
          className="anb-nav-item"
          aria-expanded={open === g.label}
          onClick={(e) => {e.stopPropagation();setOpen(open === g.label ? null : g.label);}}
          onMouseEnter={() => setOpen(g.label)}>
          
            {g.label}
            <span className="chev"></span>
            <div className="anb-dropdown" onMouseLeave={() => setOpen(null)}>
              {g.items.map((it) =>
            <a key={it.label} href={it.href} className="anb-dd-link">
                  <span className="label">{it.label}</span>
                  {it.desc && <span className="desc">{it.desc}</span>}
                </a>
            )}
            </div>
          </div>
        )}
        <a className="anb-nav-item" href="#carreras">Carreras</a>
        <a className="anb-nav-item" href="#hacienda">Hacienda</a>
      </nav>
      <a href="#devesa" className="anb-cta-pill">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M12 11V7a4 4 0 0 1 8 0v4" /><rect x="6" y="11" width="20" height="12" transform="translate(-4)" rx="0" /></svg>
        <span>Catálogo Devesa</span>
      </a>
      <div style={{ position: "relative" }}>
        <button
          className="anb-lang-toggle"
          onClick={(e) => {e.stopPropagation();setLangOpen(!langOpen);}}>
          
          {lang}
        </button>
        <div className={"anb-lang-panel" + (langOpen ? " open" : "")}>
          <h5>Idioma · Language</h5>
          <div className="tier">
            <h5 style={{ color: "rgba(200,162,75,0.6)", fontSize: 9, marginBottom: 6 }}>Tier 1 · Activo</h5>
            {[["ES", "Español"], ["EN", "English"], ["ZH", "中文"]].map(([k, n]) =>
            <button key={k} className={lang === k ? "active" : ""} onClick={() => {setLang(k);setLangOpen(false);}}>{n}</button>
            )}
          </div>
          <div className="tier">
            <h5 style={{ color: "rgba(200,162,75,0.6)", fontSize: 9, marginBottom: 6 }}>Tier 2 · Próximamente</h5>
            {["Ελληνικά", "Português", "العربية"].map((n) =>
            <button key={n} className="disabled">{n}</button>
            )}
          </div>
          <div className="tier">
            <h5 style={{ color: "rgba(200,162,75,0.6)", fontSize: 9, marginBottom: 6 }}>Tier 3 · On-demand</h5>
            {["עברית", "Deutsch", "Italiano", "Français", "Tiếng Việt", "한국어", "日本語"].map((n) =>
            <button key={n} className="disabled">{n}</button>
            )}
          </div>
        </div>
      </div>
    </header>);

}

/* ============================================================
   Footer
   ============================================================ */

function Footer() {
  return (
    <footer className="anb-footer">
      <div className="grid">
        <div>
          <a href="#hero" className="anb-wordmark anb-wordmark-footer" aria-label="Azul Natural Beef">
            <img src="assets/logos/azulnaturalbeef-wordmark-white.png" alt="Azul Natural Beef" className="anb-wordmark-img anb-wordmark-img-lg" />
          </a>
          <p className="razon">
            Razón social: Azul Natural Beef S.A.<br />
            Dos familias con más de 100 años de tradición ganadera entre Europa y Argentina.
          </p>
          <p className="razon" style={{ marginTop: 18, fontStyle: "normal", fontFamily: "var(--font-body)", fontSize: 13 }}>
            Maipú 374, Piso 3 · CABA (1006)<br />
            Las Flores Norte 1718 · Azul (7300), BA<br />
            Establecimiento N° 5039
          </p>
        </div>
        <div>
          <h6>Marcas</h6>
          <ul>
            <li><a href="#devesa">Devesa</a></li>
            <li><a href="#anb">ANB · Argentine Beef</a></li>
            <li><a href="#cyan">Cyan</a></li>
            <li><a href="#submarcas">Sub-marcas próximas</a></li>
          </ul>
        </div>
        <div>
          <h6>Negocio</h6>
          <ul>
            <li><a href="#cadena">Cadena de valor</a></li>
            <li><a href="#calidad">Calidad</a></li>
            <li><a href="#sost">Sostenibilidad</a></li>
            <li><a href="#mercados">Mercados</a></li>
            <li><a href="#rendering">Planta de Rendering</a></li>
            <li><a href="#cueros">Cueros salados</a></li>
            <li><a href="#impacto">Impacto social</a></li>
          </ul>
        </div>
        <div>
          <h6>Conexión</h6>
          <ul>
            <li><a href="#carreras">Carreras</a></li>
            <li><a href="#hacienda">Hacienda</a></li>
            <li><a href="#contacto">Contacto</a></li>
            <li><a href="#prensa">Prensa + media kit</a></li>
            <li><a href="#proveedores">Proveedores</a></li>
            <li><a href="#denuncias">Denuncias (compliance)</a></li>
          </ul>
        </div>
      </div>
      <div className="strip">
        <small>© 2026 Azul Natural Beef S.A. · Todos los derechos reservados.</small>
        <div className="links">
          <a href="#legal">Términos</a>
          <a href="#legal">Privacidad</a>
          <a href="#legal">Aviso legal</a>
        </div>
      </div>
    </footer>);

}

/* ============================================================
   Section dots + scroll progress
   ============================================================ */

function ScrollProgress() {
  const [pct, setPct] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const total = document.documentElement.scrollHeight - window.innerHeight;
      setPct(Math.max(0, Math.min(100, window.scrollY / total * 100)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return <div className="scroll-progress" style={{ width: pct + "%" }} />;
}

const SECTIONS = [
["hero", "Hero"],
["origen", "Origen"],
["cadena", "Cadena"],
["proceso", "Proceso"],
["calidad", "Calidad"],
["devesa", "Devesa"],
["mundo", "Mundo"],
["familia", "Familia"],
["cierre", "Cierre"]];


function SectionDots() {
  const [active, setActive] = useState("hero");
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + window.innerHeight * 0.4;
      let cur = "hero";
      for (const [id] of SECTIONS) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) cur = id;
      }
      setActive(cur);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className="section-dots">
      {SECTIONS.map(([id, label]) =>
      <button
        key={id}
        data-label={label}
        className={active === id ? "active" : ""}
        onClick={() => document.getElementById(id)?.scrollIntoView({ behavior: "smooth" })} />

      )}
    </div>);

}

/* ============================================================
   Particles for Devesa scene
   ============================================================ */

function Particles({ count = 24 }) {
  const items = useMemo(() =>
  Array.from({ length: count }).map(() => ({
    left: Math.random() * 100,
    top: 70 + Math.random() * 30,
    delay: Math.random() * -18,
    dur: 14 + Math.random() * 10,
    size: 1 + Math.random() * 2.5
  })), [count]);
  return (
    <div className="particles">
      {items.map((p, i) =>
      <span
        key={i}
        className="particle"
        style={{
          left: p.left + "%",
          top: p.top + "%",
          width: p.size + "px",
          height: p.size + "px",
          animationDelay: p.delay + "s",
          animationDuration: p.dur + "s"
        }} />

      )}
    </div>);

}

Object.assign(window, {
  useInView, BlurText, FadeIn, CountUp, SceneBg, Header, Footer, ScrollProgress, SectionDots, Particles
});