"use client";

import { useState, useEffect, useRef } from "react";
import { useTranslation } from "@/i18n/navigation";
import { pbLogout } from "@/app/lib/pocketbase";

function getAvatarLetter(email: string): string {
  const local = email.split("@")[0];
  if (!local) return "?";
  return local.slice(0, 1).toUpperCase();
}

interface UserAvatarProps {
  email: string;
  onLogout?: () => void;
}

/** 圆形头像 + 点击展开退出按钮，供 digital / meetup / vip 三站复用 */
export default function UserAvatar({ email, onLogout }: UserAvatarProps) {
  const { t } = useTranslation("common");
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleLogout = async () => {
    await pbLogout();
    setOpen(false);
    onLogout?.();
  };

  return (
    <div className="relative" ref={ref}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-sky-500 text-sm font-semibold text-white shadow-sm ring-2 ring-white dark:ring-slate-900 hover:bg-sky-600"
        aria-label={t("logout")}
      >
        {getAvatarLetter(email)}
      </button>
      {open && (
        <div className="absolute right-0 top-full z-50 mt-2 min-w-[120px] rounded-lg border border-slate-200 bg-white py-1 shadow-lg dark:border-slate-700 dark:bg-slate-800">
          <button
            onClick={handleLogout}
            className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-slate-700"
          >
            {t("logout")}
          </button>
        </div>
      )}
    </div>
  );
}
