import { useEffect, useRef, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Check } from '../../lib/icons'

const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]

interface Props {
  speed: number
  onChange: (speed: number) => void
}

/**
 * Playback-speed dropdown. Trigger shows the current speed badge in the
 * top bar; clicking opens a small radio-style menu. Same chrome look as
 * the existing TrackMenu so it slots in next to Audio / Subtitles.
 */
export default function SpeedMenu({ speed, onChange }: Props) {
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function onDoc(e: MouseEvent) {
      if (!ref.current) return
      if (!ref.current.contains(e.target as Node)) setOpen(false)
    }
    if (open) {
      window.addEventListener('mousedown', onDoc)
      return () => window.removeEventListener('mousedown', onDoc)
    }
  }, [open])

  const display = speed === 1 ? '1×' : `${speed}×`

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(o => !o)}
        className={`min-w-[44px] h-9 px-2 rounded-full grid place-items-center text-[12px] font-mono font-semibold tabular-nums transition-colors focus-ring ${
          speed !== 1 ? 'bg-accent/20 text-accent' : 'text-white/85 hover:text-white hover:bg-white/10'
        }`}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`Playback speed ${display}`}
        title={`Playback speed: ${display}`}
      >
        {display}
      </button>
      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0, y: -4, scale: 0.96 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -4, scale: 0.96 }}
            transition={{ duration: 0.15, ease: [0.16, 1, 0.3, 1] }}
            role="listbox"
            className="absolute right-0 top-full mt-2 w-44 bg-black/85 backdrop-blur-xl border border-white/12 rounded-lg shadow-2xl"
          >
            <div className="sticky top-0 px-3 py-2.5 bg-black/90 border-b border-white/8 z-10">
              <p className="text-[10px] uppercase tracking-[0.14em] font-semibold text-white/60">
                Playback speed
              </p>
            </div>
            <div className="p-1">
              {SPEEDS.map(s => {
                const selected = Math.abs(speed - s) < 0.001
                return (
                  <button
                    key={s}
                    onClick={() => {
                      onChange(s)
                      setOpen(false)
                    }}
                    role="option"
                    aria-selected={selected}
                    className={`w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-left transition-colors duration-100 focus-ring ${
                      selected ? 'bg-accent/15' : 'hover:bg-white/8'
                    }`}
                  >
                    <span
                      className={`w-4 h-4 grid place-items-center shrink-0 ${
                        selected ? 'text-accent' : 'text-transparent'
                      }`}
                    >
                      <Check size={13} strokeWidth={2.5} />
                    </span>
                    <span
                      className={`flex-1 text-[12.5px] font-mono tabular-nums ${
                        selected ? 'text-accent font-semibold' : 'text-white'
                      }`}
                    >
                      {s === 1 ? 'Normal (1×)' : `${s}×`}
                    </span>
                  </button>
                )
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  )
}
