"use client";

import { ChevronDown } from "lucide-react";
import { useTranslations } from "next-intl";

import { Link } from "@/i18n/navigation";
import { Avatar } from "@/components/ui/Avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import type { NavUser } from "@/lib/auth/session";

/**
 * Logged-in navbar control: avatar + dropdown with role-aware links (admins also
 * get the admin panel) and sign-out. Shown in place of Sign In / Try Free.
 */
export function UserMenu({ user }: { user: NavUser }) {
  const t = useTranslations("nav");

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          className="flex items-center gap-1.5 rounded-full p-0.5 pe-2 transition-colors hover:bg-gray-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2"
          aria-label={t("accountMenu")}
        >
          <Avatar src={user.avatarUrl} name={user.name} email={user.email} size={32} />
          <ChevronDown className="hidden h-4 w-4 text-gray-500 sm:block" aria-hidden />
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-60">
        <div className="flex items-center gap-3 px-2 py-2">
          <Avatar src={user.avatarUrl} name={user.name} email={user.email} size={40} />
          <div className="min-w-0">
            <p className="truncate text-sm font-medium text-neutral-900">{user.name}</p>
            <p className="truncate text-xs text-neutral-500">{user.email}</p>
          </div>
        </div>
        <div className="px-2 pb-1.5">
          <span
            className={`inline-block rounded-full px-2 py-0.5 text-[11px] font-medium ${
              user.isAdmin ? "bg-indigo-100 text-indigo-700" : "bg-primary-100 text-primary-700"
            }`}
          >
            {user.isAdmin ? t("roleAdmin") : t("roleUser")}
          </span>
        </div>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link href="/dashboard" className="cursor-pointer">{t("menuDashboard")}</Link>
        </DropdownMenuItem>
        {user.isAdmin && (
          <DropdownMenuItem asChild>
            <Link href="/admin" className="cursor-pointer">{t("menuAdminPanel")}</Link>
          </DropdownMenuItem>
        )}
        <DropdownMenuItem asChild>
          <Link href="/dashboard/settings" className="cursor-pointer">{t("menuProfile")}</Link>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <form action="/auth/sign-out" method="post" className="w-full">
            <button type="submit" className="w-full cursor-pointer text-start text-red-600">
              {t("menuSignOut")}
            </button>
          </form>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
