/**
 * Pop-out Media Player
 * Handles navigation, keyboard shortcuts, fullscreen, always-on-top, and dynamic window sizing
 */

(function() {
  'use strict';

  // State management
  let focusInterval = null;
  let autoAdvanceTimer = null;
  let preloadedNext = null;
  let preloadedPrev = null;
  const AUTO_ADVANCE_DELAY = 60000; // 60 seconds for images/PDFs

  // Get media element
  const media = document.getElementById('media');
  const alwaysOnTopBtn = document.getElementById('alwaysOnTopBtn');
  const autoResizeBtn = document.getElementById('autoResizeBtn');
  const playPauseBtn = document.getElementById('playPauseBtn');

  /**
   * Navigate to another product
   */
  window.navigate = function(productId) {
    if (productId) {
      window.location.href = '/player/' + productId;
    }
  };

  /**
   * Toggle play/pause
   */
  window.togglePlayPause = function() {
    if (media && (media.tagName === 'VIDEO' || media.tagName === 'AUDIO')) {
      if (media.paused) {
        media.play();
      } else {
        media.pause();
      }
    }
  };

  /**
   * Toggle fullscreen mode
   */
  window.toggleFullscreen = function() {
    if (!document.fullscreenElement) {
      // Request fullscreen on the player container, not the whole document
      const container = document.getElementById('playerContainer');
      if (container) {
        container.requestFullscreen().catch(err => {
          console.error('Error attempting to enable fullscreen:', err);
        });
      }
    } else {
      document.exitFullscreen();
    }
  };

  /**
   * Toggle always-on-top behavior
   */
  window.toggleAlwaysOnTop = function() {
    const current = localStorage.getItem('player_always_on_top') === 'true';
    const newValue = !current;
    localStorage.setItem('player_always_on_top', newValue.toString());

    if (newValue) {
      startAlwaysOnTop();
    } else {
      stopAlwaysOnTop();
    }

    updateAlwaysOnTopButton(newValue);
  };

  /**
   * Toggle auto-resize behavior
   */
  window.toggleAutoResize = function() {
    const current = localStorage.getItem('player_auto_resize') !== 'false'; // Default true
    const newValue = !current;
    localStorage.setItem('player_auto_resize', newValue.toString());
    updateAutoResizeButton(newValue);

    // If turning on, resize now
    if (newValue) {
      resizeWindowToMedia();
    }
  };

  /**
   * Start always-on-top behavior (window.focus() on interval)
   */
  function startAlwaysOnTop() {
    if (focusInterval) {
      clearInterval(focusInterval);
    }
    // Focus window every 250ms to aggressively keep it on top
    window.focus(); // Focus immediately
    focusInterval = setInterval(() => {
      window.focus();
    }, 250);
  }

  /**
   * Stop always-on-top behavior
   */
  function stopAlwaysOnTop() {
    if (focusInterval) {
      clearInterval(focusInterval);
      focusInterval = null;
    }
  }

  /**
   * Update always-on-top button appearance
   */
  function updateAlwaysOnTopButton(isActive) {
    if (alwaysOnTopBtn) {
      if (isActive) {
        alwaysOnTopBtn.classList.add('active');
        alwaysOnTopBtn.textContent = '📌 On Top';
      } else {
        alwaysOnTopBtn.classList.remove('active');
        alwaysOnTopBtn.textContent = '📌 On Top';
      }
    }
  }

  /**
   * Update fullscreen button appearance
   */
  function updateFullscreenButton() {
    if (fullscreenBtn) {
      if (document.fullscreenElement) {
        fullscreenBtn.textContent = '⛶ Exit';
      } else {
        fullscreenBtn.textContent = '⛶ Full';
      }
    }
  }

  /**
   * Update auto-resize button appearance
   */
  function updateAutoResizeButton(isActive) {
    if (autoResizeBtn) {
      if (isActive) {
        autoResizeBtn.classList.add('active');
        autoResizeBtn.textContent = '↔ Resize';
      } else {
        autoResizeBtn.classList.remove('active');
        autoResizeBtn.textContent = '↔ Resize';
      }
    }
  }

  /**
   * Update play/pause button appearance
   */
  function updatePlayPauseButton() {
    if (playPauseBtn && media && (media.tagName === 'VIDEO' || media.tagName === 'AUDIO')) {
      if (media.paused) {
        playPauseBtn.textContent = '▶';
      } else {
        playPauseBtn.textContent = '⏸';
      }
    }
  }

  /**
   * Start auto-advance timer for images and PDFs
   */
  function startAutoAdvance() {
    // Clear any existing timer
    stopAutoAdvance();

    // Only auto-advance if there's a next product
    if (!window.playerData || !window.playerData.nextProductId) {
      return;
    }

    // Set timer to advance after delay
    autoAdvanceTimer = setTimeout(() => {
      if (window.playerData && window.playerData.nextProductId) {
        navigate(window.playerData.nextProductId);
      }
    }, AUTO_ADVANCE_DELAY);
  }

  /**
   * Stop auto-advance timer
   */
  function stopAutoAdvance() {
    if (autoAdvanceTimer) {
      clearTimeout(autoAdvanceTimer);
      autoAdvanceTimer = null;
    }
  }

  /**
   * Preload next video for instant playback
   */
  async function preloadNext() {
    if (!window.playerData || !window.playerData.nextProductId) {
      return;
    }

    try {
      const response = await fetch(`/player/${window.playerData.nextProductId}`);
      const html = await response.text();
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const mediaEl = doc.querySelector('video, audio');

      if (mediaEl && mediaEl.src) {
        // Create hidden preload element
        if (preloadedNext) {
          preloadedNext.remove();
        }

        preloadedNext = document.createElement(mediaEl.tagName.toLowerCase());
        preloadedNext.src = mediaEl.src;
        preloadedNext.preload = 'auto';
        preloadedNext.style.display = 'none';
        document.body.appendChild(preloadedNext);
      }
    } catch (err) {
      console.log('Could not preload next video:', err);
    }
  }

  /**
   * Preload previous video (lower priority)
   */
  async function preloadPrev() {
    if (!window.playerData || !window.playerData.prevProductId) {
      return;
    }

    try {
      const response = await fetch(`/player/${window.playerData.prevProductId}`);
      const html = await response.text();
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const mediaEl = doc.querySelector('video, audio');

      if (mediaEl && mediaEl.src) {
        // Create hidden preload element
        if (preloadedPrev) {
          preloadedPrev.remove();
        }

        preloadedPrev = document.createElement(mediaEl.tagName.toLowerCase());
        preloadedPrev.src = mediaEl.src;
        preloadedPrev.preload = 'metadata'; // Only metadata, not full video
        preloadedPrev.style.display = 'none';
        document.body.appendChild(preloadedPrev);
      }
    } catch (err) {
      console.log('Could not preload previous video:', err);
    }
  }

  /**
   * Resize window to match media aspect ratio
   */
  function resizeWindowToMedia() {
    // Check if auto-resize is enabled (default true)
    const autoResize = localStorage.getItem('player_auto_resize') !== 'false';
    if (!autoResize) {
      return;
    }

    let width, height;

    if (media.videoWidth && media.videoHeight) {
      // Video dimensions
      width = media.videoWidth;
      height = media.videoHeight;
    } else if (media.naturalWidth && media.naturalHeight) {
      // Image dimensions
      width = media.naturalWidth;
      height = media.naturalHeight;
    } else {
      // Unknown dimensions, skip resize
      return;
    }

    // Minimum size to fit controls properly
    const minWidth = 600;
    const minHeight = 400;

    // Constrain to screen size (90% of available space)
    const maxWidth = screen.width * 0.9;
    const maxHeight = screen.height * 0.9;

    let finalWidth = Math.max(width, minWidth);
    let finalHeight = height;

    // Maintain aspect ratio while respecting minimums
    if (width < minWidth) {
      finalHeight = (height * minWidth) / width;
    }

    // Scale down if too large
    if (finalWidth > maxWidth) {
      const scale = maxWidth / finalWidth;
      finalWidth = maxWidth;
      finalHeight = finalHeight * scale;
    }

    if (finalHeight > maxHeight) {
      const scale = maxHeight / finalHeight;
      finalHeight = maxHeight;
      finalWidth = finalWidth * scale;
    }

    // Ensure we still meet minimums after scaling
    finalWidth = Math.max(finalWidth, minWidth);
    finalHeight = Math.max(finalHeight, minHeight);

    // Add extra space for controls overlay (~100px)
    const controlsHeight = 100;

    // Resize window (some browsers may restrict this)
    try {
      window.resizeTo(
        Math.round(finalWidth),
        Math.round(finalHeight + controlsHeight)
      );
    } catch (err) {
      console.warn('Could not resize window:', err);
    }
  }

  /**
   * Keyboard event handler
   */
  function handleKeydown(e) {
    switch(e.key) {
      case 'Escape':
        window.close();
        break;
      case ' ':
      case 'Spacebar':
        e.preventDefault();
        togglePlayPause();
        break;
      case 'ArrowLeft':
        e.preventDefault();
        if (window.playerData && window.playerData.prevProductId) {
          navigate(window.playerData.prevProductId);
        }
        break;
      case 'ArrowRight':
        e.preventDefault();
        if (window.playerData && window.playerData.nextProductId) {
          navigate(window.playerData.nextProductId);
        }
        break;
      case 't':
      case 'T':
        e.preventDefault();
        toggleAlwaysOnTop();
        break;
      case 'r':
      case 'R':
        e.preventDefault();
        toggleAutoResize();
        break;
      case 'g':
      case 'G':
        e.preventDefault();
        if (typeof goToProductPage === 'function') {
          goToProductPage();
        }
        break;
      case 'p':
      case 'P':
        e.preventDefault();
        if (typeof togglePip === 'function') {
          togglePip();
        }
        break;
      case 'k':
      case 'K':
        e.preventDefault();
        if (typeof toggleKaraoke === 'function') {
          toggleKaraoke();
        }
        break;
    }
  }

  /**
   * Initialize player on page load
   */
  function init() {
    // Check localStorage for always-on-top setting
    const alwaysOnTop = localStorage.getItem('player_always_on_top') === 'true';
    if (alwaysOnTop) {
      startAlwaysOnTop();
    }
    updateAlwaysOnTopButton(alwaysOnTop);

    // Check localStorage for auto-resize setting (default true)
    const autoResize = localStorage.getItem('player_auto_resize') !== 'false';
    updateAutoResizeButton(autoResize);

    // Set up keyboard event listener
    document.addEventListener('keydown', handleKeydown);

    // Cancel auto-advance on scroll (user is reading the PDF)
    document.addEventListener('wheel', () => {
      // User is scrolling, they're reading, cancel auto-advance
      stopAutoAdvance();
    });

    // Cancel auto-advance on scroll events
    window.addEventListener('scroll', () => {
      stopAutoAdvance();
    });

    // Resize window when media loads (for video and images)
    if (media) {
      if (media.tagName === 'VIDEO' || media.tagName === 'AUDIO') {
        media.addEventListener('loadedmetadata', () => {
          resizeWindowToMedia();
          // Preload next video immediately for instant playback
          preloadNext();
          // Preload previous after a short delay (lower priority)
          setTimeout(preloadPrev, 2000);
        });
        // Update play/pause button when media state changes
        media.addEventListener('play', updatePlayPauseButton);
        media.addEventListener('pause', updatePlayPauseButton);
        // Auto-advance when video/audio ends
        media.addEventListener('ended', () => {
          if (window.playerData && window.playerData.nextProductId) {
            navigate(window.playerData.nextProductId);
          }
        });
        // Initial update
        updatePlayPauseButton();
      } else if (media.tagName === 'IMG') {
        media.addEventListener('load', () => {
          resizeWindowToMedia();
          // Auto-advance after 60 seconds for images
          startAutoAdvance();
        });
      } else if (media.tagName === 'IFRAME') {
        // For PDFs
        resizeWindowToMedia();
        // Auto-advance after 60 seconds for PDFs
        startAutoAdvance();

        // Try to detect scrolling in iframe (may not work due to CORS)
        try {
          media.contentWindow.addEventListener('scroll', () => {
            // User scrolled the PDF, cancel auto-advance
            stopAutoAdvance();
          });
        } catch (err) {
          // CORS blocked, can't detect scroll
          console.log('Cannot detect PDF scroll due to CORS');
        }
      }
    }

    // Cleanup on window close
    window.addEventListener('beforeunload', () => {
      stopAlwaysOnTop();
    });
  }

  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();
