/* UserMenu — top-bar dropdown anchored to the signed-in user.
 *
 * Shows the user's name, email, and role pill at the top, then offers
 * shortcuts to /settings and /settings/security, and a sign-out action
 * that bounces back to /auth/sign-in. */

'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useSession, signOut } from '@/lib/auth-client';
import { LogOut, User as UserIcon, ShieldCheck, Settings } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { StatusBadge } from '@/components/ui/status-badge';
import { Button } from '@/components/ui/button';

export function UserMenu() {
  const { data: session } = useSession();
  const router = useRouter();

  const user = session?.user as
    | { name?: string; email?: string; role?: string }
    | undefined;
  if (!user) return null;

  const initials = (user.name ?? user.email ?? '?')
    .split(/[\s@]/)
    .filter(Boolean)
    .slice(0, 2)
    .map((p) => p[0]?.toUpperCase())
    .join('');

  const role = user.role ?? 'user';
  const roleTone =
    role === 'super-admin' ? 'accent' : role === 'admin' ? 'info' : 'neutral';
  const roleLabel = role === 'super-admin' ? 'Super-admin' : role === 'admin' ? 'Admin' : 'User';

  async function handleSignOut() {
    await signOut();
    router.push('/auth/sign-in');
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-9 px-2 gap-2"
          aria-label={`Account · ${user.email ?? user.name ?? 'signed in'}`}
        >
          <span className="inline-flex h-6 w-6 items-center justify-center rounded-full bg-primary/15 text-primary text-[11px] font-semibold">
            {initials}
          </span>
          <UserIcon className="h-3.5 w-3.5 text-muted-foreground hidden md:inline" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-64">
        <DropdownMenuLabel className="px-3 py-2">
          <div className="flex flex-col gap-1">
            {user.name && <span className="text-sm font-medium leading-tight">{user.name}</span>}
            {user.email && (
              <span className="text-xs text-muted-foreground truncate" title={user.email}>
                {user.email}
              </span>
            )}
            <StatusBadge tone={roleTone} size="xs" className="self-start mt-1">
              {roleLabel}
            </StatusBadge>
          </div>
        </DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href="/settings" className="gap-2">
            <Settings className="h-4 w-4" />
            Settings
          </Link>
        </DropdownMenuItem>
        <DropdownMenuItem asChild>
          <Link href="/settings/security" className="gap-2">
            <ShieldCheck className="h-4 w-4" />
            Security
          </Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onSelect={handleSignOut} className="gap-2 text-destructive focus:text-destructive">
          <LogOut className="h-4 w-4" />
          Sign out
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
