import { usePage } from "@inertiajs/react";
import { ChevronsUpDown } from "lucide-react";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { UserMenuContent } from "@/components/user-menu-content";
import { useInitials } from "@/hooks/use-initials";
import type { Auth } from "@/types";

/**
 * The account menu, sitting in the top bar beside the search.
 *
 * It used to live at the foot of the sidebar, which put a person's own name a
 * long way from the work and buried the way to their profile. Here it is where
 * a signed-in person looks first: photo, name, and one click to their profile.
 */
export function NavUser() {
    const { auth } = usePage<{ auth: Auth }>().props;
    const getInitials = useInitials();

    if (!auth?.user) {
        return null;
    }

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Button
                    variant="ghost"
                    className="h-9 gap-2 rounded-full py-1 pr-2 pl-1 hover:bg-accent/70"
                    aria-label={`Account menu for ${auth.user.name}`}
                    data-test="sidebar-menu-button"
                >
                    <Avatar className="size-7 overflow-hidden rounded-full">
                        <AvatarImage
                            src={auth.user.avatar}
                            alt=""
                            className="object-cover"
                        />
                        <AvatarFallback className="rounded-full bg-solar-soft text-[11px] font-semibold text-solar-ink">
                            {getInitials(auth.user.name)}
                        </AvatarFallback>
                    </Avatar>

                    <span className="hidden max-w-36 truncate text-sm font-medium xl:inline">
                        {auth.user.name}
                    </span>

                    <ChevronsUpDown className="hidden size-3.5 text-muted-foreground xl:inline" />
                </Button>
            </DropdownMenuTrigger>

            <DropdownMenuContent className="w-60" align="end" sideOffset={8}>
                <UserMenuContent user={auth.user} />
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
