// TopBar — brand + workspace + per-platform credit balances + user.

window.TopBar = function TopBar({ onOpenTweaks, credits, user, pendingAccessCount, onOpenAccessRequests, onLogout }) {
  const c = credits || {};
  const label = user?.email || user?.username || user?.user_id || '';
  const initials = (label || 'RS')
    .split(/[^a-zA-Z0-9]+/)
    .filter(Boolean)
    .slice(0, 2)
    .map(part => part[0])
    .join('')
    .toUpperCase() || 'RS';
  // Only surface platforms whose balance is known. Backend-less platforms
  // stay out of the bar until their credit feed lands.
  const chips = Object.entries(PLATFORMS)
    .map(([key, p]) => [key, p, c[key]])
    .filter(([, , bal]) => typeof bal === "number");
  return (
    <header className="topbar">
      <div className="topbar-left">
        <img src="../../assets/mark.svg" alt="" className="topbar-mark" />
        <span className="topbar-brand">Resilia</span>
      </div>
      <div className="topbar-center">
        <div className="topbar-search">
          <Icon name="search" size={14} />
          <input placeholder="Jump to brand, ad ID, or script…" />
          <kbd>⌘K</kbd>
        </div>
      </div>
      <div className="topbar-right">
        {user?.is_admin && pendingAccessCount > 0 && (
          <button className="admin-pending-badge" onClick={onOpenAccessRequests} title="Pending access requests">
            <span className="admin-pending-dot" />
            {pendingAccessCount} pending access requests
          </button>
        )}
        {chips.length > 0 && (
          <div className="topbar-credits" aria-label="Platform credit balances">
            {chips.map(([key, p, bal]) => (
              <span
                key={key}
                className="credit-chip"
                title={`${p.label} credits remaining`}
                style={{ background: p.bg, color: p.color, borderColor: p.bg }}
              >
                <span className="credit-chip-dot" style={{ background: p.color }} />
                {p.label}
                <span className="credit-chip-value">{bal.toLocaleString()}</span>
              </span>
            ))}
          </div>
        )}
        <button className="icon-btn" title="Settings">
          <Icon name="settings" size={16} />
        </button>
        <div className="topbar-user" title={label}>
          <div className="avatar">{initials}</div>
          {label && <span className="topbar-user-label">{label}</span>}
        </div>
        <button className="icon-btn" title="Sign out" onClick={onLogout}>
          <Icon name="logOut" size={16} />
        </button>
      </div>
    </header>
  );
};
