// Top bar + sub-bar + router context shared across screens

const RouterCtx = React.createContext(null);
const useRouter = () => React.useContext(RouterCtx);

const TopBar = () => {
  const { route, go, openPalette, query } = useRouter();
  const tabs = [
    { id: 'home',     label: 'Recent',   match: ['home', 'search', 'session'] },
    { id: 'projects', label: 'Projects', match: ['projects', 'project'] },
    { id: 'stats',    label: 'Stats',    match: ['stats'] },
    { id: 'health',   label: 'Health',   match: ['health'] },
    { id: 'settings', label: 'Settings', match: ['settings'] },
  ];
  const ownerScope = route.ownerScope; // set by ProjectsScreen / HomeScreen when admin uses ?owner=
  return (
    <div className="topbar">
      <span className="brand" onClick={() => go({ name: 'home' })}>assistant-log</span>
      <span className="brand-sep">/</span>
      <span className="brand-host">scarlet</span>
      <div className="search" onClick={openPalette}>
        {query
          ? <span className="mono">"{query}"</span>
          : <span className="ghost">search turns, sessions, paths…</span>}
        <span className="kbd">⌘K</span>
      </div>
      <nav>
        {tabs.map(t => (
          <span key={t.id}
            className={'tab' + (t.match.includes(route.name) ? ' active' : '')}
            onClick={() => go({ name: t.id })}>{t.label}</span>
        ))}
      </nav>
      <span className="who" onClick={() => go({ name: 'settings' })} title={`signed in via ${ME.via}`}>
        <span className="who-dot" />
        <span className="mono">{ME.user}</span>
        {ME.isAdmin && <span className="who-admin">admin</span>}
        {ownerScope && ownerScope !== ME.user && (
          <span className="who-scope mono">viewing: {ownerScope === '*' ? 'all owners' : ownerScope}</span>
        )}
      </span>
    </div>
  );
};

Object.assign(window, { RouterCtx, useRouter, TopBar });
