import { getSessionUser } from '@/lib/auth'
import { isRoleSwitchEnabled, ROLE_SWITCH_LABELS } from '@/lib/auth/env-users'
import { RoleSwitcherBar, type RoleSwitcherItem } from './role-switcher-bar'

/**
 * Pilot testing bar (AUTH_ROLE_SWITCH=true): quick navigation to every
 * role's dashboard from the top of every page — while staying signed in as
 * yourself.
 *
 * INTERNAL ONLY (Task 96, 2026-09-09). Nash: "for pilot testing, we have like
 * a small bar pilot testing bar. That one should be visible only for admin and
 * developer roles. No other users should see it."
 *
 * Every item is a plain link (2026-09-17, fixing Nash: "when I jump between
 * dashboards, the system is changing my user role… I need to stay as an
 * admin on each dashboard"). It used to switch the REAL session into a
 * configured test account (Test_Dispatcher, Test_Driver…) for a role that had
 * one, which silently changed the signed-in role — that IS what "the system
 * is changing my role" was. No switch is needed: `requireRoleRoute` already
 * lets an internal admin open any role's pages directly while staying
 * themselves (`mayOpenContext` in `src/lib/page-context.ts`), and an admin's
 * own visibility rules (`canSeeAllTrips`) apply the same on every dashboard.
 *
 * The highlight follows the page you are on (Nash, 2026-09-13) — see
 * RoleSwitcherBar.
 */
export async function RoleSwitcher({ currentRole }: { currentRole: string }) {
  const user = await getSessionUser()
  if (!user?.internal) return null
  if (!isRoleSwitchEnabled()) return null

  const groups = [
    { title: 'Freight Broker', items: [link('Broker dashboard', '/fb-dashboard', ['/fb-dashboard', '/fb-trip-workspace'])] },
    {
      title: 'Carrier',
      items: [
        link('Carrier dashboard', '/cd-dashboard', ['/cd-dashboard', '/cd-trip-workspace']),
        link('Driver app', '/ct-dashboard', ['/ct-dashboard', '/ct-trip-workspace']),
      ],
    },
    {
      title: 'Pilot Car',
      items: [
        link('Signup', '/signup/pilot', ['/signup/pilot']),
        link('Pilot dispatch dashboard', '/pd-dashboard', ['/pd-dashboard', '/pd-trip-workspace']),
        link('Pilot driver app', '/pc-dashboard', ['/pc-dashboard', '/pc-trip-workspace']),
        link('My Pilot tab · carrier', '/admin/pilot-preview/HH-2041?as=carrier', ['/admin/pilot-preview']),
      ],
    },
    { title: 'Admin', items: [link(ROLE_SWITCH_LABELS.admin, '/admin/users', ['/admin/users', '/admin/moderation', '/admin/email-templates', '/admin/company-review'])] },
  ]

  return <RoleSwitcherBar groups={groups} currentRole={currentRole} />
}

function link(label: string, href: string, activeOn: string[]): RoleSwitcherItem {
  return { kind: 'link', href, label, activeOn }
}
