"use client"

import Image from "next/image"
import { useCallback, useState } from "react"

const IMAGE_POOL = [
  "/assets/images/autumn.png",
  "/assets/images/kuss.png",
  "/assets/images/chaos.png",
  "/assets/images/conference.png",
  "/assets/images/explaining.png",
  "/assets/images/family.png",
  "/assets/images/pres_1.png",
  "/assets/images/robot.png",
] as const

function pickRandom(exclude?: string): string {
  const available = exclude
    ? IMAGE_POOL.filter((p) => p !== exclude)
    : [...IMAGE_POOL]
  return available[Math.floor(Math.random() * available.length)]
}

export function AvatarImage({ alt }: { alt: string }) {
  const [currentSrc, setCurrentSrc] = useState(() => pickRandom())
  const [isSpinning, setIsSpinning] = useState(false)

  const handleMouseEnter = useCallback(() => {
    setIsSpinning(true)
    setCurrentSrc((prev) => pickRandom(prev))
  }, [])

  const handleAnimationEnd = useCallback(() => {
    setIsSpinning(false)
  }, [])

  return (
    <div
      className="flex size-20 shrink-0 sm:size-24 [perspective:500px]"
      onMouseEnter={handleMouseEnter}
      onAnimationEnd={handleAnimationEnd}
    >
      <div
        className={`relative size-full overflow-hidden rounded-full bg-emerald-100 [transform-style:preserve-3d] ${isSpinning ? "animate-coin-spin" : ""}`}
      >
        <Image
          key={currentSrc}
          src={currentSrc}
          alt={alt}
          fill
          className="object-cover"
          sizes="192px"
          quality={95}
        />
      </div>
    </div>
  )
}
