"use client";

import { usePathname } from "next/navigation";
import Link from "next/link";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { useLoginModal } from "@/app/LoginModalContext";
import { logout } from "@/auth/actions";
import "./UserMenu.css";

interface UserMenuClientProps {
  user: {
    handle: string;
    avatar?: string;
  } | null;
}

export function UserMenuClient({ user }: UserMenuClientProps) {
  const { openLoginModal } = useLoginModal();
  const pathname = usePathname();

  if (!user) {
    return (
      <button onClick={openLoginModal} className="UserMenu-loginButton">
        log in
      </button>
    );
  }

  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger asChild>
        <button className="UserMenu-trigger" aria-label="User menu">
          {user.avatar ? (
            <img src={user.avatar} alt={user.handle} className="UserMenu-avatar" />
          ) : (
            <span className="UserMenu-avatarFallback">{user.handle[0].toUpperCase()}</span>
          )}
        </button>
      </DropdownMenu.Trigger>

      <DropdownMenu.Portal>
        <DropdownMenu.Content className="UserMenu-content" align="end" sideOffset={8}>
          <DropdownMenu.Item asChild>
            <Link href={`/@${user.handle}`} className="UserMenu-item">
              profile
            </Link>
          </DropdownMenu.Item>

          <DropdownMenu.Separator className="UserMenu-separator" />

          <DropdownMenu.Item className="UserMenu-item" onSelect={() => logout(pathname)}>
            log out
          </DropdownMenu.Item>
        </DropdownMenu.Content>
      </DropdownMenu.Portal>
    </DropdownMenu.Root>
  );
}
