(function() {
  const canvas       = document.getElementById('matrix-background');
  const ctx          = canvas.getContext('2d');
  const cfg          = window.mfcSettings || {};
  const audioEnabled = cfg.audioEnabled !== false; // defaults to true
  const audio        = audioEnabled ? document.getElementById('matrix-audio')   : null;
  const muteBtn      = audioEnabled ? document.getElementById('matrix-mute-btn'): null;

  const fontSize   = cfg.fontSize   || 16;
  const color      = cfg.color      || '#0F0';
  const interval   = cfg.interval   || 50;
  const opacity    = typeof cfg.opacity === 'number' ? cfg.opacity : 0.05;
  const letters    = (typeof cfg.characters === 'string' && cfg.characters.length)
                     ? cfg.characters
                     : 'アァカサタナハマヤャラワガザダバパイィキシチニヒミリヰギジヂビピウゥクスツヌフムユュルグズヅブプエェケセテネヘメレヱゲゼデベペオォコソトノホモヨョロゴゾドボポヴッン';
  const pauseDelay = cfg.pauseDelay  || 2000; // ms

  let width, height, columns, drops, dpr;
  let lastDrawTime  = performance.now();
  let lastMouseMove = performance.now();
  let paused        = false;

  // --- Initialization ---
  function init() {
    dpr = window.devicePixelRatio || 1;
    width  = window.innerWidth;
    height = window.innerHeight;

    canvas.width  = width * dpr;
    canvas.height = height * dpr;
    canvas.style.width  = width + 'px';
    canvas.style.height = height + 'px';

    ctx.scale(dpr, dpr);

    columns = Math.floor(width / fontSize);
    drops   = Array(columns).fill(1);
  }

  window.addEventListener('resize', init);
  window.addEventListener('mousemove', () => {
    paused = true;
    lastMouseMove = performance.now();
    canvas.style.display = 'block';  // show again after pause
  });
  window.addEventListener('click', () => {
    canvas.style.display = 'none';
    pauseAudio();
  });

  // --- Mute Button Logic ---
  if (muteBtn && audio) {
    const updateIcon = () => {
      muteBtn.textContent = audio.muted ? '🔇' : '🔊';
    };
    updateIcon();
    muteBtn.addEventListener('click', () => {
      audio.muted = !audio.muted;
      updateIcon();
    });
  }

  init();

  // --- Animation Loop ---
  function tick(now) {
    // pause when tab hidden
    if (document.hidden) {
      lastDrawTime = now;
      pauseAudio();
      requestAnimationFrame(tick);
      return;
    }

    // handle mouse-move pause
    if (paused) {
      pauseAudio();
      if (now - lastMouseMove >= pauseDelay) {
        paused = false;
        lastDrawTime = now;
      } else {
        requestAnimationFrame(tick);
        return;
      }
    }

    // throttle to configured interval
    if (now - lastDrawTime >= interval) {
      draw();
      playAudio();
      lastDrawTime = now;
    }

    requestAnimationFrame(tick);
  }

  // --- Drawing Function ---
  function draw() {
    ctx.fillStyle = `rgba(0, 0, 0, ${opacity})`;
    ctx.fillRect(0, 0, width, height);

    ctx.fillStyle = color;
    ctx.font      = `${fontSize}px monospace`;

    for (let i = 0; i < columns; i++) {
      const char = letters.charAt(Math.floor(Math.random() * letters.length));
      ctx.fillText(char, i * fontSize, drops[i] * fontSize);

      if (drops[i] * fontSize > height && Math.random() > 0.975) {
        drops[i] = 0;
      }
      drops[i]++;
    }
  }

  // --- Audio Helpers ---
  function playAudio() {
    if (audioEnabled && audio && audio.paused) {
      audio.play().catch(() => {/* autoplay may be blocked */});
    }
  }
  function pauseAudio() {
    if (audioEnabled && audio && !audio.paused) {
      audio.pause();
    }
  }

  // start!
  requestAnimationFrame(tick);
})();
