// Snap-to-edges utility for the timeline editor.

import type { Clip } from '@/types';
import { SNAP_PX } from './constants';

/**
 * Snap `t` (seconds) to nearby clip edges or the playhead when within
 * `SNAP_PX / zoom` seconds. Returns rounded, non-negative seconds.
 */
export function snapTime(
  t: number,
  zoom: number,
  currentTime: number,
  clips: Clip[],
  snappingEnabled: boolean,
): number {
  if (!snappingEnabled) return Math.max(0, t);
  const targets = [currentTime];
  for (const c of clips) {
    targets.push(c.start);
    targets.push(c.start + c.duration);
  }
  const threshold = SNAP_PX / zoom;
  for (const tg of targets) {
    if (Math.abs(t - tg) <= threshold) return tg;
  }
  return Math.max(0, Math.round(t * 100) / 100);
}