"use client" import { useState, useEffect } from "react" import { RatingInput, RatingBadge } from "@/components/ui/rating-input" import { getApiUrl } from "@/lib/api-config" interface EntityRatingProps { entityType: "show" | "song" | "venue" | "tour" | "performance" entityId: number compact?: boolean } export function EntityRating({ entityType, entityId, compact = false }: EntityRatingProps) { const [userRating, setUserRating] = useState(0) const [averageRating, setAverageRating] = useState(0) const [loading, setLoading] = useState(false) const [hasRated, setHasRated] = useState(false) useEffect(() => { // Fetch average rating fetch(`${getApiUrl()}/social/ratings/average?${entityType}_id=${entityId}`) .then(res => res.ok ? res.json() : 0) .then(data => setAverageRating(data || 0)) .catch(() => setAverageRating(0)) }, [entityType, entityId]) const handleRate = async (score: number) => { const token = localStorage.getItem("token") if (!token) { alert("Please log in to rate.") return } setLoading(true) try { const body: Record = { score } body[`${entityType}_id`] = entityId const res = await fetch(`${getApiUrl()}/social/ratings`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify(body) }) if (!res.ok) throw new Error("Failed to submit rating") const data = await res.json() setUserRating(data.score) setHasRated(true) // Re-fetch average fetch(`${getApiUrl()}/social/ratings/average?${entityType}_id=${entityId}`) .then(res => res.ok ? res.json() : averageRating) .then(setAverageRating) } catch (err) { console.error(err) alert("Error submitting rating") } finally { setLoading(false) } } if (compact) { return (
{averageRating > 0 && ( )}
) } return (
Your Rating {averageRating > 0 && ( Community avg: {averageRating.toFixed(1)} )}
{loading && (

Submitting...

)} {hasRated && !loading && (

✓ Rating saved!

)}
) }