/*
 * As legendas das aulas. O player só lê WebVTT; o .srt (o formato mais comum)
 * vira .vtt aqui: o cabeçalho, o ponto no lugar da vírgula dos milésimos e
 * só os dois tempos na linha do tempo. Arquivo salvo no Windows (latin-1)
 * também abre com os acentos certos.
 */

/* Os bytes do arquivo em texto: UTF-8 quando for; senão, Windows-1252. */
export function textoDaLegenda(bytes: Uint8Array): string {
  let texto: string;
  try {
    texto = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
  } catch {
    texto = new TextDecoder("windows-1252").decode(bytes);
  }
  return texto.replace(/^\uFEFF/, "");
}

const TEMPO = /(\d{1,2}:)?(\d{1,2}):(\d{2})[,.](\d{1,3})/g;

/* "0:01:02,5" → "00:01:02.500". */
function tempoDoVtt(horas: string | undefined, minutos: string, segundos: string, milesimos: string): string {
  const h = (horas ?? "0:").slice(0, -1).padStart(2, "0");
  return `${h}:${minutos.padStart(2, "0")}:${segundos}.${milesimos.padEnd(3, "0")}`;
}

/* O texto da legenda (.vtt ou .srt) pronto para o player. */
export function vttDaLegenda(texto: string): string {
  const limpo = texto.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").replace(/\u0000/g, "");
  if (/^WEBVTT(?:[ \t\n]|$)/.test(limpo)) return limpo.endsWith("\n") ? limpo : `${limpo}\n`;
  const linhas = limpo.split("\n").map((linha) => {
    if (!linha.includes("-->")) return linha;
    const tempos = Array.from(linha.matchAll(TEMPO)).slice(0, 2);
    /* "-->" no meio da fala quebraria a legenda: vira uma seta. */
    if (tempos.length < 2) return linha.replace(/-->/g, "→");
    const [inicio, fim] = tempos.map((t) => tempoDoVtt(t[1], t[2], t[3], t[4]));
    return `${inicio} --> ${fim}`;
  });
  return `WEBVTT\n\n${linhas.join("\n").trim()}\n`;
}
