// This script runs in the PAGE context (injected via <script src>).
// It calls the MYM display API to set CloudFront signed cookies,
// then uses HLS.js with withCredentials to play the video.

(function() {
  var hlsInstances = {};

  function startHlsPlayback(videoId, m3u8Url) {
    var video = document.getElementById(videoId);
    if (!video) return;

    if (hlsInstances[videoId]) {
      hlsInstances[videoId].destroy();
      delete hlsInstances[videoId];
    }

    if (typeof Hls !== 'undefined' && Hls.isSupported()) {
      var hls = new Hls({
        xhrSetup: function(xhr) { xhr.withCredentials = true; }
      });
      hls.loadSource(m3u8Url);
      hls.attachMedia(video);
      hls.on(Hls.Events.MANIFEST_PARSED, function() {
        console.log('[HLS page] Manifest parsed, starting playback');
        video.play().catch(function() {});
      });
      hls.on(Hls.Events.ERROR, function(event, data) {
        console.error('[HLS page] Error:', data.type, data.details);
        if (data.fatal) {
          document.dispatchEvent(new CustomEvent('mym-hls-error', {
            detail: { videoId: videoId, error: data.details }
          }));
        }
      });
      hlsInstances[videoId] = hls;
    } else if (video.canPlayType && video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = m3u8Url;
      video.play().catch(function() {});
    } else {
      console.error('[HLS page] HLS not supported');
    }
  }

  window.addEventListener('mym-hls-play', async function(e) {
    var videoId = e.detail.videoId;
    var m3u8Url = e.detail.m3u8Url;
    var mediaId = e.detail.mediaId;
    var userToken = e.detail.userToken;
    var video = document.getElementById(videoId);

    if (!video) {
      console.error('[HLS page] Video element not found:', videoId);
      return;
    }

    console.log('[HLS page] Received event - mediaId:', mediaId, 'userToken:', userToken ? 'present' : 'missing');
    
    // Log all available cookies
    console.log('[HLS page] Available cookies:', document.cookie);
    
    if (!userToken || !mediaId) {
      console.warn('[HLS page] Missing userToken or mediaId, trying playback anyway...');
      startHlsPlayback(videoId, m3u8Url);
      return;
    }

    // Call /display API to refresh CloudFront cookies
    try {
      var referer = window.location.href;
      var displayUrl = 'https://public.mym.fans/api/medias/' + mediaId + '/display?referer=' + encodeURIComponent(referer) + '&user_token=' + userToken;
      
      console.log('[HLS page] Calling /display to refresh CloudFront cookies...');
      
      var response = await fetch(displayUrl, {
        method: 'GET',
        credentials: 'omit',
        mode: 'cors'
      });
      
      console.log('[HLS page] Display API response:', response.status);
      
      // Wait a bit for cookies to propagate
      await new Promise(function(resolve) { setTimeout(resolve, 500); });
    } catch (err) {
      console.warn('[HLS page] Display API error:', err);
    }

    // Fetch m3u8 with credentials to use CloudFront cookies
    console.log('[HLS page] Fetching m3u8 with credentials...');
    try {
      var m3u8Response = await fetch(m3u8Url, {
        credentials: 'include',
        mode: 'cors'
      });
      
      if (!m3u8Response.ok) {
        throw new Error('M3U8 fetch failed: ' + m3u8Response.status);
      }
      
      var m3u8Content = await m3u8Response.text();
      console.log('[HLS page] M3U8 fetched successfully, creating blob...');
      
      // Create blob URL from m3u8 content
      var m3u8Blob = new Blob([m3u8Content], { type: 'application/vnd.apple.mpegurl' });
      var blobUrl = URL.createObjectURL(m3u8Blob);
      
      console.log('[HLS page] Blob URL created:', blobUrl.substring(0, 50) + '...');
      
      // Use blob URL for playback
      startHlsPlayback(videoId, blobUrl);
    } catch (err) {
      console.error('[HLS page] Error fetching m3u8:', err);
      console.log('[HLS page] Falling back to direct URL...');
      startHlsPlayback(videoId, m3u8Url);
    }
  });

  document.addEventListener('mym-hls-destroy', function(e) {
    var videoId = e.detail.videoId;
    if (hlsInstances[videoId]) {
      hlsInstances[videoId].destroy();
      delete hlsInstances[videoId];
    }
  });
})();
