const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
fitToContainer(canvas);

function fitToContainer(canvas){
  // Make it visually fill the positioned parent
  canvas.style.width ='100%';
  canvas.style.height='100%';
  // ...then set the internal size to match
  canvas.width  = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;
}

let audioContext;
let analyser;
let source;
let dataArray;
let bufferLength;

const TOTAL_BARS = 44 ; // Only 44 bars now
const BARS_AREA_WIDTH = 320; // Width of bars
const MAX_BAR_HEIGHT = 22;   // Max bar height

// window.onload = function() {
//     document.getElementById('my_audio').dispatchEvent(new Event('input', { bubbles: true }));
// }


window.onload = function() {

    const audio = document.getElementById("my_audio");
    audio.controls = false;
    document.body.appendChild(audio);
    audio.play();

    audioContext = new (window.AudioContext || window.webkitAudioContext)();
    source = audioContext.createMediaElementSource(audio);
    analyser = audioContext.createAnalyser();

    source.connect(analyser);
    analyser.connect(audioContext.destination);

    analyser.fftSize = 256;
    bufferLength = analyser.frequencyBinCount;
    dataArray = new Uint8Array(bufferLength);

    animate();

}

function animate() {
  requestAnimationFrame(animate);
  
  analyser.getByteFrequencyData(dataArray);

  // Clear everything (no ghosting)
  ctx.fillStyle = '#000000';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  const step = Math.floor(bufferLength / TOTAL_BARS);
  const barWidth = BARS_AREA_WIDTH / TOTAL_BARS;
  const centerY = canvas.height / 2;
  const centerX = (canvas.width - BARS_AREA_WIDTH) / 2;

  // Draw center line


  ctx.fillStyle = '#ffffff'; // White bars

  // Store top bars heights
  const barHeights = [];

  // Draw top bars
  for (let i = 0; i < TOTAL_BARS; i++) {
    let sum = 0;
    for (let j = 0; j < step; j++) {
      sum += dataArray[(i * step) + j] || 0;
    }
    const average = sum / step;

    const barHeight = (average / 255) * MAX_BAR_HEIGHT;
    barHeights.push(barHeight); // Save for mirroring

    ctx.fillRect(centerX + i * barWidth, centerY-2 - barHeight, barWidth, barHeight);
  }

  // Draw bottom bars (mirror of top)
  for (let i = 0; i < TOTAL_BARS; i++) {
    const mirroredHeight = barHeights[i];
    ctx.fillRect(centerX + i * barWidth, centerY+2, barWidth, mirroredHeight);
  }

}