/* ═══════════════════════════════════════════════════════════════════
   Top sections: Nav · Hero · CredBar · VSL  (Poligus)
   ═══════════════════════════════════════════════════════════════════ */

const NAV_LINKS = [
  { label: "Recursos", href: "#recursos" },
  { label: "Planos",   href: "#planos" },
  { label: "FAQ",      href: "#faq" },
  { label: "Contato",  href: "#contato" },
];

const Nav = ({ scrolled }) => {
  const [open, setOpen] = React.useState(false);
  return (
    <nav className="nav-mobile" style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 100, padding: "0 5%",
      background: scrolled ? "rgba(5,8,16,0.85)" : "rgba(5,8,16,0.35)",
      backdropFilter: "blur(24px) saturate(150%)", WebkitBackdropFilter: "blur(24px) saturate(150%)",
      borderBottom: scrolled ? "1px solid var(--line-strong)" : "1px solid var(--line)",
      transition: "all 0.4s ease", display: "flex", alignItems: "center", justifyContent: "space-between", height: 72,
    }}>
      <a href="#top" className="logo-mobile" style={{ display: "flex", alignItems: "center", textDecoration: "none" }}>
        <PoligusLogo height={44} />
      </a>

      {/* desktop links */}
      <div className="nav-links" style={{ display: "flex", alignItems: "center", gap: 30 }}>
        {NAV_LINKS.map(l => (
          <a key={l.label} href={l.href} className="nav-link" style={{
            color: "var(--ink-2)", textDecoration: "none", fontSize: 16.5, fontWeight: 500,
            fontFamily: "var(--font-body)", transition: "color .25s ease",
          }}
            onMouseEnter={e => e.currentTarget.style.color = "var(--cyan)"}
            onMouseLeave={e => e.currentTarget.style.color = "var(--ink-2)"}
            onTouchStart={e => e.currentTarget.style.color = "var(--cyan)"}
            onTouchEnd={e => e.currentTarget.style.color = "var(--ink-2)"}>{l.label}</a>
        ))}
      </div>

      <div className="nav-actions" style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <a href={LOGIN_URL} onClick={openLink(LOGIN_URL)} target="_blank" rel="noopener noreferrer" className="nav-link nav-enter" style={{
          color: "var(--ink-1)", textDecoration: "none", fontSize: 16.5, fontWeight: 600,
          padding: "9px 18px", borderRadius: 12, border: "1px solid var(--line-strong)",
          fontFamily: "var(--font-body)", transition: "all .25s ease",
        }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--cyan)"; e.currentTarget.style.color = "var(--cyan-2)"; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--ink-1)"; }}
          onTouchStart={e => { e.currentTarget.style.borderColor = "var(--cyan)"; e.currentTarget.style.color = "var(--cyan-2)"; }}
          onTouchEnd={e => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--ink-1)"; }}>Entrar</a>
        <a href={SIGNUP_URL} onClick={openLink(SIGNUP_URL)} target="_blank" rel="noopener noreferrer" className="btn-primary nav-cta-btn" style={{ padding: "11px 22px", fontSize: 16.5, gap: 8, minHeight: "auto", width: "auto" }}>
          <Icon name="bolt" size={16} />
          <span className="nav-cta-text">Testar 7 dias grátis</span>
        </a>
        {/* mobile hamburger */}
        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)} style={{
          display: "none", background: "rgba(125,211,255,0.08)", border: "1px solid var(--line-strong)",
          borderRadius: 10, width: 42, height: 42, color: "var(--cyan)", cursor: "pointer",
          alignItems: "center", justifyContent: "center",
        }}>
          <Icon name={open ? "plus" : "dashboard"} size={20} />
        </button>
      </div>

      {/* mobile dropdown panel */}
      {open && (
        <div className="nav-panel" style={{
          position: "absolute", top: 72, left: 0, right: 0, padding: "14px 5% 22px",
          background: "rgba(5,8,16,0.97)", borderBottom: "1px solid var(--line-strong)",
          backdropFilter: "blur(24px)", display: "flex", flexDirection: "column", gap: 4,
        }}>
          {NAV_LINKS.map(l => (
            <a key={l.label} href={l.href} onClick={() => setOpen(false)} style={{
              color: "var(--ink-1)", textDecoration: "none", fontSize: 17, fontWeight: 500,
              padding: "14px 8px", borderBottom: "1px solid var(--line)", fontFamily: "var(--font-body)",
            }}>{l.label}</a>
          ))}
        </div>
      )}
    </nav>
  );
};


/* ═══ HERO ═════════════════════════════════════════════════════════ */
const Hero = () => {
  const heroRef = React.useRef(null);
  const [mouse, setMouse] = React.useState({ x: 0.5, y: 0.5 });

  React.useEffect(() => {
    const onMove = (e) => {
      if (!heroRef.current) return;
      const r = heroRef.current.getBoundingClientRect();
      setMouse({ x: (e.clientX - r.left) / r.width, y: (e.clientY - r.top) / r.height });
    };
    const onTouch = (e) => {
      if (!heroRef.current || !e.touches || !e.touches[0]) return;
      const r = heroRef.current.getBoundingClientRect();
      const t = e.touches[0];
      setMouse({ x: (t.clientX - r.left) / r.width, y: (t.clientY - r.top) / r.height });
    };
    const el = heroRef.current;
    if (el) {
      el.addEventListener("mousemove", onMove);
      el.addEventListener("touchmove", onTouch, { passive: true });
      el.addEventListener("touchstart", onTouch, { passive: true });
    }
    return () => {
      if (el) {
        el.removeEventListener("mousemove", onMove);
        el.removeEventListener("touchmove", onTouch);
        el.removeEventListener("touchstart", onTouch);
      }
    };
  }, []);

  const px = (mouse.x - 0.5) * 30, py = (mouse.y - 0.5) * 30;

  return (
    <section id="top" ref={heroRef} className="hero-pad-mobile" style={{
      minHeight: "100vh", position: "relative", overflow: "hidden",
      display: "flex", alignItems: "center",
      background: "radial-gradient(ellipse at 30% 20%, #0a1230 0%, #050810 60%)",
      padding: "120px 5% 80px",
    }}>
      <div style={{ position: "absolute", inset: 0, opacity: 0.85, transform: `translate(${px * 0.3}px, ${py * 0.3}px)`, transition: "transform 0.3s ease-out" }}>
        <PcbSheet opacity={0.7} />
      </div>
      <div className="hero-grid-bg" style={{ transform: `translate(${px * 0.6}px, ${py * 0.6}px)`, transition: "transform 0.2s ease-out" }} />
      <AmbientOrbs palette="cool" />
      <Particles density={14} />
      <div style={{ position: "absolute", left: 0, right: 0, height: 2, background: "linear-gradient(90deg, transparent, rgba(168,228,255,0.5), transparent)", animation: "scan 8s linear infinite", pointerEvents: "none", filter: "blur(1px)" }} />

      {/* desktop sphere */}
      <div className="hero-sphere-desktop" style={{
        position: "absolute", right: "4%", top: "50%",
        transform: `translateY(-50%) translate(${-px * 0.5}px, ${-py * 0.5}px)`,
        transition: "transform 0.4s ease-out",
        width: 620, height: 620, display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <CircuitBackdrop size={620} />
        <div style={{ position: "absolute", width: 500, height: 500, borderRadius: "50%", border: "1px solid rgba(125,211,255,0.18)", animation: "rotate-ring 24s linear infinite" }}>
          <div style={{ position: "absolute", top: -5, left: "50%", marginLeft: -5, width: 10, height: 10, borderRadius: "50%", background: "#A8E4FF", boxShadow: "0 0 16px #A8E4FF, 0 0 30px #7DD3FF" }} />
        </div>
        <div style={{ position: "absolute", width: 380, height: 380, borderRadius: "50%", border: "1px solid rgba(168,228,255,0.20)", animation: "rotate-ring-rev 18s linear infinite" }}>
          <div style={{ position: "absolute", bottom: -4, left: "50%", marginLeft: -4, width: 8, height: 8, borderRadius: "50%", background: "#7DD3FF", boxShadow: "0 0 14px #7DD3FF" }} />
        </div>
        <div style={{ position: "absolute", width: 290, height: 290, borderRadius: "50%", border: "1px dashed rgba(125,211,255,0.4)", animation: "rotate-ring 11s linear infinite" }} />
        <PoligusSphere3D size={440} detail={1} />
      </div>

      {/* text block */}
      <div style={{ maxWidth: 720, position: "relative", zIndex: 4, width: "100%" }}>
        <div className="mobile-only reveal-scale" style={{
          justifyContent: "center", alignItems: "center",
          position: "relative", width: 300, height: 300, margin: "0 auto 28px",
        }}>
          <CircuitBackdrop size={300} />
          <div style={{ position: "absolute", inset: 0, borderRadius: "50%", border: "1px solid rgba(125,211,255,0.25)", animation: "rotate-ring 22s linear infinite" }}>
            <div style={{ position: "absolute", top: -3, left: "50%", marginLeft: -3, width: 6, height: 6, borderRadius: "50%", background: "#A8E4FF", boxShadow: "0 0 10px #A8E4FF" }} />
          </div>
          <div style={{ position: "absolute", width: "75%", height: "75%", borderRadius: "50%", border: "1px solid rgba(168,228,255,0.25)", animation: "rotate-ring-rev 16s linear infinite" }} />
          <PoligusSphere3D size={250} detail={1} />
        </div>

        <div className="tag-pill reveal" style={{ marginBottom: 22 }}>
          <span></span>POLIGUS · IA · NO · WHATSAPP
        </div>

        <h1 className="reveal" style={{
          fontFamily: "var(--font-display)",
          fontSize: "clamp(34px, 5.2vw, 68px)", fontWeight: 600,
          lineHeight: 1.04, letterSpacing: "-0.035em", marginBottom: 24,
        }}>
          <span style={{ color: "var(--ink-0)" }}>Seu WhatsApp trabalhando</span><br />
          <span
            style={{
              background: "linear-gradient(135deg,#A8E4FF 0%,#7DD3FF 40%,#2B7BFF 100%)",
              WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text",
              backgroundSize: "200% auto", animation: "shimmer-text 6s linear infinite",
            }}>para sua empresa</span><br />
          <span style={{ color: "var(--ink-0)" }}>24h por dia.</span>{" "}
          <span style={{
            background: "linear-gradient(135deg,#8C5BFF 0%,#2B7BFF 60%,#7DD3FF 100%)",
            WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text",
          }}>Sem parar.</span>
        </h1>

        <p className="reveal" style={{
          fontSize: "clamp(16px, 1.4vw, 18px)", color: "var(--ink-1)", lineHeight: 1.7,
          marginBottom: 26, maxWidth: 580, fontWeight: 400,
        }}>
          A <strong style={{ color: "var(--cyan-2)", fontWeight: 600 }}>Poligus</strong> atende clientes, responde mensagens, faz follow-up, agenda compromissos e organiza sua operação automaticamente — tudo direto no seu WhatsApp.
        </p>

        <div className="reveal" style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 32 }}>
          {HERO.pills.map(p => (
            <span key={p} style={{
              display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 15px", borderRadius: 50,
              background: "rgba(125,211,255,0.07)", border: "1px solid var(--line-strong)",
              fontSize: 14, color: "var(--cyan-2)", fontFamily: "var(--font-mono)", letterSpacing: 0.4,
            }}><Icon name="check" size={13} color="var(--cyan)" />{p}</span>
          ))}
        </div>

        <div className="reveal" style={{ display: "flex", gap: 14, flexWrap: "wrap", alignItems: "center" }}>
          <a href={SIGNUP_URL} onClick={openLink(SIGNUP_URL)} target="_blank" rel="noopener noreferrer" className="btn-whatsapp" style={{ background: "linear-gradient(135deg, #2B7BFF 0%, #0E4FCC 100%)", borderColor: "rgba(125,211,255,0.5)" }}>
            <Icon name="bolt" size={18} />
            Testar 7 dias grátis
          </a>
          <a href="#vsl" className="btn-outline">
            Assistir demonstração <Icon name="arrowRight" size={16} />
          </a>
        </div>
      </div>
    </section>
  );
};


/* ═══ CREDIBILITY BAR ══════════════════════════════════════════════ */
const CredBar = () =>
  <div style={{
    background: "linear-gradient(180deg, rgba(7,9,26,0.96), rgba(10,14,36,0.96))",
    borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)",
    padding: "20px 5%", position: "relative", overflow: "hidden",
  }}>
    <div className="cred-row" style={{
      maxWidth: 1180, margin: "0 auto", display: "flex", flexWrap: "wrap",
      gap: "14px 34px", justifyContent: "center", alignItems: "center",
    }}>
      {CRED.map((c, i) => (
        <span key={i} className="reveal" style={{
          display: "inline-flex", alignItems: "center", gap: 9,
          fontSize: 15, color: "var(--ink-2)", fontFamily: "var(--font-mono)", letterSpacing: 0.4,
        }}>
          <span style={{
            display: "inline-flex", width: 22, height: 22, borderRadius: "50%",
            background: "rgba(110,231,183,0.14)", border: "1px solid rgba(110,231,183,0.4)",
            alignItems: "center", justifyContent: "center", flexShrink: 0,
          }}><Icon name="check" size={13} color="#6EE7B7" /></span>
          {c}
        </span>
      ))}
    </div>
  </div>;


/* ═══ CHAT DEMO — IA atendendo ao vivo (substitui o VSL fake) ══════ */
const ChatDemo = () => {
  const D = CHAT_DEMO;
  const reduced = React.useRef(!!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches)).current;
  const [count, setCount] = React.useState(reduced ? D.messages.length : 0);
  const [typing, setTyping] = React.useState(false);
  const bodyRef = React.useRef(null);
  const startedRef = React.useRef(false);

  // autoscroll
  React.useEffect(() => {
    const el = bodyRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [count, typing]);

  // play the conversation when it scrolls into view (once), then loop
  React.useEffect(() => {
    if (reduced) return;
    const root = bodyRef.current && bodyRef.current.closest("section");
    if (!root) return;
    let timers = [];
    const clear = () => { timers.forEach(clearTimeout); timers = []; };
    const run = () => {
      clear(); setCount(0); setTyping(false);
      let acc = 600;
      D.messages.forEach((m, i) => {
        const isIA = m.from === "ia";
        const tw = isIA ? (m.typingBeforeMs || 900) : 0;
        if (isIA) {
          timers.push(setTimeout(() => setTyping(true), acc));
          acc += tw;
          timers.push(setTimeout(() => { setTyping(false); setCount(i + 1); }, acc));
        } else {
          acc += 650;
          timers.push(setTimeout(() => setCount(i + 1), acc));
        }
        acc += 350;
      });
      // loop após uma pausa
      timers.push(setTimeout(run, acc + 4200));
    };
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !startedRef.current) { startedRef.current = true; run(); }
      });
    }, { threshold: 0.4 });
    obs.observe(root);
    return () => { obs.disconnect(); clear(); };
  }, []);

  return (
    <section id="vsl" style={{ padding: "120px 5% 110px", position: "relative", overflow: "hidden",
      background: "radial-gradient(ellipse at 70% 30%, #0a1230 0%, #050810 65%)" }}>
      <Aurora />
      <div className="demo-wrap" style={{ maxWidth: 1080, margin: "0 auto", position: "relative", zIndex: 2,
        display: "grid", gridTemplateColumns: "1fr 380px", gap: 56, alignItems: "center" }}>
        <div className="demo-copy">
          <div className="tag-pill reveal-left" style={{ marginBottom: 22, display: "inline-flex" }}><span></span>{D.badge}</div>
          <h2 className="reveal-left" style={{
            fontFamily: "var(--font-display)", fontWeight: 600, lineHeight: 1.08, letterSpacing: "-0.03em",
            fontSize: "clamp(28px, 3.6vw, 48px)", marginBottom: 20, color: "var(--ink-0)",
          }}>
            Veja a Poligus atendendo um{" "}
            <span style={{ background: "linear-gradient(135deg,#A8E4FF,#2B7BFF)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", backgroundClip: "text" }}>cliente agora.</span>
          </h2>
          <p className="reveal-left" style={{ color: "var(--ink-2)", fontSize: 18, lineHeight: 1.7, maxWidth: 460, marginBottom: 28 }}>
            {D.subheadline}
          </p>
          <div className="reveal-left" style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
            {["Responde na hora", "Agenda sozinha", "Lembra do cliente"].map(t => (
              <span key={t} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 14px", borderRadius: 50,
                background: "rgba(37,211,102,0.08)", border: "1px solid rgba(37,211,102,0.3)", fontSize: 13.5, color: "#8af0b9",
                fontFamily: "var(--font-mono)", letterSpacing: 0.3 }}>
                <Icon name="check" size={12} color="#25D366" />{t}
              </span>
            ))}
          </div>
        </div>

        {/* PHONE */}
        <div className="reveal-scale" style={{ position: "relative" }}>
          <div className="phone">
            <div className="phone__notch" />
            <div className="phone__screen">
              <div className="wa__header">
                <span className="wa__avatar"><WhatsAppIcon size={20} /></span>
                <div>
                  <div className="wa__name">Atendimento · Barbearia</div>
                  <div className="wa__status"><span className="dot">●</span> online · Poligus IA</div>
                </div>
              </div>
              <div className="wa__body" ref={bodyRef}>
                {D.messages.slice(0, count).map((m, i) => (
                  <div key={i} className={"wa__msg " + (m.from === "ia" ? "in" : "out")}>
                    {m.text}
                    <span className="wa__time">{m.time}</span>
                  </div>
                ))}
                {typing && (
                  <div className="wa__typing"><span></span><span></span><span></span></div>
                )}
              </div>
              <div className="wa__footer">
                <div className="wa__inputbar" />
                <span className="wa__send"><Icon name="arrowRight" size={18} color="#0b141a" /></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};


Object.assign(window, { Nav, Hero, CredBar, ChatDemo });
