<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ product.title }} - Media Player</title>
  <link rel="stylesheet" href="/static/css/common.css">
  <style>
    /* Reset body styles for fullscreen player */
    body {
      margin: 0;
      padding: 0;
      background: #000;
      overflow: hidden;
      font-family: sans-serif;
    }

    /* Player container - CSS Grid layout */
    .player-container {
      display: grid;
      grid-template-areas: "media";
      width: 100vw;
      height: 100vh;
      position: relative;
    }

    /* Media element styles - always maintain aspect ratio */
    #media {
      grid-area: media;
      width: 100%;
      height: 100%;
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
      object-position: center;
    }

    /* For images, ensure aspect ratio is preserved */
    img#media {
      display: block;
    }

    /* For documents (PDFs), fill the viewport */
    iframe#media {
      border: none;
    }

    /* Mobile optimizations */
    @media (max-width: 600px) {
      .controls-grid {
        padding: 1rem;
        gap: 0.5rem;
        font-size: 0.9rem;
        grid-template-columns: 1fr 1fr 1fr;
      }

      .controls-grid button {
        padding: 0.6rem 0.8rem;
        font-size: 0.9rem;
        min-width: 80px;
      }

      .controls-grid button.nav-btn,
      .controls-grid button.play-btn {
        font-size: 1.3rem;
        padding: 0.8rem;
      }

      .product-title {
        font-size: 1rem;
        padding: 0.4rem 0.8rem;
      }

      /* Hide desktop-only buttons on mobile */
      #autoResizeBtn,
      #alwaysOnTopBtn {
        display: none;
      }

      /* Adjust grid for mobile - only show essential buttons */
      .controls-grid {
        grid-template-columns: 1fr 1fr 1fr;
        grid-template-rows: auto auto;
      }
    }

    /* Player controls overlay - centered grid */
    .player-controls {
      grid-area: media;
      display: grid;
      place-items: center;
      z-index: 10;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.3s;
    }

    /* Show controls on hover for desktop */
    @media (min-width: 601px) {
      .player-container:hover .player-controls {
        opacity: 1;
      }
      .player-container:hover .product-title {
        opacity: 1;
      }
    }

    /* Mobile: controls shown via tap (controlled by JS) */
    .player-controls.visible {
      opacity: 1;
    }

    .product-title.visible {
      opacity: 1;
    }

    /* Controls grid - 3 columns, multiple rows */
    .controls-grid {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 0.75rem;
      background: rgba(0,0,0,0.8);
      padding: 1.5rem;
      border-radius: 8px;
      pointer-events: auto;
    }

    .controls-grid button {
      background: rgba(255,255,255,0.2);
      border: none;
      color: white;
      padding: 0.75rem 1rem;
      border-radius: 4px;
      transition: background 0.2s;
      cursor: pointer;
      font-size: 1rem;
      white-space: nowrap;
      min-width: 100px;
    }

    .controls-grid button:hover:not(:disabled) {
      background: rgba(255,255,255,0.4);
    }

    .controls-grid button.active {
      background: rgba(255,255,255,0.6);
    }

    .controls-grid button:disabled {
      opacity: 0.3;
      cursor: not-allowed;
    }

    /* Larger buttons for prev/next/play */
    .controls-grid button.nav-btn {
      font-size: 1.5rem;
      padding: 1rem;
    }

    .controls-grid button.play-btn {
      font-size: 1.5rem;
      padding: 1rem;
    }

    /* Product title overlay */
    .product-title {
      position: absolute;
      top: 1rem;
      left: 1rem;
      color: white;
      background: rgba(0,0,0,0.5);
      padding: 0.5rem 1rem;
      border-radius: 4px;
      z-index: 5;
      font-size: 1.2rem;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.3s;
    }


    /* For images, add some styling to make navigation visible */
    img#media {
      cursor: default;
    }

    /* Audio player should be centered */
    audio#media {
      margin: auto;
    }
  </style>
</head>
<body>
  <div class="player-container" id="playerContainer">
    {% if media_type == 'video' %}
    <video id="media" src="{{ presigned_url }}" autoplay controls playsinline>
      Your browser does not support the video tag.
    </video>
    {% elif media_type == 'audio' %}
    <audio id="media" src="{{ presigned_url }}" autoplay controls playsinline>
      Your browser does not support the audio tag.
    </audio>
    {% elif media_type == 'image' %}
    <img id="media" src="{{ presigned_url }}" alt="{{ product.title }}" />
    {% elif media_type == 'document' %}
    <iframe id="media" src="{{ presigned_url }}" frameborder="0">
      Your browser does not support PDF viewing.
    </iframe>
    {% endif %}

    <div class="product-title">{{ product.title }}</div>

    <div class="player-controls">
      <div class="controls-grid">
        <!-- Row 1: Navigation -->
        {% if prev_product_id %}
        <button class="nav-btn" id="prevBtn" onclick="navigate('{{ prev_product_id }}')" title="Previous (Left Arrow)">◀</button>
        {% else %}
        <button class="nav-btn" disabled>◀</button>
        {% endif %}

        <button class="play-btn" id="playPauseBtn" onclick="togglePlayPause()" title="Play/Pause (Space)">⏸</button>

        {% if next_product_id %}
        <button class="nav-btn" id="nextBtn" onclick="navigate('{{ next_product_id }}')" title="Next (Right Arrow)">▶</button>
        {% else %}
        <button class="nav-btn" disabled>▶</button>
        {% endif %}

        <!-- Row 2: Features -->
        <button id="alwaysOnTopBtn" onclick="toggleAlwaysOnTop()" title="Always on Top (T)">📌 On Top</button>
        {% if media_type == 'video' %}
        <button id="pipBtn" onclick="togglePip()" title="Picture-in-Picture with Prev/Next (P) - True always-on-top">📺 PiP</button>
        {% endif %}
        <button onclick="goToProductPage()" title="Go to Product Page (G)">🔗 Page</button>

        <!-- Row 3: More options -->
        <button id="autoResizeBtn" onclick="toggleAutoResize()" title="Auto-Resize Window (R)">↔ Resize</button>
        <button onclick="window.close()" title="Close Window (ESC)">✕ Close</button>
        {% if instrumentals_url or vocals_url %}
        <button id="karaokeBtn" onclick="toggleKaraoke()" title="Karaoke Mode (K)">🎤 Original</button>
        {% else %}
        <span></span>
        {% endif %}
      </div>
    </div>
  </div>

  <script src="/static/js/player.js"></script>
  <script>
    // Pass navigation data to player.js
    window.playerData = {
      prevProductId: {{ ('"%s"' % prev_product_id) if prev_product_id else 'null' }},
      nextProductId: {{ ('"%s"' % next_product_id) if next_product_id else 'null' }},
      mediaType: "{{ media_type }}",
      productId: "{{ product.id }}",
      productUrl: "{{ product_url }}",
      prevProductUrl: {{ ('"%s"' % prev_product_url) if prev_product_url else 'null' }},
      nextProductUrl: {{ ('"%s"' % next_product_url) if next_product_url else 'null' }},
      instrumentalsUrl: {{ ('"%s"' % instrumentals_url) if instrumentals_url else 'null' }},
      vocalsUrl: {{ ('"%s"' % vocals_url) if vocals_url else 'null' }}
    };

    // Karaoke toggle — cycles: Original → Instrumentals → Vocals → Original
    let originalSrc = null;
    const trackModes = [];
    (function() {
      trackModes.push({name: 'Original', url: null});
      if (window.playerData.instrumentalsUrl)
        trackModes.push({name: 'Instrumentals', url: window.playerData.instrumentalsUrl});
      if (window.playerData.vocalsUrl)
        trackModes.push({name: 'Vocals', url: window.playerData.vocalsUrl});
    })();
    let trackIndex = 0;

    function toggleKaraoke() {
      const media = document.getElementById('media');
      const btn = document.getElementById('karaokeBtn');
      if (!media || trackModes.length <= 1) return;

      if (!originalSrc) originalSrc = media.src;

      const currentTime = media.currentTime;
      const wasPlaying = !media.paused;

      trackIndex = (trackIndex + 1) % trackModes.length;
      const mode = trackModes[trackIndex];

      media.src = mode.url || originalSrc;
      btn.textContent = '🎤 ' + mode.name;
      if (trackIndex === 0) {
        btn.classList.remove('active');
      } else {
        btn.classList.add('active');
      }

      media.addEventListener('loadedmetadata', function once() {
        media.currentTime = currentTime;
        if (wasPlaying) media.play();
        media.removeEventListener('loadedmetadata', once);
      });
    }

    // Go to the product page (always opens in new tab)
    function goToProductPage() {
      window.open(window.playerData.productUrl, '_blank');
    }

    // Document Picture-in-Picture with custom controls
    let pipWindow = null;

    async function togglePip() {
      const media = document.getElementById('media');
      if (!media || media.tagName !== 'VIDEO') {
        console.log('No video element found');
        return;
      }

      console.log('togglePip called');
      console.log('documentPictureInPicture support:', 'documentPictureInPicture' in window);

      // Check for Document Picture-in-Picture API support
      if ('documentPictureInPicture' in window) {
        console.log('Using Document PiP');
        if (pipWindow) {
          // Close existing PiP window
          pipWindow.close();
          pipWindow = null;
          updatePipButtonState(false);
          return;
        }

        try {
          // Calculate aspect ratio from video
          let aspectRatio = 16 / 9; // Default aspect ratio
          if (media.videoWidth && media.videoHeight) {
            aspectRatio = media.videoWidth / media.videoHeight;
            console.log('Video dimensions:', media.videoWidth, 'x', media.videoHeight, 'aspect:', aspectRatio);
          } else {
            console.log('Video dimensions not available yet, using 16:9 default');
          }

          let width = 640;
          let height = Math.round(width / aspectRatio);

          // Constrain to reasonable sizes
          if (height > 480) {
            height = 480;
            width = Math.round(height * aspectRatio);
          }

          console.log('Opening Document PiP window:', width, 'x', height);

          // Open Document PiP window with custom content
          pipWindow = await window.documentPictureInPicture.requestWindow({
            width: width,
            height: height + 60 // Extra space for controls
          });

          updatePipButtonState(true);

          // Copy stylesheets to PiP window
          const stylesheets = Array.from(document.styleSheets);
          stylesheets.forEach(stylesheet => {
            try {
              const cssRules = Array.from(stylesheet.cssRules);
              const style = pipWindow.document.createElement('style');
              cssRules.forEach(rule => {
                style.textContent += rule.cssText;
              });
              pipWindow.document.head.appendChild(style);
            } catch (e) {
              // External stylesheet, link it
              const link = pipWindow.document.createElement('link');
              link.rel = 'stylesheet';
              link.href = stylesheet.href;
              pipWindow.document.head.appendChild(link);
            }
          });

          // Add PiP-specific styles
          const pipStyle = pipWindow.document.createElement('style');
          pipStyle.textContent = `
            body {
              margin: 0;
              padding: 0;
              background: #000;
              overflow: hidden;
            }
            .pip-container {
              display: grid;
              grid-template-rows: 1fr auto;
              width: 100vw;
              height: 100vh;
            }
            .pip-video {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            .pip-controls {
              display: grid;
              grid-template-columns: auto 1fr auto;
              gap: 0.5rem;
              padding: 0.5rem;
              background: rgba(0,0,0,0.9);
              align-items: center;
            }
            .pip-controls button {
              background: rgba(255,255,255,0.2);
              border: none;
              color: white;
              padding: 0.5rem 1rem;
              border-radius: 4px;
              cursor: pointer;
              font-size: 0.9rem;
            }
            .pip-controls button:hover:not(:disabled) {
              background: rgba(255,255,255,0.4);
            }
            .pip-controls button:disabled {
              opacity: 0.3;
              cursor: not-allowed;
            }
            .pip-title {
              color: white;
              font-size: 0.9rem;
              text-align: center;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          `;
          pipWindow.document.head.appendChild(pipStyle);

          // Build PiP content with navigation controls
          const container = pipWindow.document.createElement('div');
          container.className = 'pip-container';

          // Clone video element
          const pipVideo = pipWindow.document.createElement('video');
          pipVideo.className = 'pip-video';
          pipVideo.src = media.src;
          pipVideo.currentTime = media.currentTime;
          pipVideo.controls = true;
          pipVideo.autoplay = true;

          // Create controls
          const controls = pipWindow.document.createElement('div');
          controls.className = 'pip-controls';

          // Previous button
          const prevBtn = pipWindow.document.createElement('button');
          prevBtn.textContent = '◀ Prev';
          prevBtn.disabled = !window.playerData.prevProductId;
          prevBtn.onclick = () => {
            if (window.playerData.prevProductId) {
              window.location.href = '/player/' + window.playerData.prevProductId;
            }
          };

          // Title
          const title = pipWindow.document.createElement('div');
          title.className = 'pip-title';
          title.textContent = '{{ product.title }}';

          // Next button
          const nextBtn = pipWindow.document.createElement('button');
          nextBtn.textContent = 'Next ▶';
          nextBtn.disabled = !window.playerData.nextProductId;
          nextBtn.onclick = () => {
            if (window.playerData.nextProductId) {
              window.location.href = '/player/' + window.playerData.nextProductId;
            }
          };

          controls.appendChild(prevBtn);
          controls.appendChild(title);
          controls.appendChild(nextBtn);

          container.appendChild(pipVideo);
          container.appendChild(controls);
          pipWindow.document.body.appendChild(container);

          // Sync playback between main window and PiP
          pipVideo.addEventListener('play', () => media.play());
          pipVideo.addEventListener('pause', () => media.pause());
          pipVideo.addEventListener('seeked', () => {
            media.currentTime = pipVideo.currentTime;
          });

          // When PiP video ends, navigate to next
          pipVideo.addEventListener('ended', () => {
            if (window.playerData.nextProductId) {
              window.location.href = '/player/' + window.playerData.nextProductId;
            }
          });

          // Handle PiP window close
          pipWindow.addEventListener('pagehide', () => {
            pipWindow = null;
            updatePipButtonState(false);
            // Sync playback state back to main window
            if (!pipVideo.paused) {
              media.currentTime = pipVideo.currentTime;
              media.play();
            }
          });

          // Pause main video (playback continues in PiP)
          media.pause();

        } catch (err) {
          console.error('Failed to open Document PiP:', err);
          console.error('Error details:', err.message, err.name);
          alert('Document PiP failed: ' + err.message + '. Falling back to regular PiP.');
          // Fallback to regular PiP
          fallbackToPip(media);
        }
      } else {
        console.log('Document PiP not supported, using fallback');
        alert('Document PiP not supported in this browser. Using regular PiP (no prev/next controls).');
        // Fallback to regular PiP for unsupported browsers
        fallbackToPip(media);
      }
    }

    // Fallback to regular Picture-in-Picture API
    function fallbackToPip(media) {
      console.log('Using fallback regular PiP (no custom controls)');
      if (document.pictureInPictureElement) {
        console.log('Exiting regular PiP');
        document.exitPictureInPicture().catch(err => {
          console.error('Failed to exit PiP:', err);
        });
      } else {
        console.log('Entering regular PiP');
        media.requestPictureInPicture().catch(err => {
          console.error('Failed to enter PiP:', err);
        });
      }
    }

    // Update PiP button state
    function updatePipButtonState(isActive) {
      const pipBtn = document.getElementById('pipBtn');
      if (pipBtn) {
        if (isActive) {
          pipBtn.classList.add('active');
          pipBtn.textContent = '📺 Exit PiP';
        } else {
          pipBtn.classList.remove('active');
          pipBtn.textContent = '📺 PiP';
        }
      }
    }

    // Listen for regular PiP events (fallback mode)
    document.addEventListener('enterpictureinpicture', () => {
      if (!pipWindow) {
        updatePipButtonState(true);
      }
    });

    document.addEventListener('leavepictureinpicture', () => {
      if (!pipWindow) {
        updatePipButtonState(false);
      }
    });

    // Mobile: tap to show/hide controls
    let hideTimeout;
    const isMobile = window.innerWidth <= 600;

    if (isMobile) {
      const playerContainer = document.getElementById('playerContainer');
      const playerControls = document.querySelector('.player-controls');
      const controlsGrid = document.querySelector('.controls-grid');
      const productTitle = document.querySelector('.product-title');

      // Show controls initially for 3 seconds
      playerControls.classList.add('visible');
      productTitle.classList.add('visible');
      hideTimeout = setTimeout(() => {
        playerControls.classList.remove('visible');
        productTitle.classList.remove('visible');
      }, 3000);

      // Tap on player container to toggle controls
      playerContainer.addEventListener('click', (e) => {
        // Don't toggle if clicking on a control button
        if (controlsGrid.contains(e.target)) {
          return;
        }

        // Clear existing timeout
        if (hideTimeout) {
          clearTimeout(hideTimeout);
        }

        // Toggle controls visibility
        const isVisible = playerControls.classList.contains('visible');
        if (isVisible) {
          // Hide immediately
          playerControls.classList.remove('visible');
          productTitle.classList.remove('visible');
        } else {
          // Show and auto-hide after 3 seconds
          playerControls.classList.add('visible');
          productTitle.classList.add('visible');
          hideTimeout = setTimeout(() => {
            playerControls.classList.remove('visible');
            productTitle.classList.remove('visible');
          }, 3000);
        }
      });
    }

    // Mobile autoplay fix: unmute after user interaction
    if (isMobile) {
      const media = document.getElementById('media');
      if (media && (media.tagName === 'VIDEO' || media.tagName === 'AUDIO')) {
        // Try to play muted first (allowed by most browsers)
        media.muted = true;
        const playPromise = media.play();
        if (playPromise !== undefined) {
          playPromise.then(() => {
            // Once playing, unmute after a short delay
            setTimeout(() => {
              media.muted = false;
            }, 100);
          }).catch(err => {
            console.log('Autoplay failed:', err);
            // User will need to tap play button
          });
        }
      }
    }

    // Check Document PiP support on page load
    (function() {
      console.log('=== Player Debug Info ===');
      console.log('Document PiP API available:', 'documentPictureInPicture' in window);
      console.log('Regular PiP API available:', 'pictureInPictureEnabled' in document);
      console.log('Browser:', navigator.userAgent);
      console.log('========================');
    })();

    // Debug: Add ended event listener to verify it works
    (function() {
      const media = document.getElementById('media');
      if (media && (media.tagName === 'VIDEO' || media.tagName === 'AUDIO')) {
        media.addEventListener('ended', function() {
          console.log('Media ended event fired!');
          if (window.playerData && window.playerData.nextProductId) {
            console.log('Navigating to next:', window.playerData.nextProductId);
            window.location.href = '/player/' + window.playerData.nextProductId;
          } else {
            console.log('No next product available');
          }
        });

        // Debug: Log when media is playing
        media.addEventListener('play', function() {
          console.log('Media started playing');
        });

        // Debug: Log time updates to verify playback
        let lastLogTime = 0;
        media.addEventListener('timeupdate', function() {
          const currentTime = Math.floor(media.currentTime);
          if (currentTime > lastLogTime && currentTime % 5 === 0) {
            console.log('Playback at:', currentTime + 's / ' + Math.floor(media.duration) + 's');
            lastLogTime = currentTime;
          }
        });
      }
    })();
  </script>
</body>
</html>
