const Topbar = ({ route, navigate, cart, onCartToggle, cartOpen, onLoginOpen, cartBadgePulse, user, authReady, onLogout, currency, setCurrency }) => {
  const [curOpen, setCurOpen] = useState(false);
  const [userOpen, setUserOpen] = useState(false);
  const curRef = useRef(null);
  const userRef = useRef(null);
  useEffect(() => {
    if (!curOpen) return;
    const onDoc = (e) => { if (curRef.current && !curRef.current.contains(e.target)) setCurOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [curOpen]);
  useEffect(() => {
    if (!userOpen) return;
    const onDoc = (e) => { if (userRef.current && !userRef.current.contains(e.target)) setUserOpen(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [userOpen]);
  const curObj = getCurrency(currency);
  // Versioned key — bump the suffix the next time something new lands in Free
  // and the "new" badge will surface again for everyone who already dismissed
  // the previous one.
  const FREE_BADGE_KEY = "le_free_seen_v1";
  const [freeSeen, setFreeSeen] = useState(() => {
    try { return localStorage.getItem(FREE_BADGE_KEY) === "1"; } catch { return false; }
  });
  const navWithBadgeClear = (to) => {
    if (to === "free" && !freeSeen) {
      try { localStorage.setItem(FREE_BADGE_KEY, "1"); } catch {}
      setFreeSeen(true);
    }
    navigate(to);
  };
  const links = [
    { to: "home", label: "Home" },
    { to: "scripts", label: "Paid" },
    { to: "free", label: "Free", badge: !freeSeen ? "NEW" : null },
    { to: "about", label: "About" },
    { to: "terms", label: "Terms" },
  ];
  const count = cart.length;
  const cartRef = useRef(null);
  useEffect(() => {
    if (!cartOpen) return;
    const onDoc = (e) => {
      if (cartRef.current && !cartRef.current.contains(e.target)) onCartToggle(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [cartOpen]);

  return (
    <>
      <div className="strip">
        <div className="container">
          <div className="left">
            <span className="dot dot-accent" />
            <span>USED CAR DEALERSHIP IS LIVE · synced persistent open-world lots, fixed prices, auctions & raffles · create a dealer in minutes</span>
          </div>
          <a
            href="https://discord.gg/ey2sMahZ6t"
            target="_blank"
            rel="noreferrer noopener"
            style={{ color: "inherit", textDecoration: "none", transition: "color .15s" }}
            onMouseEnter={(e) => e.currentTarget.style.color = "var(--fg-1)"}
            onMouseLeave={(e) => e.currentTarget.style.color = "inherit"}
          >
            discord.gg/ey2sMahZ6t
          </a>
        </div>
      </div>
      <header className="topbar">
        <div className="container topbar-inner">
          <a href="/" onClick={(e) => { e.preventDefault(); navigate("home"); }} style={{ cursor: "pointer" }}>
            <Logo />
          </a>
          <nav className="nav">
            {links.map((l) => (
              <a
                key={l.to}
                href={routeHref(l.to)}
                onClick={(e) => { e.preventDefault(); navWithBadgeClear(l.to); }}
                className={
                  route.startsWith(l.to) ||
                  (l.to === "scripts" && route === "product") ||
                  (l.to === "free" && route === "free-product")
                    ? "active"
                    : ""
                }
                style={{ cursor: "pointer" }}
              >
                {l.label}
                {l.badge ? <span className="nav-badge">{l.badge}</span> : null}
              </a>
            ))}
          </nav>
          <div className="topbar-actions">
            <div className="cur-anchor" ref={curRef}>
              <button className="icon-btn cur-btn" onClick={() => setCurOpen((o) => !o)} title="Currency" aria-expanded={curOpen}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em" }}>{curObj.code}</span>
              </button>
              {curOpen ? (
                <div className="cur-menu surface">
                  <div className="cur-menu-head">Display currency</div>
                  {CURRENCIES.map((c) => (
                    <button
                      key={c.code}
                      className={`cur-item ${c.code === currency ? "active" : ""}`}
                      onClick={() => { setCurrency(c.code); setCurOpen(false); }}
                    >
                      <span className="cur-sym">{c.symbol}</span>
                      <span className="cur-code">{c.code}</span>
                      <span className="cur-label">{c.label}</span>
                    </button>
                  ))}
                  <div className="cur-menu-foot">Charged in USD at checkout · Tebex converts</div>
                </div>
              ) : null}
            </div>
            <button className="icon-btn" title="Search scripts" onClick={() => navigate("scripts")}>
              <Icon.Search />
            </button>
            <div className="cart-anchor" ref={cartRef}>
              <button className="icon-btn" onClick={() => onCartToggle(!cartOpen)} title="Cart" aria-expanded={cartOpen}>
                <Icon.Cart />
                {count > 0 ? (
                  <span className={`cart-badge ${cartBadgePulse ? "pulse" : ""}`}>{count}</span>
                ) : null}
              </button>
              {cartOpen ? <CartDropdown onClose={() => onCartToggle(false)} navigate={navigate} /> : null}
            </div>
            {user ? (
              <div className="cur-anchor" ref={userRef}>
                <button className="btn btn-ghost" onClick={() => setUserOpen((o) => !o)} title={`Signed in as ${user.name} via CFX.re`}>
                  <Icon.CfxMark size={16} /> {user.name}
                </button>
                {userOpen ? (
                  <div className="cur-menu surface" style={{ width: 240 }}>
                    <div className="cur-menu-head">Signed in</div>
                    <div style={{ padding: "6px 10px 10px", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-1)", borderBottom: "1px solid var(--line)", marginBottom: 6 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <Icon.CfxMark size={14} /> <span>{user.name}</span>
                        <Icon.Check size={12} style={{ color: "var(--accent)" }} />
                      </div>
                      {user.discord ? (
                        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6, color: "var(--fg-2)" }}>
                          <Icon.Discord size={14} /> <span>{user.discord.name}</span>
                          <Icon.Check size={12} style={{ color: "var(--accent)" }} />
                        </div>
                      ) : null}
                    </div>
                    {!user.discord ? (
                      <button className="cur-item" style={{ gridTemplateColumns: "18px 1fr" }} onClick={() => { setUserOpen(false); onLoginOpen(); }}>
                        <Icon.Discord size={14} />
                        <span className="cur-label" style={{ color: "var(--fg-1)" }}>Link Discord</span>
                      </button>
                    ) : null}
                    <button className="cur-item" style={{ gridTemplateColumns: "18px 1fr" }} onClick={() => { setUserOpen(false); onLogout(); }}>
                      <Icon.X size={14} />
                      <span className="cur-label" style={{ color: "var(--fg-1)" }}>Log out</span>
                    </button>
                  </div>
                ) : null}
              </div>
            ) : !authReady ? (
              // Auth not resolved yet — reserve the exact "Log in" footprint
              // (visibility:hidden) so a signed-in visitor never sees a "Log in"
              // flash before /api/session returns, and the header doesn't shift.
              <button className="btn" disabled aria-hidden="true" tabIndex={-1} style={{ visibility: "hidden" }}>
                <Icon.User size={15} /> Log in
              </button>
            ) : (
              <button className="btn" onClick={onLoginOpen}>
                <Icon.User size={15} /> Log in
              </button>
            )}
          </div>
        </div>
      </header>
    </>
  );
};

Object.assign(window, { Topbar });
