// Top header + nav

const headerStyles = `
  .hdr {
    position: sticky; top: 0; z-index: 40;
    background: color-mix(in oklab, var(--bg) 85%, transparent);
    backdrop-filter: saturate(1.2) blur(10px);
    -webkit-backdrop-filter: saturate(1.2) blur(10px);
    border-bottom: 1px solid var(--line);
    height: var(--header-h);
  }
  .hdr-inner {
    display: grid;
    grid-template-columns: var(--rail-w) minmax(0, 1fr) auto;
    height: 100%;
    align-items: center;
    padding: 0 18px 0 22px;
    gap: 24px;
  }
  .hdr-inner > * { min-width: 0; }
  .brand {
    display: flex; align-items: center; gap: 10px;
  }
  .brand-mark {
    width: 24px; height: 24px;
    border-radius: 6px;
    background: var(--ink);
    color: var(--bg);
    display: inline-flex; align-items: center; justify-content: center;
    font-family: var(--font-serif);
    font-size: 16px;
    font-weight: 500;
    letter-spacing: -0.02em;
  }
  .brand-name {
    font-family: var(--font-serif);
    font-size: 22px;
    letter-spacing: -0.01em;
    color: var(--ink);
    line-height: 1;
  }
  .brand-name em {
    font-style: italic;
    color: var(--accent-deep);
  }
  .brand-tag {
    font-size: 10.5px;
    color: var(--muted);
    font-feature-settings: "tnum";
    margin-top: 2px;
    letter-spacing: 0.02em;
  }

  .nav {
    display: flex; align-items: center; gap: 2px;
  }
  .nav a {
    font-size: 13px;
    font-weight: 500;
    color: var(--muted);
    padding: 6px 10px;
    border-radius: var(--r-sm);
    text-decoration: none;
    display: inline-flex; align-items: center; gap: 6px;
    cursor: pointer;
    transition: all .12s;
  }
  .nav a:hover { color: var(--ink); background: var(--bg-soft); }
  .nav a.active { color: var(--ink); background: var(--bg-soft); }
  .nav a .num { color: var(--muted-2); font-family: var(--font-mono); font-size: 11px; margin-left: 2px; }

  .hdr-search {
    position: relative;
    max-width: 520px;
    width: 100%;
    margin: 0 auto;
  }
  .hdr-search .input {
    height: 34px;
    padding-left: 34px;
    padding-right: 64px;
    background: var(--bg-soft);
    border-color: transparent;
  }
  .hdr-search .input:focus {
    background: var(--surface);
  }
  .hdr-search .s-ico {
    position: absolute; left: 11px; top: 50%;
    transform: translateY(-50%);
    color: var(--muted);
    pointer-events: none;
  }
  .hdr-search .kbd-wrap {
    position: absolute; right: 8px; top: 50%;
    transform: translateY(-50%);
    display: flex; gap: 3px;
  }
  .hdr-search .search-clear {
    position: absolute; right: 8px; top: 50%;
    transform: translateY(-50%);
    width: 22px; height: 22px;
  }
  .hdr-search.has-clear .input { padding-right: 38px; }

  .hdr-right {
    display: flex; align-items: center; gap: 10px;
  }

  .status-pill {
    display: inline-flex; align-items: center; gap: 6px;
    height: 28px; padding: 0 10px 0 9px;
    border-radius: 14px;
    background: var(--live-soft);
    color: var(--live);
    font-size: 11.5px;
    font-weight: 600;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    border: 1px solid rgba(47,143,94,0.2);
  }
  .status-dot {
    width: 7px; height: 7px; border-radius: 50%;
    background: var(--live);
    animation: live-pulse 1.8s ease-out infinite;
  }
  .status-pill.off { background: var(--bg-sunken); color: var(--muted); border-color: var(--line); }
  .status-pill.off .status-dot { background: var(--faint); animation: none; }

  /* gold spot widget */
  .spot {
    display: inline-flex; align-items: center; gap: 8px;
    height: 30px; padding: 0 10px;
    border-radius: var(--r-sm);
    border: 1px solid var(--line);
    background: var(--surface);
  }
  .spot .spot-ic {
    width: 18px; height: 18px; border-radius: 4px;
    background: var(--accent); color: #fff;
    display: inline-flex; align-items: center; justify-content: center;
    font-family: var(--font-serif); font-size: 12px;
  }
  .spot .spot-val { font-family: var(--font-mono); font-size: 12.5px; font-weight: 600; color: var(--ink); font-feature-settings: "tnum"; }
  .spot .spot-unit { font-size: 10px; color: var(--muted); }
  .spot .spot-src {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: 9.5px; letter-spacing: 0.04em; text-transform: uppercase; font-weight: 600;
    padding-left: 8px; border-left: 1px solid var(--line);
  }
  .spot .spot-src .sd { width: 5px; height: 5px; border-radius: 50%; }
  .spot.live .spot-src { color: var(--live); }
  .spot.live .spot-src .sd { background: var(--live); animation: live-pulse 2.2s ease-out infinite; }
  .spot.stale_cache .spot-src { color: var(--accent-deep); }
  .spot.stale_cache .spot-src .sd { background: var(--accent); }
  .spot.fallback .spot-src { color: var(--hot); }
  .spot.fallback .spot-src .sd { background: var(--hot); }

  .signin-btn {
    display: inline-flex; align-items: center; gap: 6px;
    height: 30px; padding: 0 14px;
    border-radius: var(--r-sm);
    background: var(--ink); color: var(--bg);
    border: 1px solid var(--ink);
    font-size: 13px; font-weight: 600; cursor: pointer;
    transition: background .12s;
  }
  .signin-btn:hover { background: var(--ink-2); }

  .avatar {
    width: 28px; height: 28px;
    border-radius: 50%;
    background: var(--accent);
    color: #fff;
    display: inline-flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 600;
    font-family: var(--font-mono);
    border: 1px solid var(--accent-deep);
  }

  .sep { width: 1px; height: 20px; background: var(--line); }

  /* ticker */
  .ticker-wrap {
    border-bottom: 1px solid var(--line);
    background: var(--bg-soft);
    overflow: hidden;
    height: 28px;
    display: flex;
    align-items: center;
  }
  .ticker-label {
    padding: 0 14px;
    font-size: 10.5px;
    font-weight: 600;
    letter-spacing: 0.12em;
    text-transform: uppercase;
    color: var(--muted);
    border-right: 1px solid var(--line);
    height: 100%;
    display: flex; align-items: center;
    flex: none;
  }
  .ticker-track {
    display: flex;
    gap: 28px;
    white-space: nowrap;
    animation: ticker 60s linear infinite;
    padding-left: 28px;
    font-family: var(--font-mono);
    font-size: 11.5px;
    color: var(--muted);
  }
  .ticker-track:hover { animation-play-state: paused; }
  .ticker-track .up { color: var(--live); }
  .ticker-track .dn { color: var(--hot); }
  .ticker-track b { color: var(--ink-2); font-weight: 500; }
`;

if (!document.getElementById("hdr-styles")) {
  const s = document.createElement("style");
  s.id = "hdr-styles";
  s.textContent = headerStyles;
  document.head.appendChild(s);
}

const GoldSpot = ({ spot }) => {
  const srcLabel = { live: "Live", stale_cache: "Cached", fallback: "Fallback" }[spot.source] || spot.source;
  const age = spot.ageSeconds < 60 ? `${spot.ageSeconds}s` : `${Math.round(spot.ageSeconds/60)}m`;
  return (
    <div className={`spot ${spot.source}`} title={`Gold spot · ${srcLabel} · ${age} old · ${spot.isAuthoritative ? "authoritative" : "non-authoritative"}. All valuations depend on this price.`}>
      <span className="spot-ic">Au</span>
      <div style={{display:"flex", flexDirection:"column", lineHeight:1.05}}>
        <span className="spot-val">${spot.pricePerGram.toFixed(2)}<span className="spot-unit">/g</span></span>
      </div>
      <span className="spot-src"><span className="sd"/>{srcLabel} · {age}</span>
    </div>
  );
};

const Header = ({
  liveOn,
  active,
  setActive,
  onOpenTweaks,
  signedIn,
  onComingSoon,
  spot,
  counts,
  searchTerm,
  onSearch,
  onClearSearch,
  searching,
}) => {
  const [q, setQ] = React.useState(searchTerm || "");
  React.useEffect(() => { setQ(searchTerm || ""); }, [searchTerm]);
  const submitSearch = (e) => {
    e.preventDefault();
    onSearch?.(q);
  };
  const clear = () => {
    setQ("");
    onClearSearch?.();
  };
  const nav = [
    { k: "deals", label: "Deals" },
    { k: "browse", label: "Browse" },
    { k: "alerts", label: "Alerts", num: signedIn ? String(counts.alerts) : null, gated: true },
    { k: "saved", label: "Saved", gated: true },
    { k: "live", label: "Live", gated: true },
  ];
  return (
    <header className="hdr">
      <div className="hdr-inner">
        <div className="brand">
          <div className="brand-mark">K</div>
          <div>
            <div className="brand-name">Karat<em>Scan</em></div>
            <div className="brand-tag mono">{window.__TWEAKS__.brandTagline}</div>
          </div>
        </div>

        <div style={{display:"flex", alignItems:"center", gap:"18px", justifyContent:"space-between"}}>
          <nav className="nav">
            {nav.map(n => (
              <a key={n.k} className={active === n.k ? "active" : ""} onClick={() => setActive(n.k)} title={n.gated ? "Coming soon" : ""}>
                {n.label}{n.num ? <span className="num">{n.num}</span> : null}
                {n.gated ? <span className="num" style={{opacity:0.6}}>soon</span> : null}
              </a>
            ))}
          </nav>
          <form className={`hdr-search ${q || searchTerm ? "has-clear" : ""}`} onSubmit={submitSearch}>
            <I.search size={14} className="s-ico"/>
            <input
              className="input"
              placeholder="Search title, item type, seller..."
              value={q}
              onChange={e => setQ(e.target.value)}
              aria-label="Search items"
            />
            {q || searchTerm ? (
              <button className="btn icon sm ghost search-clear" type="button" onClick={clear} title="Clear search"><I.x size={12}/></button>
            ) : (
              <span className="kbd-wrap"><span className="kbd">Enter</span></span>
            )}
          </form>
        </div>

        <div className="hdr-right">
          <GoldSpot spot={spot}/>
          <div className="sep"/>
          <button className="btn icon sm ghost" onClick={onOpenTweaks} title="Tweaks"><I.cog size={15}/></button>
          {signedIn ? (
            <>
              <button className="btn icon sm ghost" title="Notifications coming soon" onClick={() => onComingSoon?.("Notifications")}><I.bell size={15}/></button>
              <div className="avatar" onClick={() => onComingSoon?.("Account menu")} title="Account menu coming soon" style={{cursor:"pointer"}}>MK</div>
            </>
          ) : (
            <button className="signin-btn" onClick={() => onComingSoon?.("Sign in", "Accounts and magic-link sign-in are deferred for the public MVP.")}><I.bolt size={13}/> Sign in</button>
          )}
        </div>
      </div>
    </header>
  );
};

const Ticker = () => {
  const items = [
    { sym: "Gold spot", val: "$77.42/g", d: "+0.42%", up: true },
    { sym: "XAU/oz", val: "$2,408.30", d: "+0.42%", up: true },
    { sym: "Analyzed 24h", val: "41,206", d: "+8.1%", up: true },
    { sym: "New offers 1h", val: "23", d: "+6", up: true },
    { sym: "Median ratio", val: "0.94×", d: "−0.02", up: false },
    { sym: "Avg confidence", val: "high", d: "steady", up: null },
    { sym: "Needs-weight pool", val: "312 items", d: "dig", up: null },
    { sym: "Refresh", val: "45s", d: "polling", up: null },
  ];
  const row = (
    <>
      {items.map((it, i) => (
        <span key={i}>
          <span style={{color:"var(--muted-2)"}}>{it.sym}</span>{" "}
          <b>{it.val}</b>{" "}
          {it.d !== "—" ? <span className={it.up === true ? "up" : it.up === false ? "dn" : ""}>{it.up === true ? "▲" : it.up === false ? "▼" : "·"} {it.d}</span> : null}
        </span>
      ))}
    </>
  );
  return (
    <div className="ticker-wrap">
      <div className="ticker-label">Market</div>
      <div className="ticker-track">{row}{row}</div>
    </div>
  );
};

Object.assign(window, { Header, Ticker, GoldSpot });
