export const MP4_AUDIO_MIME_TYPES = Object.freeze([
  'video/mp4;codecs=avc1,mp4a.40.2',
  'video/mp4',
]);

export const MP4_VIDEO_MIME_TYPES = Object.freeze([
  'video/mp4;codecs=avc1',
  'video/mp4',
]);

export function chooseMp4MimeType(isTypeSupported, { audio = true } = {}) {
  if (typeof isTypeSupported !== 'function') {
    throw new TypeError('A MediaRecorder support probe is required.');
  }
  const mimeTypes = audio ? MP4_AUDIO_MIME_TYPES : MP4_VIDEO_MIME_TYPES;
  const mimeType = mimeTypes.find((candidate) => isTypeSupported(candidate));
  if (!mimeType) {
    throw new Error('This Electron runtime cannot encode H.264/AAC MP4 video.');
  }
  return mimeType;
}

export function mp4ExportName(sourceName) {
  const stem = String(sourceName || 'video').replace(/\.[^.]+$/, '') || 'video';
  return `${stem}-cut.mp4`;
}

export function clipExportName(index, name) {
  const number = String(index + 1).padStart(2, '0');
  const clean = String(name || '').trim().replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').replace(/[. ]+$/g, '').slice(0, 80);
  return clean ? `${number} - ${clean}` : `clip-${number}`;
}

export function exportCanvasSize(sourceWidth, sourceHeight, preset = 'source') {
  const width = Math.max(2, Math.round(sourceWidth) || 2);
  const height = Math.max(2, Math.round(sourceHeight) || 2);
  const target = {
    '1080': [1920, 1080],
    '720': [1280, 720],
    '480': [854, 480],
  }[preset];
  if (!target) return { width: width & ~1, height: height & ~1 };
  return { width: target[0], height: target[1] };
}
