import { motion, useReducedMotion } from 'framer-motion';
import { Star } from 'lucide-react';

export default function RatingDistribution({ histogram, avg, count }: { histogram: number[]; avg: number; count: number }) {
    const reduce = useReducedMotion();
    const max = Math.max(1, ...histogram);

    if (!count) {
        return <p className="text-sm text-muted-foreground">No ratings yet. Be the first to rate this game.</p>;
    }

    return (
        <div className="space-y-4">
            <div className="flex items-end gap-3">
                <span className="text-display !text-5xl">{avg.toFixed(1)}</span>
                <div className="pb-1.5">
                    <div className="flex items-center gap-1 text-amber-400" aria-hidden>
                        {[2, 4, 6, 8, 10].map((n) => <Star key={n} className={`size-3.5 ${avg >= n - 0.5 ? 'fill-current' : 'opacity-30'}`} />)}
                    </div>
                    <p className="text-caption mt-0.5">{count.toLocaleString()} ratings</p>
                </div>
            </div>
            <ul className="space-y-1.5" aria-label="Rating distribution">
                {[...histogram.keys()].reverse().map((i) => {
                    const n = histogram[i];
                    const pct = Math.round((n / count) * 100);
                    return (
                        <li key={i} className="grid grid-cols-[1.25rem_1fr_2.5rem] items-center gap-2 text-xs" aria-label={`${i + 1} out of 10: ${n} ratings, ${pct} percent`}>
                            <span className="text-right tabular-nums text-muted-foreground">{i + 1}</span>
                            <span className="h-2 overflow-hidden rounded-full bg-muted">
                                <motion.span
                                    initial={{ width: reduce ? `${(n / max) * 100}%` : 0 }}
                                    whileInView={{ width: `${(n / max) * 100}%` }}
                                    viewport={{ once: true }}
                                    transition={{ duration: 0.7, delay: (9 - i) * 0.04, ease: [0.22, 1, 0.36, 1] }}
                                    className="block h-full rounded-full bg-primary"
                                />
                            </span>
                            <span className="tabular-nums text-muted-foreground">{pct}%</span>
                        </li>
                    );
                })}
            </ul>
        </div>
    );
}
