"use client"

import { Heart } from "lucide-react"
import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import { useRequireAuth } from "@/lib/use-require-auth"
import { useAuthStore } from "@/store/auth"

interface FavoriteButtonProps {
  initialFavorited: boolean
  targetType: "player" | "shop"
  targetId: string
}

export function FavoriteButton({ initialFavorited, targetType, targetId }: FavoriteButtonProps) {
  const [favorited, setFavorited] = useState(initialFavorited)
  const { requireAuth } = useRequireAuth()
  const userId = useAuthStore((s) => s.user?.id)
  const storageKey = useMemo(
    () => `favorite:${userId ?? "guest"}:${targetType}:${targetId}`,
    [userId, targetType, targetId],
  )

  useEffect(() => {
    const stored = window.localStorage.getItem(storageKey)
    if (stored === "1") {
      setFavorited(true)
      return
    }
    if (stored === "0") {
      setFavorited(false)
      return
    }
    setFavorited(initialFavorited)
  }, [storageKey, initialFavorited])

  return (
    <Button
      variant={favorited ? "default" : "outline"}
      size="sm"
      className="gap-1.5"
      onClick={() =>
        requireAuth(() =>
          setFavorited((prev) => {
            const next = !prev
            window.localStorage.setItem(storageKey, next ? "1" : "0")
            return next
          }),
        )
      }
    >
      <Heart className={`h-4 w-4 ${favorited ? "fill-current" : ""}`} />
      {favorited ? "已收藏" : "收藏"}
    </Button>
  )
}
