import { motion } from 'framer-motion'
import { cn } from '@/lib/utils'
import { SubtitleWord } from '@/lib/mockData'

interface CaptionsTimelineProps {
    currentTime: number
    words: SubtitleWord[]
    onWordClick: (word: SubtitleWord) => void
}

const SECOND_WIDTH = 100 // px per second

export const CaptionsTimeline = ({ currentTime, words, onWordClick }: CaptionsTimelineProps) => {
    // Center alignment: Viewport Center = Time 0. But we want Current Time to be at Center.
    // So transform = -currentTime * width

    return (
        <div className="bg-muted/30 h-[80px] w-full relative border-y border-border/50 overflow-hidden select-none">
            {/* Center Marker Line */}
            <div className="absolute left-1/2 top-0 bottom-0 w-0.5 bg-primary/50 z-20" />

            <motion.div
                className="relative h-full left-1/2 will-change-transform flex items-center"
                initial={false}
                animate={{ x: -currentTime * SECOND_WIDTH }}
                transition={{ type: "tween", ease: "linear", duration: 0.1 }} // Smooth continous movement
            >
                {words.map((word, idx) => {
                    const isActive = currentTime >= word.startTime && currentTime <= word.endTime

                    return (
                        <div
                            key={idx}
                            className={cn(
                                "absolute px-2 py-1 rounded cursor-pointer transition-all border text-sm font-medium whitespace-nowrap flex items-center justify-center hover:z-10",
                                isActive
                                    ? "bg-primary text-primary-foreground border-primary shadow-lg scale-110 z-10"
                                    : "bg-card border-border hover:bg-accent text-foreground hover:scale-105"
                            )}
                            style={{
                                left: word.startTime * SECOND_WIDTH,
                                width: Math.max((word.endTime - word.startTime) * SECOND_WIDTH, 40) // Min width
                            }}
                            onClick={(e) => {
                                e.stopPropagation()
                                onWordClick(word)
                            }}
                        >
                            {word.text}
                        </div>
                    )
                })}
            </motion.div>
        </div>
    )
}
