import type { TripParticipant } from '@/types/db'

/**
 * Which role's experience to render.
 *
 * Pilot convenience (unchanged): any account may preview any role via `?view=`.
 * Shared by the dashboard and the trip page so the preview switcher keeps
 * working after a driver navigates into a trip.
 */
export type EffectiveRole = 'broker' | 'dispatcher' | 'driver'

export const VIEW_MAP: Record<string, EffectiveRole> = {
  broker: 'broker',
  carrier: 'dispatcher',
  dispatcher: 'dispatcher',
  driver: 'driver',
}

/**
 * Dashboard: no trip context, so the account role decides.
 *
 * `?view=` is INTERNAL-ONLY (Task 96, 2026-09-09) — it is the same "see
 * another role's screen" capability as the pilot bar, just addressed by URL,
 * and Nash: "if somebody logs in with a regular… any other type of account,
 * like a broker, driver, or carrier… he should not see this admin tools."
 * For a customer the parameter is ignored and their own role wins.
 */
export function dashboardRole(
  view: string | undefined,
  accountRole: string,
  internal = false,
): EffectiveRole {
  const override = internal ? VIEW_MAP[view ?? ''] : undefined
  return (
    override ??
    (accountRole === 'dispatcher' ? 'dispatcher' : accountRole === 'driver' ? 'driver' : 'broker')
  )
}

/**
 * Trip page: the person's role ON THIS TRIP wins over their account role — the
 * same account can be a dispatcher on one trip and a driver on another. An
 * explicit `?view=` always wins, so the pilot preview switcher still works.
 *
 * Nash, 2026-09-07: "on the driver page, when you click on the active trip…
 * he should open the driver view, right? The active trip driver view."
 */
export function isDriverOnTrip(
  view: string | undefined,
  participant: TripParticipant | null,
  accountRole: string,
  internal = false,
): boolean {
  // Internal only (Task 96) — see dashboardRole. A real driver needs no
  // override: their participant role already resolves to driver, so the
  // ?view=driver links inside the driver interface (Task 78) keep working.
  const override = internal ? VIEW_MAP[view ?? ''] : undefined
  if (override) return override === 'driver'
  if (participant) return participant.role === 'driver'
  return accountRole === 'driver'
}

/**
 * Pilot car design replicas (Phase 1, 2026-09-12) — `?view=pilot-dispatch`
 * and `?view=pilot-driver`. Internal only, like every other `?view=`; a
 * customer's own role wins and the parameter is ignored. Kept out of
 * `EffectiveRole` on purpose: no real account has these roles yet, so the
 * trip page and everything keyed on EffectiveRole stay untouched.
 */
export type PilotPreviewView = 'pilot-dispatch' | 'pilot-driver'

export function pilotPreviewView(view: string | undefined, internal = false): PilotPreviewView | null {
  if (!internal) return null
  return view === 'pilot-dispatch' || view === 'pilot-driver' ? view : null
}
