"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, usePathname } from "next/navigation";
import { motion } from "framer-motion";
import { User, Sun, Moon, Monitor } from "lucide-react";
import { getCachedProfile } from "@/lib/userId";
import { type Theme, getStoredTheme, setStoredTheme } from "@/lib/theme";
import AuthModal from "@/components/AuthModal";
import type { UserProfile } from "@/types";

const HIDDEN_PREFIXES = ["/profile"];

export default function GlobalUserBadge() {
  const router = useRouter();
  const pathname = usePathname();
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [showAuth, setShowAuth] = useState(false);
  const [theme, setTheme] = useState<Theme>("system");
  const hidden = HIDDEN_PREFIXES.some((p) => pathname.startsWith(p));

  useEffect(() => {
    setProfile(getCachedProfile());
  }, [pathname]);

  useEffect(() => {
    setTheme(getStoredTheme());
  }, []);

  useEffect(() => {
    const handler = () => setProfile(getCachedProfile());
    window.addEventListener("nowhatever_auth", handler);
    return () => window.removeEventListener("nowhatever_auth", handler);
  }, []);

  const handleAuth = useCallback((p: UserProfile) => {
    setProfile(p);
    setShowAuth(false);
  }, []);

  const cycleTheme = useCallback(() => {
    const order: Theme[] = ["system", "light", "dark"];
    const next = order[(order.indexOf(theme) + 1) % 3];
    setTheme(next);
    setStoredTheme(next);
  }, [theme]);

  const ThemeIcon = theme === "light" ? Sun : theme === "dark" ? Moon : Monitor;
  const themeLabel = theme === "light" ? "浅色" : theme === "dark" ? "深色" : "自动";

  if (hidden) return null;

  return (
    <>
      <motion.div
        className="fixed right-4 top-3 z-50 flex items-center gap-1.5"
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ delay: 0.1, duration: 0.3 }}
      >
        <button
          onClick={cycleTheme}
          className="flex h-8 items-center gap-1 rounded-full bg-surface/80 px-2.5 text-muted ring-1 ring-border/50 backdrop-blur-md transition-colors hover:bg-elevated hover:text-heading"
        >
          <ThemeIcon size={13} />
          <span className="text-[10px] font-medium">{themeLabel}</span>
        </button>

        {profile ? (
          <button
            onClick={() => router.push("/profile")}
            className="flex h-8 items-center gap-1.5 rounded-full bg-surface/80 px-3 ring-1 ring-border/50 backdrop-blur-md transition-colors hover:bg-elevated active:opacity-80"
          >
            <span className="text-base leading-none">{profile.avatar}</span>
            <span className="max-w-20 truncate text-xs font-semibold text-secondary">
              {profile.username}
            </span>
          </button>
        ) : (
          <button
            onClick={() => setShowAuth(true)}
            className="flex h-8 items-center gap-1.5 rounded-full bg-surface/80 px-3 text-xs font-medium text-muted ring-1 ring-border/50 backdrop-blur-md transition-colors hover:bg-elevated hover:text-secondary"
          >
            <User size={13} />
            登录
          </button>
        )}
      </motion.div>

      <AuthModal
        open={showAuth}
        onClose={() => setShowAuth(false)}
        onAuth={handleAuth}
      />
    </>
  );
}
