'use client'

import Link from 'next/link'
import { signOut } from '@/app/(auth)/actions'
import { surfacesFor } from '@/lib/domain/moderator-access'
import { ADMIN_WORKSPACES, ROLE_LABELS, type UserContext } from '@/lib/domain/modes'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

/**
 * Account dropdown in the app header: profile, settings, alerts, support, sign out.
 * The moderator section lists only the pages this person may open — every page
 * for the admin, the granted ones for a moderator, none for a customer
 * (Nash, 2026-09-23).
 */
export function UserMenu({ name, role, surfaces, modes, activeKey }: {
  name: string
  role: string
  surfaces?: string[]
  /** Every mode this person may switch into (2026-09-24). */
  modes?: UserContext[]
  activeKey?: string | null
}) {
  const pages = surfacesFor({ role, surfaces })
  const switchable = modes ?? []
  const current = switchable.find((m) => m.key === activeKey) ?? null
  const initials = name
    .split(/\s+/)
    .map((w) => w[0])
    .slice(0, 2)
    .join('')
    .toUpperCase()

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          className="grid h-8 w-8 place-items-center rounded-full bg-[#0f1b2d] text-xs font-bold text-[#f5a623] transition hover:opacity-90"
          title="Account menu"
        >
          {initials || 'U'}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        <DropdownMenuLabel>
          <p className="truncate text-sm font-semibold">{name}</p>
          <p className="text-xs font-normal capitalize text-neutral-500">{role}</p>
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild><Link href="/profile">Profile</Link></DropdownMenuItem>
        {(switchable.length > 0 || role === 'admin') && <DropdownMenuItem asChild><Link href="/settings/roles">Roles &amp; Workspaces</Link></DropdownMenuItem>}
        <DropdownMenuItem asChild><Link href="/settings">Settings</Link></DropdownMenuItem>
        <DropdownMenuItem asChild><Link href="/settings/auto-participants">Auto-Participants</Link></DropdownMenuItem>
        {(role === 'broker' || role === 'dispatcher') && (
          <DropdownMenuItem asChild><Link href="/company">Company</Link></DropdownMenuItem>
        )}
        <DropdownMenuItem asChild><Link href="/alerts">Alerts</Link></DropdownMenuItem>
        <DropdownMenuItem asChild><Link href="/billing">Billing &amp; Wallet</Link></DropdownMenuItem>
        <DropdownMenuItem asChild><Link href="/support">Support</Link></DropdownMenuItem>
        {/* Switch Mode (Nash, 2026-09-24): the whole interface changes, so the
            menu names the mode the person is in and every mode they may enter. */}
        {switchable.length > 1 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuLabel className="text-[11px] font-normal text-neutral-400">Switch Mode</DropdownMenuLabel>
            {switchable.map((m) => (
              <DropdownMenuItem key={m.key} asChild>
                <Link href={`/api/modes/open?key=${encodeURIComponent(m.key)}`}>
                  {m.key === current?.key ? '✓ ' : ''}{ROLE_LABELS[m.roleType]} — {m.companyName ?? 'Independent'}
                </Link>
              </DropdownMenuItem>
            ))}
          </>
        )}
        {role === 'admin' && (
          <>
            {/* Admin's Switch Mode (Nash, 2026-09-24, §14): every supported
                interface, product views clearly marked as previews. The access
                comes from the platform role, so nothing here is a membership. */}
            <DropdownMenuSeparator />
            <DropdownMenuLabel className="text-[11px] font-normal text-neutral-400">Switch Mode</DropdownMenuLabel>
            {ADMIN_WORKSPACES.map((w) => (
              <DropdownMenuItem key={w.key} asChild>
                <Link href={`/api/modes/preview?workspace=${encodeURIComponent(w.key)}`}>
                  {w.label}{w.group === 'product' ? ' (preview)' : ''}
                </Link>
              </DropdownMenuItem>
            ))}
            <DropdownMenuItem asChild><Link href="/modes">Choose workspace…</Link></DropdownMenuItem>
          </>
        )}
        {pages.length > 0 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuLabel className="text-[11px] font-normal text-neutral-400">{role === 'admin' ? 'Admin' : 'Moderator'}</DropdownMenuLabel>
            {pages.map((p) => (
              <DropdownMenuItem key={p.key} asChild><Link href={p.path}>{p.label}</Link></DropdownMenuItem>
            ))}
            {role === 'admin' && <DropdownMenuItem asChild><Link href="/signup/pilot">Pilot Signup (preview)</Link></DropdownMenuItem>}
          </>
        )}
        <DropdownMenuSeparator />
        <form action={signOut}>
          <DropdownMenuItem asChild>
            <Button variant="ghost" size="sm" type="submit" className="w-full justify-start px-2 font-normal">
              Sign out
            </Button>
          </DropdownMenuItem>
        </form>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
