export function firstVideoFrameURL(url?: string) {
  if (!url) return "";
  return `${url.split("#", 1)[0]}#t=0.001`;
}

export async function readAudioDurationMs(file: File): Promise<number | undefined> {
  const url = URL.createObjectURL(file);
  try {
    return await new Promise((resolve) => {
      const audio = document.createElement("audio");
      audio.preload = "metadata";
      audio.onloadedmetadata = () =>
        resolve(Number.isFinite(audio.duration) ? Math.round(audio.duration * 1000) : undefined);
      audio.onerror = () => resolve(undefined);
      audio.src = url;
    });
  } finally {
    URL.revokeObjectURL(url);
  }
}

export function formatMediaDuration(durationMs?: number) {
  const seconds = Number(durationMs || 0) / 1000;
  if (!Number.isFinite(seconds) || seconds <= 0) return "";
  return `${seconds.toFixed(1).replace(/\.0$/, "")} 秒`;
}
