import { useEffect, useState, type CSSProperties } from 'react'

const spinnerRegistry = {
  cascade: {
    frames: [
      '⠀⠀⠀⠀',
      '⠁⠀⠀⠀',
      '⠋⠀⠀⠀',
      '⠞⠁⠀⠀',
      '⡴⠋⠀⠀',
      '⣠⠞⠁⠀',
      '⢀⡴⠋⠀',
      '⠀⣠⠞⠁',
      '⠀⢀⡴⠋',
      '⠀⠀⣠⠞',
      '⠀⠀⢀⡴',
      '⠀⠀⠀⣠',
      '⠀⠀⠀⢀',
    ],
    interval: 60,
  },
  orbit: {
    frames: ['⠃', '⠉', '⠘', '⠰', '⢠', '⣀', '⡄', '⠆'],
    interval: 90,
  },
} as const

function useSpinnerFrame(frames: readonly string[], interval: number) {
  const [index, setIndex] = useState(0)

  useEffect(() => {
    const id = window.setInterval(() => {
      setIndex((current) => (current + 1) % frames.length)
    }, interval)
    return () => window.clearInterval(id)
  }, [frames, interval])

  return frames[index] ?? ''
}

export function NamedAgentSpinner({
  name,
  size = 28,
  color = 'currentColor',
  className,
  style,
}: {
  name: keyof typeof spinnerRegistry
  size?: number
  color?: string
  className?: string
  style?: CSSProperties
}) {
  const meta = spinnerRegistry[name]
  const frame = useSpinnerFrame(meta.frames, meta.interval)

  return (
    <div
      className={className}
      style={{
        width: size * 2.5,
        height: size * 2.5,
        display: 'grid',
        placeItems: 'center',
        ...style,
      }}
    >
      <span
        style={{
          fontSize: size,
          color,
          lineHeight: 1,
          whiteSpace: 'pre',
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',
        }}
      >
        {frame}
      </span>
    </div>
  )
}
