/**
 * Pure, DOM-free playback helpers for the video quad-viewer. Fully unit-testable —
 * no React, no `<video>`, no VTK. The hook (`usePlaybackSync`) and the components
 * compose these.
 */
import type { QuadIndex, ExpandedView } from './types';

/**
 * Clamp a time to the playable range [0, duration].
 * Guards NaN / negative / non-finite inputs and a 0 (or unknown) duration → 0.
 */
export function clampTime(t: number, duration: number): number {
  if (!Number.isFinite(t) || t < 0) return 0;
  if (!Number.isFinite(duration) || duration <= 0) return 0;
  return t > duration ? duration : t;
}

/**
 * Format seconds as "m:ss" (e.g. 75 → "1:15"). Guards NaN / negative / non-finite → "0:00".
 */
export function formatTimecode(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds < 0) return '0:00';
  const total = Math.floor(seconds);
  const m = Math.floor(total / 60);
  const s = total % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

/** Vietnamese labels for the four quad panes. Diacritics preserved. */
export const QUAD_LABELS: Record<QuadIndex, string> = {
  0: 'Video gốc',
  1: 'Bản đồ độ sâu',
  2: 'Mặt nạ phân vùng',
  3: 'Tái tạo 3D',
};

/**
 * Whether a quad is time-driven (synced to the master video clock).
 * True for 0/1/2 (video, depth, segmentation); false for 3 (the 3D recon
 * placeholder is not a time-based stream).
 */
export function isTimeBased(q: QuadIndex): boolean {
  return q === 0 || q === 1 || q === 2;
}

/**
 * Quad render order. When a pane is expanded, return [expanded, ...the other three
 * in ascending order] — main first, then the three thumbnails. When null, the
 * natural 2×2 order [0,1,2,3].
 */
export function expandedOrder(expanded: ExpandedView): QuadIndex[] {
  const all: QuadIndex[] = [0, 1, 2, 3];
  if (expanded === null) return all;
  return [expanded, ...all.filter((i) => i !== expanded)];
}
