import { useState } from 'react'

export default function Stars({ value = 0, onChange, small }) {
  const [hover, setHover] = useState(0)
  const shown = hover || value || 0
  return (
    <span
      className={`stars${small ? ' stars-small' : ''}${onChange ? '' : ' stars-readonly'}`}
      onMouseLeave={() => setHover(0)}
    >
      {[1, 2, 3, 4, 5].map((n) => (
        <button
          key={n}
          type="button"
          className={n <= shown ? 'star filled' : 'star'}
          disabled={!onChange}
          onMouseEnter={() => onChange && setHover(n)}
          onClick={(e) => {
            e.stopPropagation()
            // Clicking the current rating clears it.
            onChange(n === value ? 0 : n)
          }}
          title={onChange ? `${n} star${n > 1 ? 's' : ''}` : undefined}
        >
          ★
        </button>
      ))}
    </span>
  )
}
