"use client" import { Button } from "@/components/ui/button" import { addFavorite, isFavorited, listFavorites, removeFavorite } from "@/lib/api/favorites" import { toApiError } from "@/lib/errors" import { notifyInfo } from "@/lib/toast" import { useRequireAuth } from "@/lib/use-require-auth" import { useAuthStore } from "@/store/auth" import { Heart } from "lucide-react" import { useEffect, useState } from "react" interface FavoriteButtonProps { initialFavorited: boolean targetType: "player" | "shop" targetId: string } export function FavoriteButton({ initialFavorited, targetType, targetId }: FavoriteButtonProps) { const { requireAuth } = useRequireAuth() const userId = useAuthStore((s) => s.user?.id) const [favorited, setFavorited] = useState(initialFavorited) const [pending, setPending] = useState(false) useEffect(() => { let cancelled = false if (!userId) { void Promise.resolve().then(() => { if (cancelled) return setFavorited(initialFavorited) }) return () => { cancelled = true } } isFavorited(userId, targetType, targetId) .then((value) => { if (cancelled) return setFavorited(value) }) .catch((err: unknown) => { if (cancelled) return if (err instanceof Error && err.message === "UNAUTHORIZED") return notifyInfo(toApiError(err).msg) }) return () => { cancelled = true } }, [initialFavorited, targetId, targetType, userId]) return ( ) }