// Nav.jsx — sticky translucent top nav + slim "connects to" trust strip
const navLinks = [
  { label: "The Audit", href: "#convert" },
  { label: "Case Studies", href: "#showcase", dropdown: [
    { label: "Her Fantasy Box", href: "/conversion/case-study/subscription-purchase-growth", sub: "Subscription & purchase growth" },
    { label: "Annabella", href: "/conversion/case-study/dtc-baby-brand", sub: "Audit-led Shopify rebuild" },
  ] },
  { label: "How it works", href: "#how" },
  { label: "FAQs", href: "#faq" },
];

function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [onLight, setOnLight] = useState(false);
  const [openIdx, setOpenIdx] = useState(-1);
  const [menuOpen, setMenuOpen] = useState(false);
  const [mCasesOpen, setMCasesOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    document.body.classList.toggle("nav-menu-open", menuOpen);
    return () => { document.body.style.overflow = ""; document.body.classList.remove("nav-menu-open"); };
  }, [menuOpen]);
  useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 24);
      const lights = document.querySelectorAll(".section--light");
      let light = false;
      lights.forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top <= 37 && r.bottom >= 37) light = true;
      });
      setOnLight(light);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const linkColor = onLight ? "#3A3A42" : "var(--fg2)";
  const linkHover = onLight ? "#0E0E10" : "var(--fg1)";
  const secondaryCtaStyle = onLight
    ? {
        animationDelay: ".58s",
        color: "#141419",
        background: "rgba(255,255,255,0.88)",
        borderColor: "rgba(0,0,0,0.16)",
        boxShadow: "0 10px 26px rgba(0,0,0,0.12), inset 0 1px 0 rgba(255,255,255,0.65)",
        backdropFilter: "blur(18px)",
        WebkitBackdropFilter: "blur(18px)",
      }
    : {
        animationDelay: ".58s",
        color: "#F8F5FF",
        background: "linear-gradient(180deg, rgba(31,24,48,0.94) 0%, rgba(17,13,28,0.92) 100%)",
        borderColor: "rgba(255,255,255,0.24)",
        boxShadow: "0 12px 32px rgba(0,0,0,0.42), inset 0 1px 0 rgba(255,255,255,0.12)",
        backdropFilter: "blur(18px)",
        WebkitBackdropFilter: "blur(18px)",
        textShadow: "0 1px 2px rgba(0,0,0,0.42)",
      };
  return (
    <React.Fragment>
    <nav style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
      transition: "background .3s, border-color .3s, backdrop-filter .3s",
      background: onLight ? "rgba(245,245,247,0.82)" : (scrolled ? "rgba(2,3,13,0.74)" : "transparent"),
      backdropFilter: (scrolled || onLight) ? "blur(16px)" : "none",
      WebkitBackdropFilter: (scrolled || onLight) ? "blur(16px)" : "none",
      borderBottom: `1px solid ${onLight ? "rgba(0,0,0,0.08)" : (scrolled ? "var(--border-subtle)" : "transparent")}`,
    }}>
      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 74 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <a href="#top" aria-label="Conversion Works home" style={{ display: "inline-flex", alignItems: "center", textDecoration: "none" }}>
            <span className="nav-load-logo" style={{ display: "inline-flex" }}><Logo height={42} dark={onLight} /></span>
          </a>
          <a href="https://www.taurist.com/" className="nav-byline" style={{ fontFamily: "var(--font-ui)", fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: onLight ? "rgba(0,0,0,0.42)" : "var(--fg3)", paddingLeft: 12, borderLeft: `1px solid ${onLight ? "rgba(0,0,0,0.14)" : "var(--border-default)"}`, transition: "color .3s, border-color .3s", textDecoration: "none" }}>
            by Taurist
          </a>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 34 }} className="nav-links">
          {navLinks.map((l, i) => {
            const linkStyle = {
              fontFamily: "var(--font-ui)", fontSize: 14, fontWeight: 500,
              color: linkColor, textDecoration: "none", transition: "color .15s",
              animationDelay: `${(0.46 + i * 0.05).toFixed(2)}s`,
            };
            if (!l.dropdown) {
              return (
                <a key={l.label} href={l.href} className="nav-load-link" style={linkStyle}
                  onMouseEnter={(e) => (e.currentTarget.style.color = linkHover)}
                  onMouseLeave={(e) => (e.currentTarget.style.color = linkColor)}
                >{l.label}</a>
              );
            }
            const open = openIdx === i;
            return (
              <div key={l.label} style={{ position: "relative" }}
                onMouseEnter={() => setOpenIdx(i)} onMouseLeave={() => setOpenIdx(-1)}>
                <a href={l.href} className="nav-load-link" style={{ ...linkStyle, display: "inline-flex", alignItems: "center", gap: 5, color: open ? linkHover : linkColor }}>
                  {l.label}
                  <i className="ri-arrow-down-s-line" style={{ fontSize: 16, transition: "transform .2s", transform: open ? "rotate(180deg)" : "none" }} />
                </a>
                <div style={{ position: "absolute", top: "100%", left: -8, paddingTop: 14, opacity: open ? 1 : 0, transform: open ? "translateY(0)" : "translateY(-6px)", pointerEvents: open ? "auto" : "none", transition: "opacity .18s, transform .18s" }}>
                  <div style={{ minWidth: 248, padding: 7, borderRadius: 14, background: "rgba(11,16,32,0.96)", border: "1px solid var(--border-default)", backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)", boxShadow: "0 18px 44px rgba(0,0,0,0.5)" }}>
                    {l.dropdown.map((d) => (
                      <a key={d.label} href={d.href} style={{ display: "block", padding: "10px 13px", borderRadius: 9, textDecoration: "none", transition: "background .15s" }}
                        onMouseEnter={(e) => (e.currentTarget.style.background = "rgba(255,255,255,0.05)")}
                        onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
                        <span style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: 14, fontWeight: 600, color: "var(--fg1)" }}>{d.label}</span>
                        <span style={{ display: "block", fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 12.5, color: "var(--fg3)", marginTop: 2 }}>{d.sub}</span>
                      </a>
                    ))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }} className="nav-cta-group">
          <a href="#cta" className="btn btn-secondary btn-sm nav-load-cta nav-secondary-cta" style={secondaryCtaStyle}>Get 5 AI Fixes</a>
          <a href="#cta" className="btn btn-primary btn-sm nav-load-cta nav-primary-cta" style={{ animationDelay: ".64s" }}>Book a Shopify audit</a>
          <button type="button" className="nav-burger" aria-label="Open menu" onClick={() => setMenuOpen(true)}><i className="ri-menu-line" /></button>
        </div>
      </div>
    </nav>
    {menuOpen && (
      <div className="nav-mobile-menu">
        <div className="nmm-head">
          <div className="nmm-id">
            <a href="#top" aria-label="Conversion Works home" onClick={() => setMenuOpen(false)} style={{ display: "inline-flex" }}>
              <Logo height={42} />
            </a>
            <a href="https://www.taurist.com/" className="nmm-byline" onClick={() => setMenuOpen(false)}>by Taurist</a>
          </div>
          <button type="button" className="nmm-close" aria-label="Close menu" onClick={() => setMenuOpen(false)}><i className="ri-close-line" /></button>
        </div>
        <nav className="nmm-links">
          {navLinks.map((l) => l.dropdown ? (
            <div key={l.label} className="nmm-group">
              <button type="button" className="nmm-link nmm-link--btn" aria-expanded={mCasesOpen} onClick={() => setMCasesOpen((o) => !o)}>
                {l.label}
                <i className="ri-arrow-down-s-line" style={{ transition: "transform .2s", transform: mCasesOpen ? "rotate(180deg)" : "none" }} />
              </button>
              <div className={"nmm-cases-sub" + (mCasesOpen ? " open" : "")}>
                {l.dropdown.map((d) => (
                  <a key={d.label} href={d.href} className="nmm-sublink" onClick={() => setMenuOpen(false)}>
                    <b>{d.label}</b>{d.sub}
                  </a>
                ))}
              </div>
            </div>
          ) : (
            <a key={l.label} href={l.href} className="nmm-link" onClick={() => setMenuOpen(false)}>{l.label}</a>
          ))}
          <a href="#cta" className="btn btn-secondary nmm-cta nmm-cta--secondary" onClick={() => setMenuOpen(false)}>Get 5 AI Fixes</a>
          <a href="#cta" className="btn btn-primary nmm-cta" onClick={() => setMenuOpen(false)}>Book a Shopify audit</a>
        </nav>
        <div className="nmm-foot">
          <a href="https://www.taurist.com/" target="_blank" rel="noopener noreferrer">taurist</a>
          <span>|</span>
          <a href="https://www.taurist.com/siteworks" target="_blank" rel="noopener noreferrer">siteworks</a>
          <span>|</span>
          <a href="https://www.taurist.com/workers" target="_blank" rel="noopener noreferrer">workers</a>
        </div>
      </div>
    )}
    </React.Fragment>
  );
}

// client logo wall — the Shopify brands we've audited, in two scrolling rows
function TrustStrip() {
  const clients = [
    { s: "juvenon",         a: "Juven\u00f6n" },
    { s: "annabella",       a: "Annabella" },
    { s: "drunken-cookies", a: "Drunken Cookies" },
    { s: "crew-supply-co",  a: "Crew Supply Co." },
    { s: "mifold",          a: "mifold" },
    { s: "her-fantasy-box", a: "Her Fantasy Box" },
    { s: "empava",          a: "Empava" },
    { s: "lirys-jewelry",   a: "Liry's Jewelry" },
  ];
  const metrics = [
    { prefix: "$",  to: 500,  decimals: 0, suffix: "M+",    label: "Additional / influenced revenue", short: "Influenced revenue" },
    {               to: 17.8, decimals: 1, suffix: "%",     label: "Average conversion-rate lift",   short: "Avg. conversion lift" },
    { prefix: "+$", to: 240,  decimals: 0, suffix: "k",     label: "Added revenue from one test",     short: "From one test" },
    {               to: 1,    decimals: 0, suffix: " week", label: "Audit roadmap after access",      short: "Audit roadmap" },
  ];
  // two horizontal rows scrolling in opposite directions
  const rows = [
    { items: clients.slice(0, 4), dir: "thv-left",  dur: 32 },
    { items: clients.slice(4),    dir: "thv-right", dur: 36 },
  ];
  const ref = useReveal();
  return (
    <div className="tools-band">
      <div ref={ref} className="reveal wrap proof-banner">
        {/* left — copy + single-line metrics */}
        <div className="proof-banner__left">
          <p className="proof-banner__text">Built on real Shopify audits and winning tests.</p>
          <div className="bn-metrics">
            {metrics.map((m, i) => (
              <div className="bn-metric" key={i}>
                <div className="bn-metric__num">{m.prefix}<CountUp to={m.to} decimals={m.decimals} /><span className="bn-metric__suffix">{m.suffix}</span></div>
                <div className="bn-metric__label"><span className="lbl-full">{m.label}</span><span className="lbl-short">{m.short}</span></div>
              </div>
            ))}
          </div>
        </div>
        {/* right — 2 horizontal logo rows */}
        <div className="proof-rows" aria-hidden="true">
          {rows.map((row, ri) => {
            const loop = [...row.items, ...row.items, ...row.items];
            return (
              <div className="proof-row" key={ri}>
                <div className={"proof-row-track " + row.dir} style={{ animationDuration: `${row.dur}s` }}>
                  {loop.map((c, k) => (
                    <div className="proof-tile" key={k}>
                      <img src={rasterAsset(`assets/ecom-logos/${c.s}`)} alt={c.a} loading="lazy" />
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// counts 0 → `to` once it scrolls into view
function CountUp({ to, dur = 1500, decimals = 0 }) {
  const [n, setN] = useState(0);
  const ref = useRef(null);
  const done = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { setN(to); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !done.current) {
          done.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / dur);
            const eased = 1 - Math.pow(1 - t, 3);
            setN(eased * to);
            if (t < 1) requestAnimationFrame(tick);
            else setN(to);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to, dur]);
  return <span ref={ref}>{Number(n).toFixed(decimals)}</span>;
}

Object.assign(window, { Nav, TrustStrip, CountUp });
