const Timeline = ({ duration, currentTime, onSeek, transcriptions }) => {
    const formatTime = (seconds) => {
        const m = Math.floor(seconds / 60);
        const s = Math.floor(seconds % 60);
        return `${m}:${s.toString().padStart(2, '0')}`;
    };

    const handleClick = (e) => {
        const rect = e.currentTarget.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const percent = Math.max(0, Math.min(1, x / rect.width));
        onSeek(percent * duration);
    };

    return (
        <div className="w-full mt-4 glass-panel rounded-xl p-4">
            <div className="flex justify-between text-xs text-slate-400 mb-2 font-mono">
                <span>{formatTime(currentTime)}</span>
                <span>{formatTime(duration)}</span>
            </div>

            <div
                className="relative h-12 bg-slate-900/50 rounded-lg cursor-pointer group overflow-hidden"
                onClick={handleClick}
            >
                {/* Segments */}
                {transcriptions.map((t, i) => {
                    // Convert "00:00:03.500" to seconds
                    const parseTime = (timeStr) => {
                        const [h, m, s] = timeStr.split(':');
                        return parseInt(h) * 3600 + parseInt(m) * 60 + parseFloat(s);
                    };

                    const start = parseTime(t.start);
                    const end = parseTime(t.end);
                    const left = (start / duration) * 100;
                    const width = ((end - start) / duration) * 100;

                    // Determine color based on speaker
                    const isVoiceover = t.contains_voiceover;

                    return (
                        <div
                            key={i}
                            className={`absolute top-2 bottom-2 rounded-sm opacity-60 hover:opacity-100 transition-opacity
                                ${isVoiceover ? 'bg-indigo-500' : 'bg-sky-500'}
                            `}
                            style={{ left: `${left}%`, width: `${width}%` }}
                            title={`${t.speaker_id}: ${t.transcription.substring(0, 30)}...`}
                        />
                    );
                })}

                {/* Scrubber Head */}
                <div
                    className="absolute top-0 bottom-0 w-0.5 bg-white shadow-[0_0_10px_rgba(255,255,255,0.8)] z-10 pointer-events-none transition-all duration-75"
                    style={{ left: `${(currentTime / duration) * 100}%` }}
                >
                    <div className="absolute -top-1 -left-1.5 w-3.5 h-3.5 bg-white rounded-full shadow-sm transform scale-0 group-hover:scale-100 transition-transform" />
                </div>
            </div>
        </div>
    );
};

window.Timeline = Timeline;
