﻿/**
 * @file features/layout/components/user-menu.tsx
 * @description 사용자 프로필 드롭다운 메뉴 컴포넌트
 */

"use client";

import { User } from "@supabase/supabase-js";
import { LogOut, Settings, User as UserIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { signout } from "@/features/auth/actions";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";

const SESSION_RELATED_STORAGE_KEYS = [
  "session-storage",
  "auth-storage",
  "autotrade-kis-runtime-store",
] as const;

interface UserMenuProps {
  /** Supabase User 객체 */
  user: User | null;
  /** 홈 랜딩의 shader 배경 위에서 대비를 높이는 모드 */
  blendWithBackground?: boolean;
}

/**
 * 사용자 메뉴/프로필 컴포넌트
 * @param user 로그인한 사용자 정보
 * @param blendWithBackground shader 배경 위 가독성 모드
 * @returns Avatar 버튼 + 드롭다운 메뉴
 * @see features/layout/components/header.tsx 헤더 우측 액션 영역에서 호출
 */
export function UserMenu({ user, blendWithBackground = false }: UserMenuProps) {
  const router = useRouter();

  if (!user) return null;

  /**
   * @description 로그아웃 제출 직전에 세션 관련 로컬 스토리지를 정리합니다.
   * @see features/auth/actions.ts signout - 서버 세션 종료를 담당합니다.
   */
  const clearSessionRelatedStorage = () => {
    if (typeof window === "undefined") return;

    for (const key of SESSION_RELATED_STORAGE_KEYS) {
      window.localStorage.removeItem(key);
    }
  };

  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger asChild>
        <button
          className={cn(
            "flex items-center gap-2 rounded-full outline-none transition-colors",
            blendWithBackground
              ? "ring-1 ring-white/30 hover:bg-black/30 focus-visible:ring-2 focus-visible:ring-white/70"
              : "",
          )}
          aria-label="사용자 메뉴 열기"
        >
          <Avatar className="h-8 w-8 transition-opacity hover:opacity-90">
            <AvatarImage src={user.user_metadata?.avatar_url} />
            <AvatarFallback
              className={cn(
                "text-xs font-bold text-white",
                blendWithBackground
                  ? "bg-brand-500/90 [text-shadow:0_1px_8px_rgba(0,0,0,0.45)]"
                  : "bg-linear-to-br from-brand-500 to-brand-700",
              )}
            >
              {user.email?.charAt(0).toUpperCase()}
            </AvatarFallback>
          </Avatar>
        </button>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="end" className="w-56">
        <DropdownMenuLabel className="font-normal">
          <div className="flex flex-col space-y-1">
            <p className="text-sm font-medium leading-none">
              {user.user_metadata?.full_name || user.user_metadata?.name || "사용자"}
            </p>
            <p className="text-xs leading-none text-muted-foreground">{user.email}</p>
          </div>
        </DropdownMenuLabel>

        <DropdownMenuSeparator />

        <DropdownMenuItem onClick={() => router.push("/profile")}>
          <UserIcon className="mr-2 h-4 w-4" />
          <span>프로필</span>
        </DropdownMenuItem>

        <DropdownMenuItem onClick={() => router.push("/settings")}>
          <Settings className="mr-2 h-4 w-4" />
          <span>설정</span>
        </DropdownMenuItem>

        <DropdownMenuSeparator />

        <form action={signout} onSubmit={clearSessionRelatedStorage}>
          <DropdownMenuItem asChild>
            <button className="w-full text-red-600 dark:text-red-400">
              <LogOut className="mr-2 h-4 w-4" />
              <span>로그아웃</span>
            </button>
          </DropdownMenuItem>
        </form>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
