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

/* ============================================================
   Hooks & primitives
   ============================================================ */
function useReveal() {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el || inView) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setInView(true);
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.15, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [inView]);
  return [ref, inView];
}

function Reveal({ as: Tag = "div", delay = 0, className = "", children, ...rest }) {
  const [ref, inView] = useReveal();
  return (
    <Tag
      ref={ref}
      className={`reveal ${inView ? "in" : ""} ${className}`}
      style={{ "--reveal-delay": `${delay}ms`, ...(rest.style || {}) }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

function SplitText({ text, className = "", baseDelay = 0, perWord = 60 }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            el.classList.add("in");
            io.unobserve(el);
          }
        });
      },
      { threshold: 0.3 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const words = text.split(" ");
  return (
    <span ref={ref} className={`split ${className}`}>
      {words.map((w, i) => (
        <React.Fragment key={i}>
          <span
            className="split-word"
            style={{ "--word-delay": `${baseDelay + i * perWord}ms` }}
          >
            <span>{w}</span>
          </span>
          {i < words.length - 1 ? " " : ""}
        </React.Fragment>
      ))}
    </span>
  );
}

function MagneticCta({ children, className = "cta", href = "#", strength = 0.25, ...rest }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const x = e.clientX - r.left;
    const y = e.clientY - r.top;
    const cx = r.width / 2;
    const cy = r.height / 2;
    const dx = (x - cx) * strength;
    const dy = (y - cy) * strength;
    el.style.transform = `translate(${dx}px, ${dy}px)`;
    el.style.setProperty("--mx", `${(x / r.width) * 100}%`);
    el.style.setProperty("--my", `${(y / r.height) * 100}%`);
  };
  const onLeave = () => {
    const el = ref.current;
    if (!el) return;
    el.style.transform = "translate(0, 0)";
  };
  return (
    <a
      ref={ref}
      href={href}
      className={className}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
      onClick={(e) => {
        const isWa = (href || "").includes("whatsapp") || (href || "").includes("wa.me");
        if (isWa) {
          window.__trackWhatsApp?.(rest.label || "cta");
        } else {
          window.__pixel?.("ViewContent", { content_name: rest.label || "cta-click" });
        }
      }}
      {...rest}
    >
      {children}
    </a>
  );
}

function ArrowGlyph() {
  return (
    <span className="arrow" aria-hidden="true">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <line x1="5" y1="12" x2="19" y2="12" />
        <polyline points="12 5 19 12 12 19" />
      </svg>
    </span>
  );
}

function Counter({ to = 50, suffix = "", duration = 2000 }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const t0 = performance.now();
          const tick = (t) => {
            const p = Math.min(1, (t - t0) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return (
    <span ref={ref} className="counter">
      <span className="plus">+</span>{n}{suffix}
    </span>
  );
}

/* ============================================================
   Nav + scroll progress + floating WA
   ============================================================ */
function Chrome({ wa }) {
  const [scrolled, setScrolled] = useState(false);
  const [showFloat, setShowFloat] = useState(false);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 24);
      setShowFloat(y > 600);
      const doc = document.documentElement;
      const max = doc.scrollHeight - window.innerHeight;
      setProgress(max > 0 ? (y / max) * 100 : 0);

      // Pixel-style milestones
      const pct = max > 0 ? (y / max) : 0;
      if (pct >= 0.5 && !window.__s50) { window.__s50 = true; window.__pixel?.("Scroll50"); }
      if (pct >= 0.75 && !window.__s75) { window.__s75 = true; window.__pixel?.("Scroll75"); }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <>
      <div className="scroll-progress" style={{ "--p": `${progress}%` }} />
      <header className={`nav ${scrolled ? "scrolled" : ""}`}>
        <div className="container nav-inner">
          <a href="#top" className="nav-logo">
            <img src="assets/athera-logo.png" alt="" />
            <span>Athera</span>
            <small>Tecnologia</small>
          </a>
          <a href={wa} className="nav-cta" onClick={() => window.__trackWhatsApp?.("nav")}>
            <span className="dot" />
            <span>Quero minha prévia</span>
          </a>
        </div>
      </header>

      <a href={wa} className={`wa-float ${showFloat ? "show" : ""}`} onClick={() => window.__trackWhatsApp?.("floating")}>
        <span className="ico" aria-hidden="true">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M20.5 3.5A11 11 0 0 0 3.6 17.3L2 22l4.8-1.6A11 11 0 1 0 20.5 3.5Zm-8.5 17a9 9 0 0 1-4.6-1.3l-.3-.2-2.8 1 1-2.7-.2-.3a9 9 0 1 1 6.9 3.5Zm5-6.7c-.3-.1-1.6-.8-1.9-.9-.2-.1-.4-.1-.6.1-.2.3-.7.9-.9 1-.1.2-.3.2-.6.1a7.4 7.4 0 0 1-3.7-3.2c-.3-.5.3-.5.8-1.6.1-.2 0-.4 0-.5l-.9-2.1c-.2-.5-.5-.4-.6-.4h-.5c-.2 0-.5.1-.7.4a3 3 0 0 0-1 2.3c0 1.3 1 2.6 1.1 2.8.1.2 2 3 4.8 4.2 2.8 1.2 2.8.8 3.3.7.5 0 1.6-.6 1.8-1.3.2-.7.2-1.2.2-1.3-.1 0-.3-.1-.6-.2Z"/></svg>
        </span>
        <span className="label">Falar no WhatsApp</span>
      </a>
    </>
  );
}

/* ============================================================
   HERO
   ============================================================ */
function Hero({ wa }) {
  const visualRef = useRef(null);
  useEffect(() => {
    const el = visualRef.current;
    if (!el) return;
    const onScroll = () => {
      const r = el.getBoundingClientRect();
      const center = window.innerHeight / 2;
      const offset = (r.top + r.height / 2 - center) * -0.06;
      el.style.transform = `translateY(${offset}px)`;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section id="top" className="hero">
      <div className="container">
        <div className="hero-grid">
          <div>
            <Reveal>
              <span className="eyebrow">Athera · Construção digital</span>
            </Reveal>
            <h1 className="display-1 hero-headline">
              <SplitText text="Você só paga" perWord={70} />
              <br />
              <span style={{ fontStyle: "italic", fontFamily: "var(--serif)", color: "var(--accent)" }}>
                <SplitText text="depois de aprovar." perWord={70} baseDelay={400} />
              </span>
            </h1>
            <Reveal delay={600} className="hero-sub">
              Prévia em até 24h. Site publicado em até 5 dias úteis. Sem mensalidade.
            </Reveal>
            <Reveal delay={750}>
              <div className="hero-actions">
                <MagneticCta href="#fluxo" className="cta" label="hero-flow">
                  <span>Ver como funciona em tempo real</span>
                  <ArrowGlyph />
                </MagneticCta>
                <a href="#exemplos" className="cta-ghost">
                  <span>Ver exemplos entregues</span>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
                </a>
              </div>
              <div className="hero-micro">
                <span className="pulse" />
                <span>Sem cartão · Sem compromisso · Respondemos em até <b style={{ color: "var(--ink)", fontWeight: 600 }}>1h</b> pelo WhatsApp</span>
              </div>
            </Reveal>
          </div>

          <Reveal delay={400}>
            <div className="hero-visual-v2" ref={visualRef}>
              <div className="browser-frame">
                <div className="browser-chrome">
                  <div className="browser-dots"><span /><span /><span /></div>
                  <div className="browser-url">zagobikes.com.br</div>
                </div>
                <div className="browser-body">
                  <img src="https://image.thum.io/get/width/1200/crop/750/https://zagobikes.com.br" alt="Prévia de site Athera" />
                </div>
              </div>

              <div className="float-card fc-preview">
                <div className="row">
                  <span className="ico" aria-hidden="true">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                  </span>
                  <div>
                    <span className="label">Prévia entregue</span>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>em até 24h</div>
                  </div>
                </div>
              </div>

              <div className="float-card fc-approved dark">
                <span className="label">Status do cliente</span>
                <div className="big" style={{ color: "var(--accent-2)" }}>Aprovou ✓</div>
                <div className="delta">
                  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="6 9 12 15 18 9"/></svg>
                  site no ar há 2 min
                </div>
              </div>

              <div className="float-card fc-metric">
                <span className="label">Sites entregues / mês</span>
                <div className="big">42<span style={{ fontSize: 14, color: "var(--muted)", marginLeft: 6 }}>projetos</span></div>
                <div className="mini-bars">
                  {[0.5,0.7,0.4,0.85,0.6,0.95,0.75].map((h,i)=>(
                    <span key={i} style={{ height: `${h*100}%`, animationDelay: `${i*120}ms`, opacity: 0.35 + h*0.6 }} />
                  ))}
                </div>
              </div>
            </div>
          </Reveal>
        </div>

        <Reveal className="trust" delay={300}>
          <div>
            <span className="icon">●</span>
            <span><b>Joinville/SC</b> — base local, atendimento próximo.</span>
          </div>
          <div>
            <span className="icon">+</span>
            <span><b>+50 empresas</b> com presença digital estruturada.</span>
          </div>
          <div>
            <span className="icon">✓</span>
            <span><b>Pagamento</b> só após aprovação da prévia.</span>
          </div>
        </Reveal>

        {typeof MobileStats !== "undefined" ? <MobileStats /> : null}
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, SplitText, MagneticCta, ArrowGlyph, Counter, Chrome, Hero });
