import type { TranscriptSegment } from '@shumai/dtos' export function createTranscriptTimeline(segments: TranscriptSegment[]) { const ordered = [...segments].sort((a, b) => a.startMs - b.startMs) let latestEndMs = 0 const timeline = ordered.map((segment) => { latestEndMs = Math.max(latestEndMs, segment.endMs) return { segment, latestEndMs } }) return (playbackTimeMs: number): string | undefined => { // Remove floating-point noise around millisecond boundaries while keeping microsecond precision. const timeMs = Math.round(playbackTimeMs * 1000) / 1000 let first = 0 let last = timeline.length while (first < last) { const middle = Math.floor((first + last) / 2) if (timeline[middle].segment.startMs <= timeMs) first = middle + 1 else last = middle } // Prefer the most recent start when segments overlap. The running maximum bounds // the backward scan even in long gaps or after the last segment. for (let index = first - 1; index >= 0; index--) { const { segment, latestEndMs } = timeline[index] if (latestEndMs <= timeMs) break if (segment.endMs > timeMs) return segment.id } } }