import { useState, useRef, useEffect } from "react";
import { MapPin, Puzzle, Settings, ChevronRight } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import { Avatar } from "./ui/avatar";
import { useProfileStore } from "../stores/profileStore";

// Secondary destinations (previously in the hamburger menu).
const SECONDARY = [
  { path: "/locations", label: "Emplacements", icon: MapPin },
  { path: "/games", label: "Jeux importés", icon: Puzzle },
  { path: "/settings", label: "Paramètres", icon: Settings },
];

// Top-right avatar that opens the profile + secondary menu.
export function ProfileMenu() {
  const [isOpen, setIsOpen] = useState(false);
  const navigate = useNavigate();
  const ref = useRef<HTMLDivElement>(null);
  const activeProfile = useProfileStore((s) => s.activeProfile);

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

  const go = (path: string) => {
    setIsOpen(false);
    navigate(path);
  };

  return (
    <div ref={ref} className="relative z-50">
      <button
        onClick={() => setIsOpen((v) => !v)}
        className="active:scale-95 transition-transform rounded-full"
        aria-label="Profil et réglages"
      >
        <Avatar
          src={activeProfile?.avatar}
          name={activeProfile?.name || "?"}
          size="md"
          className="ring-2 ring-primary/20"
        />
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, scale: 0.95, transformOrigin: "top right" }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            transition={{ duration: 0.15 }}
            className="absolute top-full right-0 mt-2 w-60 bg-card border shadow-xl rounded-2xl overflow-hidden"
          >
            <button
              onClick={() => go("/profiles")}
              className="flex items-center w-full p-4 hover:bg-secondary text-left transition-colors bg-primary/5"
            >
              <Avatar
                src={activeProfile?.avatar}
                name={activeProfile?.name || "?"}
                size="md"
                className="mr-3"
              />
              <div className="flex-1 min-w-0">
                <div className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
                  Profil actif
                </div>
                <div className="font-black truncate">
                  {activeProfile?.name || "—"}
                </div>
              </div>
              <ChevronRight className="w-4 h-4 text-muted-foreground shrink-0" />
            </button>

            {SECONDARY.map((item) => {
              const Icon = item.icon;
              return (
                <button
                  key={item.path}
                  onClick={() => go(item.path)}
                  className="flex items-center w-full p-4 hover:bg-secondary text-left font-medium transition-colors border-t border-border/50"
                >
                  <Icon className="w-5 h-5 mr-3 text-primary" /> {item.label}
                </button>
              );
            })}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
