import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cn } from './utils'

export interface ScoreRingProps extends HTMLAttributes<HTMLDivElement> {
  score: number
  size?: number
  radius?: number
  strokeWidth?: number
  stroke?: string
  trackStroke?: string
  children?: ReactNode
}

const ScoreRing = forwardRef<HTMLDivElement, ScoreRingProps>(
  (
    {
      score,
      size = 132,
      radius = 56,
      strokeWidth = 6,
      stroke = 'currentColor',
      trackStroke = 'var(--border-2)',
      className,
      children,
      style,
      ...props
    },
    ref
  ) => {
    const clamped = Math.max(0, Math.min(100, score))
    const circumference = 2 * Math.PI * radius
    const offset = circumference - (clamped / 100) * circumference
    const center = size / 2

    return (
      <div
        ref={ref}
        className={cn('relative inline-flex items-center justify-center', className)}
        style={{ ...style, width: size, height: size }}
        {...props}
      >
        <svg
          width={size}
          height={size}
          viewBox={`0 0 ${size} ${size}`}
          className="-rotate-90"
          aria-hidden="true"
        >
          <circle
            cx={center}
            cy={center}
            r={radius}
            fill="none"
            stroke={trackStroke}
            strokeWidth={strokeWidth}
          />
          <circle
            cx={center}
            cy={center}
            r={radius}
            fill="none"
            stroke={stroke}
            strokeWidth={strokeWidth}
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={offset}
            className="transition-[stroke-dashoffset] duration-500 ease-out"
          />
        </svg>
        {children && (
          <div className="absolute inset-0 flex items-center justify-center">{children}</div>
        )}
      </div>
    )
  }
)
ScoreRing.displayName = 'ScoreRing'
export { ScoreRing }
