import type { TripParticipant } from '@/types/db'
import { VIEW_MAP } from '@/lib/role-view'

/**
 * Role-specific page context (article "Snapshot and Role-Specific Page
 * Separation", 2026-09-13; route scheme chosen by Nash the same day —
 * "they really like to be called freight brokers… FB instead of BD").
 *
 * Five page groups, each with its own dashboard and trip/assignment view,
 * addressed by a role abbreviation — "user role abbreviation dash… all in one
 * link", no nested role sub-trees:
 *
 *   FB freight broker              /fb-dashboard   /fb-trip-workspace/<trip number>
 *   CD carrier dispatch    /cd-dashboard   /cd-trip-workspace/<trip number>
 *   PD pilot dispatch      /pd-dashboard   /pd-trip-workspace/<trip number>
 *   CT carrier truck driver/ct-dashboard   /ct-trip-workspace/<trip number>
 *   PC pilot car driver    /pc-dashboard   /pc-trip-workspace/<trip number>
 *
 * The trip number is `trips.ref_code` (unique). `/dashboard` and `/trips/<id>`
 * remain as redirects into the signed-in role's environment so old links and
 * emails keep working. Cross-role jumps exist only for internal admins
 * (`?view=` and the pilot testing bar) — "unless it is an intentional
 * admin/developer testing action".
 *
 * The backend resolves the context (article §6); every role route reads it
 * and applies that role's data, actions and navigation.
 */
export type PageContext = 'broker' | 'carrier' | 'pilot-company' | 'carrier-driver' | 'pilot-driver'

export const ROLE_ABBR: Record<PageContext, 'fb' | 'cd' | 'pd' | 'ct' | 'pc'> = {
  broker: 'fb',
  carrier: 'cd',
  'pilot-company': 'pd',
  'carrier-driver': 'ct',
  'pilot-driver': 'pc',
}

export const PAGE_CONTEXT_LABELS: Record<PageContext, string> = {
  broker: 'Freight broker',
  carrier: 'Carrier dispatch',
  'pilot-company': 'Pilot dispatch',
  'carrier-driver': 'Carrier driver',
  'pilot-driver': 'Pilot driver',
}

export function dashboardPath(ctx: PageContext): string {
  return `/${ROLE_ABBR[ctx]}-dashboard`
}

export function tripPath(ctx: PageContext, tripNumber: string): string {
  return `/${ROLE_ABBR[ctx]}-trip-workspace/${encodeURIComponent(tripNumber)}`
}

/** The context a role route belongs to, from its abbreviation. */
export function contextForAbbr(abbr: string): PageContext | null {
  const entry = (Object.entries(ROLE_ABBR) as [PageContext, string][]).find(([, a]) => a === abbr)
  return entry ? entry[0] : null
}

/**
 * Dashboard context from the ACCOUNT role. Internal admins may override with
 * `?view=` (broker | carrier | dispatcher | driver | pilot-dispatch |
 * pilot-driver); a customer's own role always wins. Admin accounts land on
 * the broker dashboard (platform-wide trip visibility), as before.
 */
export function contextForAccount(accountRole: string, view?: string, internal = false): PageContext {
  if (internal && view) {
    if (view === 'pilot-dispatch') return 'pilot-company'
    if (view === 'pilot-driver') return 'pilot-driver'
    const mapped = VIEW_MAP[view]
    if (mapped === 'broker') return 'broker'
    if (mapped === 'dispatcher') return 'carrier'
    if (mapped === 'driver') return 'carrier-driver'
  }
  if (accountRole === 'dispatcher') return 'carrier'
  if (accountRole === 'driver') return 'carrier-driver'
  return 'broker'
}

/**
 * Trip-view context: the person's role ON THIS TRIP wins over the account
 * role — the same account can be a dispatcher on one trip and a driver on
 * another (Nash, 2026-09-07). Broker participants get the broker trip view,
 * driver participants the carrier driver view; dispatcher, pilot and shipper
 * participants (and an admin who is not a participant) get the carrier
 * dispatch trip view — exactly what the shared workspace rendered for them
 * before the split. Pilot participants move to their own views when pilot
 * account roles exist (pilot task document, Phase 2).
 */
export function contextForTrip(
  participant: Pick<TripParticipant, 'role'> | null,
  accountRole: string,
  view?: string,
  internal = false,
): PageContext {
  if (internal && view) {
    const forced = contextForAccount(accountRole, view, true)
    if (forced !== contextForAccount(accountRole)) return forced
  }
  if (participant) {
    if (participant.role === 'driver') return 'carrier-driver'
    if (participant.role === 'broker') return 'broker'
    return 'carrier'
  }
  return contextForAccount(accountRole)
}

/**
 * May this account open a route of the given context? Their own context
 * always; internal admins any (testing). Pilot pages are Phase 1 replicas
 * on demo data — internal only until pilot account roles exist.
 */
export function mayOpenContext(routeCtx: PageContext, accountCtx: PageContext, internal: boolean): boolean {
  if (internal) return true
  if (routeCtx === 'pilot-company' || routeCtx === 'pilot-driver') return false
  return routeCtx === accountCtx
}
