(function () {
  const init = async () => {
    const player = document.getElementById('player');
    if (!player) return;

    let isVip = false;
    const userId = localStorage.getItem('film_userId');
    if (userId) {
      try {
        const res = await fetch(`/api/user?id=${encodeURIComponent(userId)}`);
        const data = await res.json();
        isVip = (data?.vipLevel || 0) > 0;
      } catch {}
    }

    let banners;
    try {
      const res = await fetch('/api/banners?placement=PRE_ROLL');
      const data = await res.json();
      if (!Array.isArray(data)) return;
      banners = data;
    } catch {
      return;
    }

    const banner = banners.find((item) => {
      if (item.type !== 'PREROLL_VIDEO' && item.type !== 'PREROLL_BANNER') return false;
      if (item.targetUser === 'REGULAR' && isVip) return false;
      return true;
    });

    if (!banner) return;
    const key = `pre_roll_${banner.id}`;
    if (sessionStorage.getItem(key)) return;

    const wasPlaying = !player.paused;
    try { player.pause(); } catch {}

    const overlay = document.createElement('div');
    overlay.style.position = 'fixed';
    overlay.style.inset = '0';
    overlay.style.zIndex = '80';
    overlay.style.background = 'rgba(0,0,0,0.9)';
    overlay.style.display = 'flex';
    overlay.style.alignItems = 'center';
    overlay.style.justifyContent = 'center';
    overlay.style.flexDirection = 'column';
    overlay.style.gap = '12px';

    const box = document.createElement('div');
    box.style.maxWidth = '90vw';
    box.style.maxHeight = '70vh';
    box.style.display = 'flex';
    box.style.alignItems = 'center';
    box.style.justifyContent = 'center';
    box.style.borderRadius = '16px';
    box.style.overflow = 'hidden';
    box.style.background = 'rgba(255,255,255,0.06)';
    box.style.border = '1px solid rgba(255,255,255,0.12)';

    let mediaEl;
    if (banner.type === 'PREROLL_VIDEO' && banner.videoUrl) {
      const video = document.createElement('video');
      video.src = banner.videoUrl;
      video.autoplay = true;
      video.muted = true;
      video.playsInline = true;
      video.style.maxWidth = '90vw';
      video.style.maxHeight = '70vh';
      mediaEl = video;
    } else if (banner.imageUrl) {
      const img = document.createElement('img');
      img.src = banner.imageUrl;
      img.alt = banner.title || 'Ad';
      img.style.maxWidth = '90vw';
      img.style.maxHeight = '70vh';
      mediaEl = img;
    }

    if (!mediaEl) return;
    if (banner.linkUrl) {
      const link = document.createElement('a');
      link.href = banner.linkUrl;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.appendChild(mediaEl);
      box.appendChild(link);
    } else {
      box.appendChild(mediaEl);
    }

    const skip = document.createElement('button');
    skip.style.padding = '8px 16px';
    skip.style.borderRadius = '999px';
    skip.style.border = '1px solid rgba(255,255,255,0.2)';
    skip.style.background = 'rgba(0,0,0,0.6)';
    skip.style.color = '#fff';
    skip.style.fontSize = '12px';
    skip.style.cursor = 'pointer';
    skip.disabled = true;

    let countdown = 5;
    skip.textContent = `Lewati dalam ${countdown}s`;

    const timer = setInterval(() => {
      countdown -= 1;
      if (countdown <= 0) {
        clearInterval(timer);
        skip.disabled = false;
        skip.textContent = 'Lewati Iklan';
      } else {
        skip.textContent = `Lewati dalam ${countdown}s`;
      }
    }, 1000);

    const finish = () => {
      clearInterval(timer);
      overlay.remove();
      sessionStorage.setItem(key, '1');
      if (wasPlaying) {
        try { player.play(); } catch {}
      }
    };

    skip.addEventListener('click', finish);

    if (mediaEl.tagName === 'VIDEO') {
      mediaEl.addEventListener('ended', finish);
    }

    overlay.appendChild(box);
    overlay.appendChild(skip);
    document.body.appendChild(overlay);
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
