import { createPreviewLoop, generateSyntheticFreq } from "../utils.ts";

export const category = "classic";

export const params = [
  {
    key: "barCount",
    type: "number",
    default: 16,
    min: 2,
    max: 64,
    label: "amt",
  },
  { key: "barColor", type: "color", default: "#ffffff", label: "fg" },
  { key: "bgColor", type: "color", default: "#000000", label: "bg" },
];

export function draw(
  canvas: HTMLCanvasElement,
  freq: Uint8Array,
  options: Record<string, string | number | HTMLImageElement>,
) {
  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  ctx.fillStyle = String(options.bgColor ?? "#000000");
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  const barCount = Number(options.barCount ?? 16);
  const barColor = String(options.barColor ?? "#ffffff");
  const barWidth = canvas.width / barCount;

  for (let i = 0; i < barCount; i++) {
    const freqIndex = Math.floor((i / barCount) * freq.length);
    const freqAmpl = freq[freqIndex] / 255;
    const barHeight = freqAmpl * canvas.height;

    ctx.fillStyle = barColor;
    ctx.fillRect(i * barWidth, canvas.height - barHeight, barWidth, barHeight);
  }
}

export function preview(
  canvas: HTMLCanvasElement,
  _freq: Uint8Array,
  getOptions: () => Record<string, string | number | HTMLImageElement>,
  fps: number,
) {
  let phase = 0;
  const size = 1024;
  const freq = new Uint8Array(size);

  return createPreviewLoop(canvas, fps, (offscreen, dt) => {
    phase += 3 * dt;
    generateSyntheticFreq(freq, phase);
    draw(offscreen, freq, getOptions());
  });
}
