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

// Count-up hook: tween from 0 -> target when ref enters viewport (or immediately)
function useCountUp(target, { duration = 1400, delay = 0, immediate = true } = {}) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const start = () => {
      if (started.current) return;
      started.current = true;
      const t0 = performance.now() + delay;
      const tick = (now) => {
        if (now < t0) { requestAnimationFrame(tick); return; }
        const p = Math.min(1, (now - t0) / duration);
        // ease-out cubic
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(target * eased);
        if (p < 1) requestAnimationFrame(tick);
        else setVal(target);
      };
      requestAnimationFrame(tick);
    };
    if (immediate) { start(); return; }
    const el = ref.current;
    if (!el || !("IntersectionObserver" in window)) { start(); return; }
    const io = new IntersectionObserver((entries) => {
      if (entries.some(e => e.isIntersecting)) { start(); io.disconnect(); }
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [target, duration, delay, immediate]);
  return [val, ref];
}

function CountStat({ value, suffix = "", prefix = "", delay = 0, decimals = 0 }) {
  const [v, ref] = useCountUp(value, { delay, immediate: true });
  const rounded = decimals === 0 ? Math.round(v) : v.toFixed(decimals);
  return <span ref={ref}>{prefix}{rounded}{suffix}</span>;
}

// ============================================================
// ICONS (inline SVG)
// ============================================================
const Icon = {
  Shield: (p) => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z" />
      <path d="M9 12l2 2 4-4" />
    </svg>
  ),
  Trend: (p) => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 17l6-6 4 4 8-8" />
      <path d="M14 7h7v7" />
    </svg>
  ),
  Truck: (p) => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 16V6h11v10" />
      <path d="M14 9h4l3 4v3h-7" />
      <circle cx="7" cy="18" r="2" />
      <circle cx="17" cy="18" r="2" />
    </svg>
  ),
  Headset: (p) => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M4 14v-3a8 8 0 0116 0v3" />
      <rect x="3" y="14" width="4" height="6" rx="1" />
      <rect x="17" y="14" width="4" height="6" rx="1" />
      <path d="M17 20a4 4 0 01-4 4h-1" />
    </svg>
  ),
  Beef: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M5 8c0-2 1-4 4-4s4 1 5 3c1-1 3-1 4 0 2 2 1 5-1 6l-1 6-9 1-3-7 1-5z" />
    </svg>
  ),
  ShieldSm: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z" />
    </svg>
  ),
  Drop: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M12 3s7 8 7 13a7 7 0 11-14 0c0-5 7-13 7-13z" />
    </svg>
  ),
  Flask: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M9 3h6M10 3v6L4 19a2 2 0 002 3h12a2 2 0 002-3l-6-10V3" />
    </svg>
  ),
  Doc: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M14 3H6a1 1 0 00-1 1v16a1 1 0 001 1h12a1 1 0 001-1V8l-5-5z" />
      <path d="M14 3v5h5M8 13h8M8 17h6" />
    </svg>
  ),
  Tag: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 12V3h9l9 9-9 9-9-9z" />
      <circle cx="8" cy="8" r="1.5" />
    </svg>
  ),
  Award: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <circle cx="12" cy="9" r="6" />
      <path d="M8 14l-2 7 6-3 6 3-2-7" />
    </svg>
  ),
  Cap: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 9l9-4 9 4-9 4-9-4z" />
      <path d="M7 11v5c0 1 2 3 5 3s5-2 5-3v-5" />
    </svg>
  ),
  People: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <circle cx="9" cy="8" r="3" />
      <circle cx="17" cy="9" r="2.5" />
      <path d="M3 19c0-3 3-5 6-5s6 2 6 5M14 19c0-2 2-4 4-4s4 2 4 4" />
    </svg>
  ),
  Factory: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 21V9l5 4V9l5 4V9l8 5v7H3z" />
      <path d="M7 17h2M11 17h2M15 17h2" />
    </svg>
  ),
  Discount: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <circle cx="12" cy="12" r="9" />
      <path d="M8 16l8-8M9 9h.01M15 15h.01" />
    </svg>
  ),
  Chat: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M21 12a8 8 0 11-3.5-6.6L21 4l-1.5 3.5A8 8 0 0121 12z" />
    </svg>
  ),
  Cocho: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M3 9l3 11h12l3-11" />
      <path d="M3 9h18M8 13c1-1 3-1 4 0s3 1 4 0" />
    </svg>
  ),
  ChatBubble: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M21 12a9 9 0 11-4-7.5L21 3l-1.5 4A9 9 0 0121 12z" />
    </svg>
  ),
  Insta: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="5" />
      <circle cx="12" cy="12" r="4" />
      <circle cx="17.5" cy="6.5" r="0.7" fill="currentColor" />
    </svg>
  ),
  Mail: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="3" y="5" width="18" height="14" rx="1" />
      <path d="M3 7l9 7 9-7" />
    </svg>
  ),
  Pin: (p) => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M12 22s7-7 7-13a7 7 0 10-14 0c0 6 7 13 7 13z" />
      <circle cx="12" cy="9" r="2.5" />
    </svg>
  ),
  WhatsApp: (p) => (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M20.5 3.5A10.5 10.5 0 003.4 15.8L2 22l6.4-1.4A10.5 10.5 0 1020.5 3.5zm-8.5 17a8.6 8.6 0 01-4.4-1.2l-.3-.2-3.8.9.9-3.7-.2-.3a8.6 8.6 0 117.8 4.5zm4.8-6.5c-.3-.1-1.6-.8-1.9-.9-.3-.1-.4-.1-.6.1l-.9 1.1c-.2.2-.3.2-.6.1-.3-.1-1.3-.5-2.5-1.6-.9-.8-1.5-1.9-1.7-2.2-.2-.3 0-.5.1-.6l.4-.5.3-.5c.1-.2 0-.4 0-.5l-.8-1.9c-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.2s.9 2.6 1.1 2.8c.1.2 1.9 2.9 4.6 4 .6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.6-.7 1.8-1.3.2-.6.2-1.2.2-1.3-.1-.1-.3-.2-.6-.3z" />
    </svg>
  ),
};

// ============================================================
// NAV
// ============================================================
function Nav() {
  return (
    <header className="nav">
      <a href="#top" className="nav-logo">
        <img src="assets/nutrow-logo.png" alt="NUTROW" />
      </a>
      <nav className="nav-links">
        <a href="#produtos">Produtos</a>
        <a href="#sobre">Sobre</a>
        <a href="#como-comprar">Como Comprar</a>
        <a href="#contato">Contato</a>
      </nav>
      <a href="#cta" className="btn btn-primary nav-cta">Quero saber mais</a>
      <button className="nav-burger" aria-label="Menu"><span></span></button>
    </header>
  );
}

// ============================================================
// STICKY NAV — appears after user scrolls past hero
// ============================================================
function StickyNav() {
  const [visible, setVisible] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 300);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);
  const close = () => setMobileOpen(false);
  return (
    <>
      <header className={"sticky-nav " + (visible ? "show" : "")}>
        <nav className="sticky-nav-links">
          <a href="#produtos">Produtos</a>
          <a href="#sobre">Sobre</a>
          <a href="#como-comprar">Como Comprar</a>
          <a href="#contato">Contato</a>
        </nav>
        <a href="#top" className="sticky-nav-logo" aria-label="NUTROW — início">
          <img src="assets/nutrow-logo.png" alt="NUTROW" />
        </a>
        <div className="sticky-nav-right">
          <a href="#cta" className="btn btn-primary nav-cta sticky-nav-cta">Quero saber mais</a>
          <button
            className={"nav-burger sticky-nav-burger " + (mobileOpen ? "open" : "")}
            aria-label="Menu"
            aria-expanded={mobileOpen}
            onClick={() => setMobileOpen(v => !v)}
          ><span></span></button>
        </div>
      </header>
      <div className={"mobile-menu " + (mobileOpen ? "open" : "")} onClick={close}>
        <div className="mobile-menu-inner" onClick={(e) => e.stopPropagation()}>
          <a href="#produtos" onClick={close}>Produtos</a>
          <a href="#sobre" onClick={close}>Sobre</a>
          <a href="#como-comprar" onClick={close}>Como Comprar</a>
          <a href="#contato" onClick={close}>Contato</a>
          <a href="#cta" className="btn btn-primary" onClick={close}>Quero saber mais</a>
        </div>
      </div>
    </>
  );
}

// ============================================================
// HERO
// ============================================================
function Hero() {
  return (
    <section className="hero" id="top">
      <Nav />
      <div className="hero-inner">
        <div>
          <div className="eyebrow hero-eyebrow">Suplemento mineral e proteico · direto do fabricante</div>
          <div className="hero-logo">
            <img src="assets/nutrow-logo.png" alt="NUTROW" />
          </div>
          <div className="hero-line"></div>
          <h1 className="hero-title">
            O rebanho sente.
            <span className="accent">O bolso agradece.</span>
          </h1>
          <p className="hero-sub">
            Suplementação de alta performance para bovinos de corte e leite.
            Compre direto do fabricante, receba na fazenda e veja o resultado
            <span className="o"> no cocho e na balança.</span>
          </p>
          <div className="hero-ctas">
            <a href="#produtos" className="btn btn-primary">Ver Produtos</a>
            <a href="#cta" className="btn btn-ghost-dark">
              Comprar pelo Whatsapp <span className="btn-arrow">→</span>
            </a>
          </div>
        </div>

        <div className="hero-stats">
          <div className="hero-stat">
            <div className="hero-stat-val"><CountStat value={200} prefix="+" suffix="g" /></div>
            <div className="hero-stat-lbl">Ganho de peso por dia</div>
          </div>
          <div className="hero-stat">
            <div className="hero-stat-val"><CountStat value={15} prefix="+" suffix="%" delay={150} /></div>
            <div className="hero-stat-lbl">Produção de leite</div>
          </div>
          <div className="hero-stat">
            <div className="hero-stat-val"><CountStat value={100} suffix="%" delay={300} /></div>
            <div className="hero-stat-lbl">Registro MAPA garantido</div>
          </div>
        </div>
      </div>

      <div className="hero-strip">
        <div className="hero-strip-left">
          <span>— Registro MAPA</span>
          <span>— Venda Direta</span>
          <span>— Entrega na Fazenda</span>
          <span>— Suporte Técnico</span>
        </div>
        <div className="hero-strip-right">
          <span>Scroll</span>
          <span>↓</span>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// QUEM SOMOS
// ============================================================
function QuemSomos() {
  return (
    <section className="section light" id="sobre">
      <div className="container quem-grid">
        <div>
          <div className="eyebrow">Quem somos</div>
          <h2 className="headline" style={{marginTop: 24}}>
            Nutrição que<br/>converte em<br/>
            <span className="accent">arroba.</span>
          </h2>
          <div className="short-bar"></div>
          <p className="body-text muted-dark">
            A NUTROW é fabricante de suplemento mineral e proteico para bovinos.
            Vendemos <strong>direto da fábrica para o produtor</strong>, sem
            atravessador, com registro MAPA e suporte técnico no WhatsApp.
          </p>
          <p className="body-text muted-dark" style={{marginTop: 16}}>
            Porque o boi que come bem, engorda mais. E o produtor que compra
            direto, paga menos.
          </p>
          <div className="callout-light">
            <div className="eyebrow">Por que comprar direto</div>
            <p>Sem revenda, sem atravessador. <span className="o">ATÉ 30%</span> mais barato que o mesmo produto na revenda. Você fala direto com quem fabrica.</p>
          </div>
        </div>

        <div className="feature-grid">
          {[
            { Icon: Icon.ShieldSm, title: "Registro MAPA", desc: "Composição garantida no rótulo" },
            { Icon: Icon.Trend, title: "Resultado Real", desc: "GPD mensurável na balança" },
            { Icon: Icon.Truck, title: "Entrega na Fazenda", desc: "Direto do fabricante para você" },
            { Icon: Icon.Headset, title: "Suporte Técnico", desc: "Tira-dúvidas no WhatsApp" },
          ].map((f, i) => (
            <div className="feature-card" key={i}>
              <f.Icon className="feature-icon" />
              <div className="feature-title">{f.title}</div>
              <div className="feature-desc">{f.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============================================================
// RESULTADO POR PRODUTO
// ============================================================
function ResultadoPorProduto() {
  const stats = [
    {
      icon: Icon.Beef,
      name: "Nutrow Engorda Max",
      val: "+200g",
      lbl: "Ganho de peso por dia",
      desc: "Mais arroba na balança em menos tempo de cocho.",
    },
    {
      icon: Icon.ShieldSm,
      name: "Nutrow Imuno",
      val: "90%",
      lbl: "Menos bicheira no rebanho",
      desc: "Selênio e zinco quelados que fortalecem a imunidade do animal.",
    },
    {
      icon: Icon.Drop,
      name: "Nutrow Leite",
      val: "+15%",
      lbl: "Produção de leite por vaca",
      desc: "Cálcio e fósforo elevados para sustentar a lactação sem ureia.",
    },
  ];
  return (
    <section className="section dark">
      <div className="container">
        <div className="result-head">
          <div className="eyebrow">Resultado por produto</div>
          <h2 className="headline" style={{marginTop: 18}}>
            Cada produto,<br/>um <span className="accent">resultado real.</span>
          </h2>
          <p>Não é promessa. São números medidos em fazendas que já usam o suplemento NUTROW direto do fabricante.</p>
        </div>

        <div className="result-stats">
          {stats.map((s, i) => (
            <div className="result-stat" key={i}>
              <div className="result-stat-idx">
                <s.icon className="result-stat-icon" />
                <span>{String(i+1).padStart(2,"0")} / 03</span>
              </div>
              <div className="result-stat-name">{s.name}</div>
              <div className="result-stat-val">{s.val}</div>
              <div className="result-stat-lbl">{s.lbl}</div>
              <p className="result-stat-desc">{s.desc}</p>
            </div>
          ))}
        </div>

        <div className="result-bottom">
          <div className="result-bottom-cell">
            <div className="result-bottom-num">30%</div>
            <div className="result-bottom-lbl">Mais barato direto da fábrica</div>
          </div>
          <div className="result-bottom-cell">
            <div className="result-bottom-num">100%</div>
            <div className="result-bottom-lbl">Registro MAPA garantido</div>
          </div>
          <div className="result-bottom-cell">
            <div className="result-bottom-num">0</div>
            <div className="result-bottom-lbl">Atravessador entre nós</div>
          </div>
          <div className="result-bottom-cell">
            <div className="result-bottom-num">BR</div>
            <div className="result-bottom-lbl">Entregamos em todo país</div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.SectionsTop = { Nav, StickyNav, Hero, QuemSomos, ResultadoPorProduto, Icon };
