/* ============================================================
   Nav + cinematic Hero (light, immersive, floating depth)
   ============================================================ */

function LangSwitch() {
  const { lang, setLang } = useT();
  const item = (code) => (
    <button key={code} onClick={() => setLang(code)}
      aria-pressed={lang === code}
      style={{ fontSize: 12.5, fontWeight: 700, letterSpacing: ".02em", padding: "5px 8px", borderRadius: 8,
        color: lang === code ? "var(--ink)" : "var(--ink-3)", background: lang === code ? "var(--surface-2)" : "transparent",
        transition: "color .2s, background .2s" }}>{code.toUpperCase()}</button>
  );
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 1 }} className="nav-lang" aria-label="Language">
      {item("da")}<span style={{ color: "var(--line-2)", fontSize: 12 }}>·</span>{item("en")}
    </span>
  );
}

function Nav() {
  const { L, lang } = useT();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const intgHref = lang === "en" ? "/en/integrations" : "/integrations";
  const links = [[L.nav.product, "#product"], [L.nav.integrations, intgHref], [L.nav.safety, "#product"], [L.nav.pricing, "#pricing"]];
  const close = () => setOpen(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 60);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  return (
    <header style={{ position: "fixed", top: scrolled ? 12 : 18, left: 0, right: 0, zIndex: 100, display: "flex", flexDirection: "column", alignItems: "center", gap: 10, padding: "0 16px", pointerEvents: "none", transition: "top .35s var(--ease)" }}>
      <div className="glass" style={{ display: "flex", alignItems: "center", gap: 4, padding: "8px 8px 8px 16px", borderRadius: 999, pointerEvents: "auto", maxWidth: "100%",
        background: scrolled ? "rgba(255,255,255,.9)" : undefined,
        boxShadow: scrolled ? "var(--shadow-lg)" : "var(--shadow)", transition: "box-shadow .35s var(--ease), background .35s" }}>
        <a href="#top" style={{ marginRight: 10 }} onClick={close}><Logo /></a>
        <nav style={{ display: "flex", gap: 2, alignItems: "center" }} className="nav-links">
          {links.map(([t, h]) => (
            <a key={t} href={h} style={{ fontSize: 14, fontWeight: 500, color: "var(--ink-2)", padding: "8px 12px", borderRadius: 999, transition: "color .2s, background .2s" }}
               onMouseEnter={e => { e.currentTarget.style.color = "var(--ink)"; e.currentTarget.style.background = "var(--surface-2)"; }}
               onMouseLeave={e => { e.currentTarget.style.color = "var(--ink-2)"; e.currentTarget.style.background = "transparent"; }}>{t}</a>
          ))}
        </nav>
        <span className="nav-lang-wrap" style={{ display: "inline-flex", margin: "0 4px 0 6px" }}><LangSwitch /></span>
        <a href="https://app.sanddo.ai/dashboard" className="btn btn-ghost nav-signin" style={{ height: 40, padding: "0 16px", fontSize: 14 }}>{L.nav.login}</a>
        <a href="#demo" className="btn btn-primary" style={{ height: 40, padding: "0 18px", fontSize: 14 }} onClick={close}>{L.nav.bookDemo}</a>
        <button type="button" className="nav-burger" aria-label="Menu" aria-expanded={open} onClick={() => setOpen(o => !o)}
          style={{ width: 40, height: 40, flex: "none", borderRadius: 999, display: "none", alignItems: "center", justifyContent: "center", color: "var(--ink)", transition: "background .2s" }}>
          {open
            ? <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
            : <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>}
        </button>
      </div>

      {open && (
        <div className="glass nav-menu" style={{ pointerEvents: "auto", width: "min(360px, calc(100vw - 32px))", borderRadius: 20, boxShadow: "var(--shadow-lg)", padding: 10, display: "grid", gap: 2 }}>
          {links.map(([t, h]) => (
            <a key={t} href={h} onClick={close}
               style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 15, fontWeight: 600, color: "var(--ink)", padding: "12px 14px", borderRadius: 12, transition: "background .2s" }}>
              {t}<Icon.arrow style={{ color: "var(--ink-4)" }} />
            </a>
          ))}
          <div style={{ height: 1, background: "var(--line)", margin: "8px 6px" }}></div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "4px 8px 6px" }}>
            <LangSwitch />
            <a href="https://app.sanddo.ai/dashboard" className="btn btn-ghost" style={{ height: 38, padding: "0 16px", fontSize: 14 }}>{L.nav.login}</a>
          </div>
        </div>
      )}

      <style>{`@media (max-width: 860px){ .nav-links,.nav-lang-wrap,.nav-signin{ display:none !important; } .nav-burger{ display:inline-flex !important; } }
        @media (min-width: 861px){ .nav-menu{ display:none !important; } }
        .nav-burger:hover{ background:var(--surface-2); }
        .nav-menu a:hover{ background:var(--surface-2); }`}</style>
    </header>
  );
}

/* ---- floating product fragments ---- */
function Frag({ children, w }) {
  return (
    <div className="glass" style={{ borderRadius: 14, padding: "11px 13px", width: w, boxShadow: "var(--shadow)", lineHeight: 1.4 }}>
      {children}
    </div>
  );
}
function TicketFrag({ initials, subject, pill, tag }) {
  return (
    <Frag w={194}>
      <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
        <span style={{ width: 26, height: 26, flex: "none", borderRadius: 8, background: "var(--surface-2)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, color: "var(--primary)" }}>{initials}</span>
        <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{subject}</span>
      </div>
      <div style={{ marginTop: 9 }}><span className={`pill ${pill}`}><span className="dot"></span>{tag}</span></div>
    </Frag>
  );
}
function ChipFrag({ label, pill, tag }) {
  return (
    <div className="glass" style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "10px 14px", borderRadius: 999, boxShadow: "var(--shadow)" }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)" }}>{label}</span>
      <span className={`pill ${pill}`}><span className="dot"></span>{tag}</span>
    </div>
  );
}
function GaugeFrag({ value, color, trustLabel }) {
  return (
    <div className="glass" style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px 10px 11px", borderRadius: 999, boxShadow: "var(--shadow)" }}>
      <Gauge value={value} size={34} stroke={4} color={color} />
      <span style={{ fontSize: 12.5, color: "var(--ink-2)", fontWeight: 600 }}>{trustLabel}</span>
    </div>
  );
}

function makeFragments(L) {
  const f = L.hero.frag;
  return [
    { x: "8%",  y: "19%", d: 64, el: <TicketFrag initials="AB" subject={f.whereOrder} pill="pill-auto" tag={f.tagAuto} /> },
    { x: "73%", y: "15%", d: 52, el: <ChipFrag label={f.orderStatus} pill="pill-auto" tag={f.tagAuto} /> },
    { x: "83%", y: "63%", d: 70, el: <TicketFrag initials="LM" subject={f.refundReq} pill="pill-stop" tag={f.tagStop} /> },
    { x: "11%", y: "66%", d: 58, el: <GaugeFrag value={92} color="var(--auto)" trustLabel={f.trust} /> },
    { x: "62%", y: "80%", d: 46, el: <ChipFrag label={f.returns} pill="pill-auto" tag={f.tagAuto} /> },
    { x: "19%", y: "40%", d: 40, el: <ChipFrag label={f.productQ} pill="pill-approve" tag={f.tagApprove} /> },
    { x: "87%", y: "37%", d: 60, el: (
        <Frag w={210}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 9 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: "var(--ink)" }}>Order #21994DE</span>
            <span style={{ marginLeft: "auto", fontSize: 9, fontWeight: 700, letterSpacing: ".04em", color: "var(--auto)", background: "var(--auto-tint)", padding: "2px 6px", borderRadius: 5 }}>SHIPPED</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, color: "var(--ink-3)" }}><span>{f.amount}</span><span style={{ fontWeight: 700, color: "var(--ink)" }}>44.94 EUR</span></div>
        </Frag> ) },
    { x: "3%",  y: "45%", d: 50, el: <ChipFrag label={f.refund} pill="pill-stop" tag={f.tagStop} /> },
    { x: "68%", y: "45%", d: 44, el: (
        <Frag w={216}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 6 }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink)" }}>{f.reOrderStatus}</span>
            <span style={{ marginLeft: "auto", fontSize: 9, fontWeight: 700, letterSpacing: ".04em", color: "var(--stop)", background: "var(--stop-tint)", padding: "2px 6px", borderRadius: 5 }}>{f.blocked}</span>
          </div>
          <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{f.heldBy}</div>
        </Frag> ) },
    { x: "29%", y: "81%", d: 66, el: <GaugeFrag value={81} color="var(--approve)" trustLabel={f.trust} /> },
    { x: "40%", y: "11%", d: 38, el: <ChipFrag label={f.qaPassed} pill="pill-auto" tag="✓" /> },
  ];
}

function FloatingField() {
  const { L } = useT();
  const ref = useRef(null);
  const fragments = makeFragments(L);
  useEffect(() => {
    const field = ref.current; if (!field) return;
    let raf = 0, tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      tx = (e.clientX / window.innerWidth - 0.5);
      ty = (e.clientY / window.innerHeight - 0.5);
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const tick = () => {
      cx += (tx - cx) * 0.08; cy += (ty - cy) * 0.08;
      field.style.setProperty("--px", cx.toFixed(4));
      field.style.setProperty("--py", cy.toFixed(4));
      raf = (Math.abs(tx - cx) > 0.001 || Math.abs(ty - cy) > 0.001) ? requestAnimationFrame(tick) : 0;
    };
    window.addEventListener("pointermove", onMove, { passive: true });
    return () => { window.removeEventListener("pointermove", onMove); if (raf) cancelAnimationFrame(raf); };
  }, []);
  return (
    <div ref={ref} aria-hidden style={{ position: "absolute", inset: 0, zIndex: 1, "--px": 0, "--py": 0, pointerEvents: "none" }}>
      {fragments.map((fr, i) => (
        <div key={i} style={{ position: "absolute", left: fr.x, top: fr.y,
          transform: `translate(calc(var(--px) * ${fr.d}px), calc(var(--py) * ${fr.d}px))`, willChange: "transform" }}>
          <div style={{ animation: `drift${i % 4} ${7 + (i % 5)}s ease-in-out ${i * 0.4}s infinite`, opacity: .92 }}>
            {fr.el}
          </div>
        </div>
      ))}
    </div>
  );
}

function CyclingWord({ words }) {
  const [i, setI] = useState(0);
  useEffect(() => { setI(0); const t = setInterval(() => setI(v => (v + 1) % words.length), 2200); return () => clearInterval(t); }, [words]);
  // All words share one grid cell, so the pill reserves the width of the LONGEST word
  // and never resizes as the active word changes — the line stays centered.
  return (
    <span style={{ display: "inline-grid", placeItems: "center", padding: "2px 16px", borderRadius: 999, border: "1px solid var(--line-2)", color: "var(--ink)", verticalAlign: "middle" }}>
      {words.map((w, idx) => (
        <span key={idx} aria-hidden={idx !== i}
          style={{ gridArea: "1 / 1", whiteSpace: "nowrap", pointerEvents: "none",
            opacity: idx === i ? 1 : 0,
            transform: idx === i ? "none" : "translateY(8px)",
            transition: "opacity .5s var(--ease), transform .5s var(--ease)" }}>{w}</span>
      ))}
    </span>
  );
}

function Wordmark({ text }) {
  const parts = String(text).trim().split(" ");
  const last = parts.pop();
  return (
    <React.Fragment>{parts.join(" ")} <span style={{ color: "var(--primary)" }}>{last}</span></React.Fragment>
  );
}

function Hero() {
  const { L } = useT();
  return (
    <section id="top" className="dotted" style={{ position: "relative", minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden", paddingTop: 80, paddingBottom: 80 }}>
      {/* ambient wash */}
      <div aria-hidden style={{ position: "absolute", inset: 0, zIndex: 0,
        background: "radial-gradient(60% 50% at 50% 46%, rgba(29,78,216,.10), transparent 70%)" }}></div>
      <FloatingField />
      {/* center vignette so the wordmark reads above the fragments (stronger + blurred on mobile) */}
      <div className="hero-veil" aria-hidden style={{ position: "absolute", inset: 0, zIndex: 2, pointerEvents: "none",
        background: "radial-gradient(54% 46% at 50% 49%, var(--bg) 36%, rgba(252,252,253,.55) 66%, transparent 86%)" }}></div>

      <div className="wrap" style={{ position: "relative", zIndex: 3, textAlign: "center" }}>
        <div style={{ display: "inline-flex" }}>
          <span className="kicker" style={{ marginBottom: 30, background: "var(--glass)", backdropFilter: "blur(10px)", padding: "8px 16px", borderRadius: 999, boxShadow: "var(--shadow-sm)" }}>{L.hero.badge}</span>
        </div>

        <h1 className="h-display" style={{ marginBottom: 26, fontSize: "clamp(40px,6.6vw,96px)", maxWidth: 14 + "ch", marginLeft: "auto", marginRight: "auto" }}>
          <Wordmark text={L.hero.wordmark} />
        </h1>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", flexWrap: "wrap", gap: 12, fontSize: "clamp(18px,2vw,26px)", color: "var(--ink-2)", fontWeight: 500, marginBottom: 40 }}>
          <span>{L.hero.taglinePre}</span>
          <CyclingWord words={L.hero.words} />
        </div>

        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <a href="#demo" className="btn btn-lg" style={{ background: "var(--sky-2)", color: "var(--primary-ink)" }}>{L.hero.primary} <Icon.arrow className="btn-arrow" /></a>
          <a href="#product" className="btn btn-ghost btn-lg">{L.hero.secondary}</a>
        </div>
      </div>

      {/* scroll cue */}
      <a href="#why" style={{ position: "absolute", bottom: 30, right: 36, zIndex: 4, display: "flex", alignItems: "center", gap: 12, color: "var(--ink-3)", fontSize: 13 }} className="scroll-cue">
        <span>{L.hero.scroll}</span>
        <span style={{ width: 34, height: 34, borderRadius: 999, border: "1px solid var(--line-2)", display: "grid", placeItems: "center" }}>
          <span style={{ display: "block", width: 7, height: 7, borderRadius: 999, background: "var(--ink-2)", animation: "scrollPulse 1.8s var(--ease) infinite" }}></span>
        </span>
      </a>

      <style>{`
        @keyframes wordIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
        @keyframes scrollPulse { 0%,100%{ transform: translateY(-5px); opacity:.4; } 50%{ transform: translateY(5px); opacity:1; } }
        @keyframes drift0 { 0%,100%{ transform: translateY(0); } 50%{ transform: translateY(-14px); } }
        @keyframes drift1 { 0%,100%{ transform: translateY(0); } 50%{ transform: translateY(12px); } }
        @keyframes drift2 { 0%,100%{ transform: translate(0,0); } 50%{ transform: translate(8px,-10px); } }
        @keyframes drift3 { 0%,100%{ transform: translate(0,0); } 50%{ transform: translate(-9px,9px); } }
        @media (max-width: 720px){ .scroll-cue{ display:none !important; }
          #top [aria-hidden] > div > div { transform: scale(.82); }
          .hero-veil{
            background: radial-gradient(78% 52% at 50% 49%, var(--bg) 46%, rgba(252,252,253,.55) 72%, transparent 92%) !important;
            -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px);
            -webkit-mask-image: radial-gradient(82% 56% at 50% 49%, #000 52%, transparent 94%);
            mask-image: radial-gradient(82% 56% at 50% 49%, #000 52%, transparent 94%);
          }
        }
        @media (prefers-reduced-motion: reduce){ #top [style*="animation"]{ animation: none !important; } }
      `}</style>
    </section>
  );
}

Object.assign(window, { LangSwitch, Nav, Hero });
