'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { switchRole } from '@/app/(auth)/actions'

export type RoleSwitcherItem =
  | { kind: 'switch'; role: string; label: string; activeOn: string[] }
  | { kind: 'link'; href: string; label: string; activeOn: string[]; hint?: string }

export interface RoleSwitcherGroup {
  title: string
  items: RoleSwitcherItem[]
}

/**
 * The pilot testing bar's rendering. Highlight follows the PAGE you are on
 * (Nash, 2026-09-13: "if I click on the broker dashboard, it should highlight
 * it, and then I can click on the carrier dashboard, and it will highlight
 * it") — the item whose route prefix matches the current path best. When no
 * item matches (Billing, Settings…), the real session role's switch stays lit.
 */
/** The one item to light up for this path: longest matching route prefix; else the session role's switch. */
export function pickActiveItem(items: RoleSwitcherItem[], pathname: string, currentRole: string): RoleSwitcherItem | null {
  let best: RoleSwitcherItem | null = null
  let bestLen = 0
  for (const item of items) {
    for (const prefix of item.activeOn) {
      if ((pathname === prefix || pathname.startsWith(`${prefix}/`)) && prefix.length > bestLen) {
        best = item
        bestLen = prefix.length
      }
    }
  }
  return best ?? items.find((i) => i.kind === 'switch' && i.role === currentRole) ?? null
}

export function RoleSwitcherBar({ groups, currentRole }: { groups: RoleSwitcherGroup[]; currentRole: string }) {
  const pathname = usePathname() ?? ''
  const active = pickActiveItem(groups.flatMap((g) => g.items), pathname, currentRole)
  const isActive = (item: RoleSwitcherItem) => item === active

  const pill = (active: boolean) =>
    `mx-0.5 rounded-full px-3 py-1 font-semibold transition ${
      active ? 'bg-[#f5a623] text-[#0f1b2d]' : 'text-neutral-300 hover:bg-white/10 hover:text-white'
    }`

  return (
    <div className="border-b bg-[#0f1b2d] px-4 py-2 text-center text-xs text-white">
      <span className="mr-2 font-semibold text-[#f5a623]">Pilot testing:</span>
      {groups.map((g, gi) => (
        <span key={g.title} className={`inline-flex flex-wrap items-center ${gi > 0 ? 'ml-3 border-l border-white/20 pl-3' : ''}`}>
          <span className="mr-1 font-semibold text-neutral-400">{g.title}</span>
          {g.items.map((item) =>
            item.kind === 'switch' ? (
              <form key={item.label} action={switchRole} className="inline">
                <input type="hidden" name="role" value={item.role} />
                <button type="submit" className={pill(isActive(item))} aria-current={isActive(item) ? 'page' : undefined}>
                  {item.label}
                </button>
              </form>
            ) : (
              <Link key={item.label} href={item.href} title={item.hint} className={pill(isActive(item))} aria-current={isActive(item) ? 'page' : undefined}>
                {item.label}
              </Link>
            ),
          )}
        </span>
      ))}
    </div>
  )
}
