"use client";

import { useEffect, useRef, useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { LogOut } from "lucide-react";
import { useLoginModalStore } from "@/lib/login-modal-store";

/**
 * 导航栏 **右侧** 的登录入口：
 * - 未登录：紫色描边胶囊「登录 / 注册」→ 点击弹出 LoginModal
 * - 已登录：头像 + 昵称 胶囊 → 点击下方展开下拉，含「退出登录」
 *
 * 中部的「我的」链接由 NavLinks 处理（独立组件），不在本组件内。
 */
export default function AuthMenu() {
  const { data: session, status } = useSession();
  const openLogin = useLoginModalStore((s) => s.show);
  const [menuOpen, setMenuOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!menuOpen) return;
    const handler = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) {
        setMenuOpen(false);
      }
    };
    const esc = (e: KeyboardEvent) => {
      if (e.key === "Escape") setMenuOpen(false);
    };
    document.addEventListener("mousedown", handler);
    document.addEventListener("keydown", esc);
    return () => {
      document.removeEventListener("mousedown", handler);
      document.removeEventListener("keydown", esc);
    };
  }, [menuOpen]);

  const user = session?.user;
  const initial = user?.name?.charAt(0).toUpperCase() ?? "?";

  // 未登录态：与登录后保持一致的紫色实心胶囊
  if (status !== "authenticated") {
    return (
      <button
        type="button"
        onClick={() => status !== "loading" && openLogin()}
        className="font-display text-[10px] sm:text-xs tracking-[0.2em] uppercase px-4 sm:px-5 h-9 inline-flex items-center justify-center rounded-full bg-grad-purple text-white shadow-[0_0_14px_rgba(139,92,246,0.45)] ring-1 ring-inset ring-white/15 hover:brightness-110 active:brightness-95 transition-all"
      >
        登录 / 注册
      </button>
    );
  }

  // 已登录态：头像 + 昵称 + 下拉（紫色渐变实心胶囊，高亮用户身份）
  return (
    <div ref={rootRef} className="relative">
      <button
        type="button"
        onClick={() => setMenuOpen((v) => !v)}
        className="flex items-center gap-2 h-9 px-2.5 rounded-full bg-grad-purple shadow-[0_0_14px_rgba(139,92,246,0.45)] ring-1 ring-inset ring-white/15 hover:brightness-110 active:brightness-95 transition-all"
        aria-haspopup="menu"
        aria-expanded={menuOpen}
        aria-label={`${user?.name ?? "用户"} · 账号菜单`}
      >
        <span className="w-7 h-7 rounded-full flex items-center justify-center text-white font-display text-xs bg-white/15 border border-white/25">
          {initial}
        </span>
        <span className="text-xs text-white hidden sm:inline max-w-[80px] truncate">
          {user?.name}
        </span>
      </button>

      {menuOpen && (
        <div
          role="menu"
          className="absolute right-0 top-full mt-2 w-44 rounded-xl bg-elevated/95 backdrop-blur-xl border border-white/10 shadow-[0_12px_36px_rgba(0,0,0,0.55),0_0_24px_rgba(139,92,246,0.12)] overflow-hidden z-50"
        >
          <div className="px-4 py-3 border-b border-white/[0.06]">
            <div className="text-xs text-white/55">登录账号</div>
            <div className="text-sm text-white truncate mt-0.5">
              {user?.name}
            </div>
          </div>
          <button
            type="button"
            role="menuitem"
            onClick={() => {
              setMenuOpen(false);
              signOut({ callbackUrl: "/" });
            }}
            className="w-full px-4 py-3 flex items-center gap-2 text-sm text-white/80 hover:bg-pink-500/[0.08] hover:text-pink-400 transition-colors text-left"
          >
            <LogOut size={14} />
            退出登录
          </button>
        </div>
      )}
    </div>
  );
}
