import { useCallback, useEffect, useRef, useState } from 'react'

export interface ScrubberMark {
  time: number
  color: string
}

interface Props {
  current: number
  duration: number
  marks: ScrubberMark[]
  onSeek: (time: number) => void
}

const TICK_PERCENTS = [0, 25, 50, 75, 100]

export default function Scrubber({ current, duration, marks, onSeek }: Props) {
  const trackRef = useRef<HTMLDivElement>(null)
  const [dragging, setDragging] = useState(false)
  const safeDuration = duration > 0 ? duration : 1
  const pct = Math.max(0, Math.min(100, (current / safeDuration) * 100))

  const seekFromClientX = useCallback((clientX: number) => {
    const el = trackRef.current
    if (!el) return
    const rect = el.getBoundingClientRect()
    const x = Math.max(0, Math.min(rect.width, clientX - rect.left))
    onSeek((x / rect.width) * safeDuration)
  }, [onSeek, safeDuration])

  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault()
    setDragging(true)
    seekFromClientX(e.clientX)
  }

  useEffect(() => {
    if (!dragging) return
    const move = (e: MouseEvent) => seekFromClientX(e.clientX)
    const up = () => setDragging(false)
    window.addEventListener('mousemove', move)
    window.addEventListener('mouseup', up)
    return () => {
      window.removeEventListener('mousemove', move)
      window.removeEventListener('mouseup', up)
    }
  }, [dragging, seekFromClientX])

  return (
    <div ref={trackRef} className="scrub" onMouseDown={handleMouseDown}>
      <div className="fill" style={{ width: `${pct}%` }} />
      {TICK_PERCENTS.map(p => (
        <div key={p} className="tick" style={{ left: `${p}%` }} />
      ))}
      {marks.map((m, i) => {
        const mpct = Math.max(0, Math.min(100, (m.time / safeDuration) * 100))
        return <div key={i} className="mark" style={{ left: `${mpct}%`, background: m.color }} />
      })}
      <div className="head" style={{ left: `${pct}%` }} />
      <div className="head-knob" style={{ left: `${pct}%` }} />
    </div>
  )
}
