"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useUser } from "@/hooks/useUser";

export function Avatar() {
  const { email, name } = useUser();
  const router = useRouter();
  const [profileName, setProfileName] = useState<string | null>(null);

  useEffect(() => {
    if (!email) return;
    try {
      const raw = localStorage.getItem(`profile-${email}`);
      if (raw) {
        const profile = JSON.parse(raw);
        if (profile.displayName) setProfileName(profile.displayName);
      }
    } catch {}
  }, [email]);

  const displayName = profileName || name || (email ? email.split("@")[0] : "User");
  const initials = displayName
    .split(/[@.\s]/)
    .filter(Boolean)
    .slice(0, 2)
    .map((s) => s[0].toUpperCase())
    .join("");

  return (
    <button
      onClick={() => router.push("/profile")}
      className="flex cursor-pointer items-center gap-2 rounded-lg px-1 py-1 transition hover:bg-zinc-100 dark:hover:bg-zinc-800"
      aria-label="View profile"
    >
      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-zinc-200 text-xs font-semibold text-zinc-700 dark:bg-zinc-700 dark:text-zinc-200">
        {initials}
      </div>
      <span className="hidden text-sm font-medium text-zinc-700 dark:text-zinc-300 lg:block">
        {displayName}
      </span>
    </button>
  );
}
