"use client";

import { useId } from "react";

function StarIcon({ filled, half, gradientId }: { filled?: boolean; half?: boolean; gradientId?: string }) {
    if (half && gradientId) {
        return (
            <svg className="size-[18px] text-[var(--warm)]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
                <defs>
                    <linearGradient id={gradientId} x1="0" x2="1" y1="0" y2="0">
                        <stop offset="50%" stopColor="currentColor" />
                        <stop offset="50%" stopColor="transparent" />
                    </linearGradient>
                </defs>
                <path fill={`url(#${gradientId})`} d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
            </svg>
        );
    }
    return (
        <svg className="size-[18px] text-[var(--warm)]" viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5" aria-hidden>
            <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
        </svg>
    );
}

export function StarRatingDisplay({ value, size = "md" }: { value: number; size?: "sm" | "md" }) {
    const id = useId();
    const full = Math.floor(value);
    const hasHalf = value % 1 >= 0.25 && value % 1 < 0.75;
    const stars = [];

    for (let i = 0; i < 5; i++) {
        if (i < full) {
            stars.push(<StarIcon key={i} filled />);
        } else if (i === full && hasHalf) {
            stars.push(<StarIcon key={i} half gradientId={id.replace(/:/g, "")} />);
        } else {
            stars.push(<StarIcon key={i} />);
        }
    }

    const wrapperClass = size === "sm" ? "scale-90 origin-left" : "";

    return (
        <div className={`flex items-center gap-0.5 ${wrapperClass}`} aria-label={`${value.toFixed(1)} out of 5 stars`}>
            {stars}
        </div>
    );
}
