export interface QueueChapter {
  id: string;
  position: number;
  title: string;
  segments: Array<{ id: string; position: number; included: boolean }>;
}

export interface QueueItem {
  chapterId: string;
  chapterTitle: string;
  segmentId: string;
}

export function buildPlaybackQueue(chapters: readonly QueueChapter[]): QueueItem[] {
  return [...chapters]
    .sort((left, right) => left.position - right.position)
    .flatMap((chapter) => [...chapter.segments]
      .sort((left, right) => left.position - right.position)
      .filter((segment) => segment.included)
      .map((segment) => ({
        chapterId: chapter.id,
        chapterTitle: chapter.title,
        segmentId: segment.id,
      })));
}

export function moveQueue(index: number, delta: number, length: number): number {
  if (length < 1) return 0;
  return Math.max(0, Math.min(length - 1, Math.round(index + delta)));
}

export function seekAcrossQueue(input: {
  index: number;
  offsetMs: number;
  deltaMs: number;
  durations: readonly number[];
}): { index: number; offsetMs: number } {
  if (!input.durations.length) return { index: 0, offsetMs: 0 };
  let index = moveQueue(input.index, 0, input.durations.length);
  let offsetMs = Math.max(0, input.offsetMs) + input.deltaMs;
  while (offsetMs < 0 && index > 0) {
    index -= 1;
    offsetMs += Math.max(0, input.durations[index] ?? 0);
  }
  while (offsetMs > Math.max(0, input.durations[index] ?? 0) && index < input.durations.length - 1) {
    offsetMs -= Math.max(0, input.durations[index] ?? 0);
    index += 1;
  }
  return {
    index,
    offsetMs: Math.max(0, Math.min(Math.max(0, input.durations[index] ?? 0), offsetMs)),
  };
}
