const card = document.getElementById('birthdayCard');
const balloonContainer = document.getElementById('balloonContainer');
const bgMusic = document.getElementById('bgMusic');
const video = document.getElementById('birthdayVideo');

let balloonInterval = null;

/* ================= CLICK CARD ================= */
if (card) {
  card.addEventListener('click', function () {
    this.classList.toggle('active');

    if (this.classList.contains('active')) {
      fireConfetti();
      startBalloons();

      // pastikan musik mulai jika sebelumnya diblokir browser
      if (bgMusic) bgMusic.play().catch(() => {});
    } else {
      stopBalloons();
    }
  });
}

/* ================= CONFETTI ================= */
function fireConfetti() {
  const duration = 3000;
  const end = Date.now() + duration;

  (function frame() {
    confetti({
      particleCount: 4,
      angle: 60,
      spread: 55,
      origin: { x: 0 },
      colors: ['#1BBC9B', '#C0392B', '#FDE3A7'],
    });

    confetti({
      particleCount: 4,
      angle: 120,
      spread: 55,
      origin: { x: 1 },
      colors: ['#1BBC9B', '#C0392B', '#FDE3A7'],
    });

    if (Date.now() < end) requestAnimationFrame(frame);
  })();
}

/* ================= GALLERY ANIMATION ================= */
document.querySelectorAll('.gallery img').forEach((img) => {
  img.addEventListener('mouseenter', () => {
    img.style.zIndex = '5';
  });

  img.addEventListener('mouseleave', () => {
    img.style.zIndex = '1';
  });
});

/* ================= BALLOON SPAWN ================= */
function startBalloons() {
  if (balloonInterval) return;
  balloonInterval = setInterval(createBalloon, 500);
}

function stopBalloons() {
  clearInterval(balloonInterval);
  balloonInterval = null;
  if (balloonContainer) balloonContainer.innerHTML = '';
}

function createBalloon() {
  if (!balloonContainer) return;

  const balloon = document.createElement('img');

  const balloons = [
    'image/ballon1.svg',
    'image/ballon2.svg',
    'image/ballon3.svg',
    'image/hat.svg',
  ];

  balloon.src = balloons[Math.floor(Math.random() * balloons.length)];
  balloon.className = 'balloon';
  balloon.style.left = Math.random() * 100 + 'vw';

  const duration = 6 + Math.random() * 5;
  balloon.style.animationDuration = duration + 's';

  balloonContainer.appendChild(balloon);

  setTimeout(() => balloon.remove(), duration * 1000);
}

/* ================= MUSIC CONTROL ================= */
if (bgMusic) {
  bgMusic.volume = 0.5;

  window.addEventListener('load', () => {
    bgMusic.play().catch(() => {});
  });
}

/* ================= VIDEO CONTROL ================= */
if (video && bgMusic) {
  video.addEventListener('play', () => {
    bgMusic.pause();
  });

  video.addEventListener('ended', () => {
    bgMusic.play().catch(() => {});
  });

  video.addEventListener('pause', () => {
    if (video.currentTime < video.duration) {
      bgMusic.play().catch(() => {});
    }
  });
}
