// ============================================================================
// public/shell/topbar.jsx — Top bar with title, search, theme toggle, profile
// ----------------------------------------------------------------------------
// Title + subtitle come from ROUTE_META in app.jsx.
// Profile pill shows: user name, plan badge (or "Super Admin" for admin view).
// ============================================================================

function TopBar({ meta, view, theme, onToggleTheme, onMenu, session, subscription }) {
  const user   = session?.user;
  const tenant = session?.tenant;
  const planName = subscription?.planName || (tenant?.status === "trial" ? "Trial" : "Free");

  return (
    <div className="topbar">

      {/* Mobile menu trigger */}
      <button className="topbar-icon-btn mobile-only menu-btn" onClick={onMenu} title="Menu">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <line x1="3" y1="6"  x2="21" y2="6" />
          <line x1="3" y1="12" x2="21" y2="12"/>
          <line x1="3" y1="18" x2="21" y2="18"/>
        </svg>
      </button>

      <div className="topbar-title">
        <h1>{meta.title}</h1>
        {meta.subtitle && <small className="desktop-only">{meta.subtitle}</small>}
      </div>
      <div className="topbar-spacer"/>

      {/* Desktop global search */}
      <div className="search-box desktop-only">
        <I.search size={14}/>
        <input placeholder="Search calls, contacts, agents…"/>
        <span className="kbd">⌘ K</span>
      </div>

      {/* Mobile search icon */}
      <button className="topbar-icon-btn mobile-only" title="Search">
        <I.search size={16}/>
      </button>

      {/* Theme toggle */}
      <button
        className="topbar-icon-btn theme-toggle"
        title={`Switch to ${theme === "dark" ? "light" : "dark"} mode`}
        onClick={onToggleTheme}
      >
        {theme === "dark" ? <I.sun size={16}/> : <I.moon size={16}/>}
      </button>

      {/* Notifications */}
      <button className="topbar-icon-btn" title="Notifications">
        <I.bell size={16}/>
        <span className="dot"/>
      </button>

      {/* Profile pill */}
      <div className="profile-pill">
        <Avatar name={user?.name || tenant?.name || "?"} size={30}/>
        <div className="desktop-only">
          <div className="name">{user?.name || "—"}</div>
          <div className="email">{view === "admin" ? "Super Admin" : `${planName} plan`}</div>
        </div>
        <I.chevD size={14} className="desktop-only"/>
      </div>
    </div>
  );
}

window.TopBar = TopBar;
