import "./ui/menu-bar.ts";
import { visualizers } from "./visualizers/index.ts";
import { buildParamsUI, buildVisSelect, currentOptions } from "./ui/params.ts";
import { fitCanvas, startPreview, updateCanvas } from "./ui/preview.ts";
import { handleRender } from "./ui/render.ts";

const main = async () => {
  const canvas = document.querySelector("canvas")!;
  const resSelect = document.querySelector<HTMLSelectElement>("#res-select")!;
  const ratioSelect = document.querySelector<HTMLSelectElement>(
    "#ratio-select",
  )!;
  const select = document.querySelector<HTMLSelectElement>("#vis-select")!;
  const fpsSelect = document.querySelector<HTMLSelectElement>("#fps-select")!;
  const qualitySelect = document.querySelector<HTMLSelectElement>(
    "#quality-select",
  )!;

  globalThis.window.addEventListener("resize", () => fitCanvas(canvas));
  fitCanvas(canvas);

  buildVisSelect(select);

  const onUpdate = () =>
    updateCanvas(
      canvas,
      resSelect,
      ratioSelect,
      select,
      fpsSelect,
      visualizers,
      currentOptions,
    );

  resSelect.addEventListener("change", onUpdate);
  ratioSelect.addEventListener("change", onUpdate);
  fpsSelect.addEventListener("change", () =>
    startPreview(
      select.value,
      canvas,
      fpsSelect,
      visualizers,
      currentOptions,
    ));

  const renderWebmBtn = document.querySelector<HTMLButtonElement>(
    "#render-webm",
  );
  renderWebmBtn!.addEventListener(
    "click",
    () =>
      handleRender(
        canvas,
        fpsSelect,
        qualitySelect,
        select,
        currentOptions,
        "webm",
      ),
  );

  const renderMp4Btn = document.querySelector<HTMLButtonElement>("#render-mp4");
  renderMp4Btn!.addEventListener(
    "click",
    () =>
      handleRender(
        canvas,
        fpsSelect,
        qualitySelect,
        select,
        currentOptions,
        "mp4",
      ),
  );

  select.addEventListener("change", () => {
    buildParamsUI(select.value);
    startPreview(
      select.value,
      canvas,
      fpsSelect,
      visualizers,
      currentOptions,
    );
  });

  await document.fonts.ready;
  buildParamsUI(select.value);
  startPreview(
    select.value,
    canvas,
    fpsSelect,
    visualizers,
    currentOptions,
  );
};

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", main);
} else {
  main();
}
