/**
 * Shaka Settings Popup Component
 * Uses Shaka Player modules to detect renditions and subtitles
 */
import './SettingsPopup.css';

class ShakaSettingsPopup {
  constructor(player, parentButtonEl) {
    super(player, options);
    this.isPopupOpen = false;
    this.currentSpeed = 1;
    this.currentRendition = null;
    this.renditions = [];
    this.currentSubtitle = null;
    this.subtitles = [];
    this.currentMenu = 'main'; // 'main', 'playback-speed', 'quality', or 'subtitles'
    this.shakaPlayer = null;

    console.log('ShakaSettingsPopup constructor called');
    this.setupShakaPlayer();
    this.createElements();
    this.attachEvents();
    this.setupEventListeners();
  }

  setupShakaPlayer() {
    // Get tech instance
    const tech = this.player().tech();
    console.log('Tech instance:', tech);
    
    // Store tech reference for accessing quality and text tracks data
    this.tech = tech;
    
    // Try to get Shaka Player instance from tech
    const shakaPlayer = tech.getShakaPlayer ? tech.getShakaPlayer() : tech.shakaPlayer;
    if (shakaPlayer) {
      this.shakaPlayer = shakaPlayer;
      console.log('Shaka Player instance found:', this.shakaPlayer);
    } else {
      console.warn('Shaka Player instance not found, will use Video.js APIs instead');
    }
  }

  setupEventListeners() {
    // Listen for Video.js events to update renditions and subtitles
    this.player().on('loadedqualitydata', (event) => {
      console.log('loadedqualitydata event - updating renditions');
      this.updateRenditions();
    });

    this.player().on('texttracksloaded', (event) => {
      console.log('texttracksloaded event - updating subtitles');
      this.updateSubtitles();
    });

    this.player().on('loadedmetadata', () => {
      console.log('loadedmetadata event - updating renditions and subtitles');
      // Delay to ensure setup is complete
      setTimeout(() => {
        this.updateRenditions();
        this.updateSubtitles();
      }, 1000);
    });

    this.player().on('loadstart', () => {
      console.log('loadstart event - updating renditions and subtitles');
      // Delay to ensure setup is complete
      setTimeout(() => {
        this.updateRenditions();
        this.updateSubtitles();
      }, 2000);
    });
    
    this.player().on('playing', () => {
      console.log('playing event - updating renditions and subtitles');
      this.updateRenditions();
      this.updateSubtitles();
    });

    this.player().on('canplay', () => {
      console.log('canplay event - updating renditions and subtitles');
      this.updateRenditions();
      this.updateSubtitles();
    });

    // Listen for quality changes
    this.player().on('qualitychange', () => {
      console.log('qualitychange event - updating renditions');
      this.updateRenditions();
    });

    // Listen for text track changes
    this.player().on('texttrackchange', () => {
      console.log('texttrackchange event - updating subtitles');
      this.updateSubtitles();
      this.updateCurrentSubtitle();
    });
  }

  createElements() {
    // Main popup container
    this.popupEl = document.createElement('div');
    this.popupEl.className = 'videojs-drm-settings-popup';
    this.popupEl.style.display = 'none';

    // Create main menu content
    this.createMainMenu();

    this.parentButtonEl.appendChild(this.popupEl);
  }

  createMainMenu() {
    const qualityText = this.currentRendition ? 
      this.formatRenditionLabel(this.currentRendition) : 'Auto';
    
    const subtitleText = this.currentSubtitle ? 
      this.formatSubtitleLabel(this.currentSubtitle) : 'Off';
    
    this.mainMenuContent = `
      <div class="settings-popup-item" data-action="playback-speed">
        <svg class="settings-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8 5v14l11-7z"/>
        </svg>
        <span class="settings-text">Playback speed</span>
        <span class="settings-value">${
          this.currentSpeed === 1
            ? 'Normal'
            : this.currentSpeed + 'x'
        }</span>
        <svg class="settings-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
        </svg>
      </div>
      <div class="settings-popup-item" data-action="quality">
        <svg class="settings-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
        </svg>
        <span class="settings-text">Quality</span>
        <span class="settings-value">${qualityText}</span>
        <svg class="settings-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
        </svg>
      </div>
      <div class="settings-popup-item" data-action="subtitles">
        <svg class="settings-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"/>
        </svg>
        <span class="settings-text">Subtitles</span>
        <span class="settings-value">${subtitleText}</span>
        <svg class="settings-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"/>
        </svg>
      </div>
    `;

    this.popupEl.innerHTML = this.mainMenuContent;
  }

  createPlaybackSpeedMenu() {
    const speeds = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];
    
    const speedItems = speeds.map(speed => `
      <div class="settings-popup-item speed-item ${speed === this.currentSpeed ? 'selected' : ''}" 
           data-speed="${speed}">
        <span class="settings-text">${speed === 1 ? 'Normal' : speed + 'x'}</span>
        ${speed === this.currentSpeed ? '<svg class="settings-check" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : ''}
      </div>
    `).join('');

    return `
      <div class="settings-popup-header">
        <svg class="settings-back" viewBox="0 0 24 24" fill="currentColor" data-action="back">
          <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
        <span class="settings-title">Playback speed</span>
      </div>
      ${speedItems}
    `;
  }

  createQualityMenu() {
    console.log('Creating quality menu, renditions:', this.renditions);
    
    if (!Array.isArray(this.renditions) || this.renditions.length === 0) {
      return `
        <div class="settings-popup-header">
          <svg class="settings-back" viewBox="0 0 24 24" fill="currentColor" data-action="back">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
          <span class="settings-title">Quality</span>
        </div>
        <div class="settings-popup-item">
          <span class="settings-text">No renditions available</span>
        </div>
      `;
    }

    const qualityItems = this.renditions.map(rendition => `
      <div class="settings-popup-item quality-item ${rendition === this.currentRendition ? 'selected' : ''}" 
           data-rendition-id="${rendition.id}">
        <span class="settings-text">${this.formatRenditionLabel(rendition)}</span>
        ${rendition === this.currentRendition ? '<svg class="settings-check" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : ''}
      </div>
    `).join('');

    return `
      <div class="settings-popup-header">
        <svg class="settings-back" viewBox="0 0 24 24" fill="currentColor" data-action="back">
          <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
        <span class="settings-title">Quality</span>
      </div>
      <div class="settings-popup-item quality-item ${!this.currentRendition ? 'selected' : ''}" 
           data-rendition-id="auto">
        <span class="settings-text">Auto</span>
        ${!this.currentRendition ? '<svg class="settings-check" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : ''}
      </div>
      ${qualityItems}
    `;
  }

  createSubtitlesMenu() {
    console.log('Creating subtitles menu, subtitles:', this.subtitles);
    
    if (!Array.isArray(this.subtitles) || this.subtitles.length === 0) {
      return `
        <div class="settings-popup-header">
          <svg class="settings-back" viewBox="0 0 24 24" fill="currentColor" data-action="back">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
          <span class="settings-title">Subtitles</span>
        </div>
        <div class="settings-popup-item">
          <span class="settings-text">No subtitles available</span>
        </div>
      `;
    }

    const subtitleItems = this.subtitles.map(subtitle => `
      <div class="settings-popup-item subtitle-item ${subtitle === this.currentSubtitle ? 'selected' : ''}" 
           data-subtitle-id="${subtitle.id}">
        <span class="settings-text">${this.formatSubtitleLabel(subtitle)}</span>
        ${subtitle === this.currentSubtitle ? '<svg class="settings-check" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : ''}
      </div>
    `).join('');

    return `
      <div class="settings-popup-header">
        <svg class="settings-back" viewBox="0 0 24 24" fill="currentColor" data-action="back">
          <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
        <span class="settings-title">Subtitles</span>
      </div>
      <div class="settings-popup-item subtitle-item ${!this.currentSubtitle ? 'selected' : ''}" 
           data-subtitle-id="off">
        <span class="settings-text">Off</span>
        ${!this.currentSubtitle ? '<svg class="settings-check" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : ''}
      </div>
      ${subtitleItems}
    `;
  }

  attachEvents() {
    // Click events for popup items
    this.popupEl.addEventListener('click', (e) => {
      e.stopPropagation();
      
      const action = e.target.closest('[data-action]')?.dataset.action;
      const speed = e.target.closest('[data-speed]')?.dataset.speed;
      const renditionId = e.target.closest('[data-rendition-id]')?.dataset.renditionId;
      const subtitleId = e.target.closest('[data-subtitle-id]')?.dataset.subtitleId;

      if (action) {
        this.handleAction(action);
      } else if (speed) {
        this.setSpeed(parseFloat(speed));
      } else if (renditionId) {
        this.setRendition(renditionId);
      } else if (subtitleId) {
        this.setSubtitle(subtitleId);
      }
    });

    // Click outside to close
    document.addEventListener('click', (e) => {
      if (!this.popupEl.contains(e.target) && !this.parentButtonEl.contains(e.target)) {
        this.hide();
      }
    });
  }

  handleAction(action) {
    switch (action) {
      case 'playback-speed':
        this.showPlaybackSpeedMenu();
        break;
      case 'quality':
        this.showQualityMenu();
        break;
      case 'subtitles':
        this.showSubtitlesMenu();
        break;
      case 'back':
        this.showMainMenu();
        break;
    }
  }

  showMainMenu() {
    this.currentMenu = 'main';
    this.createMainMenu();
  }

  showPlaybackSpeedMenu() {
    this.currentMenu = 'playback-speed';
    this.popupEl.innerHTML = this.createPlaybackSpeedMenu();
  }

  showQualityMenu() {
    this.currentMenu = 'quality';
    this.popupEl.innerHTML = this.createQualityMenu();
  }

  showSubtitlesMenu() {
    this.currentMenu = 'subtitles';
    this.popupEl.innerHTML = this.createSubtitlesMenu();
  }

  setSpeed(speed) {
    this.currentSpeed = speed;
    this.player().playbackRate(speed);
    this.showMainMenu();
  }

  setRendition(renditionId) {
    if (renditionId === 'auto') {
      this.enableAutoQuality();
      this.currentRendition = null;
    } else {
      const rendition = this.renditions.find(r => r.id === renditionId);
      if (rendition) {
        this.setRenditionTrack(rendition);
        this.currentRendition = rendition;
      }
    }
    this.showMainMenu();
  }

  setSubtitle(subtitleId) {
    if (subtitleId === 'off') {
      this.disableSubtitles();
      this.currentSubtitle = null;
    } else {
      const subtitle = this.subtitles.find(s => s.id === subtitleId);
      if (subtitle) {
        this.enableSubtitle(subtitle);
        this.currentSubtitle = subtitle;
      }
    }
    this.showMainMenu();
  }

  setRenditionTrack(rendition) {
    if (!this.tech || !this.tech.qualitySwitchCallback) {
      console.warn('No quality switch callback available');
      return;
    }

    try {
      // Use the quality switch callback from setup-quality-tracks
      this.tech.qualitySwitchCallback(rendition.track.id, 'video');
      console.log('Set rendition:', rendition);
    } catch (error) {
      console.warn('Could not set rendition:', error);
    }
  }

  enableAutoQuality() {
    if (!this.tech || !this.tech.qualitySwitchCallback) {
      console.warn('No quality switch callback available');
      return;
    }

    try {
      // Use the quality switch callback with id -1 for auto
      this.tech.qualitySwitchCallback(-1, 'video');
      this.currentRendition = null;
      console.log('Enabled auto quality');
    } catch (error) {
      console.warn('Could not enable auto quality:', error);
    }
  }

  enableSubtitle(subtitle) {
    if (!this.player() || !subtitle.track) return;

    try {
      // Use Video.js text tracks API
      const textTracks = this.player().textTracks();
      
      // Disable all other subtitles
      for (let i = 0; i < textTracks.length; i++) {
        const track = textTracks[i];
        if (track.kind === 'captions' || track.kind === 'subtitles') {
          track.mode = 'disabled';
        }
      }

      // Enable selected subtitle
      subtitle.track.mode = 'showing';
      this.currentSubtitle = subtitle;
      
      console.log('Enabled subtitle:', subtitle);
    } catch (error) {
      console.warn('Could not enable subtitle:', error);
    }
  }

  disableSubtitles() {
    if (!this.player()) return;

    try {
      // Use Video.js text tracks API
      const textTracks = this.player().textTracks();
      
      // Disable all subtitles
      for (let i = 0; i < textTracks.length; i++) {
        const track = textTracks[i];
        if (track.kind === 'captions' || track.kind === 'subtitles') {
          track.mode = 'disabled';
        }
      }
      
      this.currentSubtitle = null;
      console.log('Disabled subtitles');
    } catch (error) {
      console.warn('Could not disable subtitles:', error);
    }
  }

  updateRenditions() {
    console.log('Updating renditions...');
    
    // Try to get quality data from tech
    if (!this.tech) {
      this.setupShakaPlayer();
    }

    if (!this.tech || !this.tech.qualityData) {
      console.log('No quality data available, retrying in 1 second...');
      setTimeout(() => {
        this.updateRenditions();
      }, 1000);
      return;
    }

    try {
      const qualityData = this.tech.qualityData;
      console.log('Quality data from tech:', qualityData);
      
      if (qualityData && qualityData.length > 0) {
        this.renditions = qualityData.map((track, index) => ({
          id: track.id || `rendition-${index}`,
          width: track.width,
          height: track.height,
          bandwidth: track.bandwidth,
          frameRate: track.frameRate,
          label: track.label,
          track: track
        }));

        // Find current rendition (look for selected: true)
        this.currentRendition = this.renditions.find(r => r.track.selected) || null;

        console.log('Available renditions:', this.renditions);
        console.log('Current rendition:', this.currentRendition);
        
        // Update menu if currently showing quality menu
        if (this.currentMenu === 'quality') {
          this.popupEl.innerHTML = this.createQualityMenu();
        }
      } else {
        console.log('No quality data available, retrying in 2 seconds...');
        setTimeout(() => {
          this.updateRenditions();
        }, 2000);
        this.renditions = [];
        this.currentRendition = null;
      }
    } catch (error) {
      console.warn('Could not get renditions from tech:', error);
      console.log('Retrying in 2 seconds...');
      setTimeout(() => {
        this.updateRenditions();
      }, 2000);
      this.renditions = [];
      this.currentRendition = null;
    }
  }

  updateSubtitles() {
    console.log('Updating subtitles...');
    
    // Try to get text tracks data from tech
    if (!this.tech) {
      this.setupShakaPlayer();
    }

    if (!this.tech || !this.tech.textTracksData) {
      console.log('No text tracks data available, retrying in 1 second...');
      setTimeout(() => {
        this.updateSubtitles();
      }, 1000);
      return;
    }

    try {
      const textTracksData = this.tech.textTracksData;
      console.log('Text tracks data from tech:', textTracksData);
      
      if (textTracksData && textTracksData.length > 0) {
        this.subtitles = textTracksData
          .filter(track => track.kind === 'captions' || track.kind === 'subtitles')
          .map((track, index) => ({
            id: `subtitle-${index}`,
            language: track.language,
            label: track.label || track.language || `Subtitle ${index + 1}`,
            kind: track.kind,
            track: track
          }));

        console.log('Available subtitles:', this.subtitles);
        
        // Update menu if currently showing subtitles menu
        if (this.currentMenu === 'subtitles') {
          this.popupEl.innerHTML = this.createSubtitlesMenu();
        }
      } else {
        console.log('No text tracks data available, retrying in 2 seconds...');
        setTimeout(() => {
          this.updateSubtitles();
        }, 2000);
        this.subtitles = [];
      }
    } catch (error) {
      console.warn('Could not get subtitles from tech:', error);
      console.log('Retrying in 2 seconds...');
      setTimeout(() => {
        this.updateSubtitles();
      }, 2000);
      this.subtitles = [];
    }
  }

  updateCurrentSubtitle() {
    if (!this.shakaPlayer) return;

    try {
      const tracks = this.shakaPlayer.getTextTracks();
      const activeTrack = tracks.find(track => 
        (track.kind === 'captions' || track.kind === 'subtitles') && 
        track.active
      );

      if (activeTrack) {
        this.currentSubtitle = this.subtitles.find(s => s.track === activeTrack);
      } else {
        this.currentSubtitle = null;
      }

      console.log('Current subtitle updated:', this.currentSubtitle);
    } catch (error) {
      console.warn('Could not update current subtitle:', error);
    }
  }

  formatRenditionLabel(rendition) {
    if (!rendition) return 'Auto';
    
    if (rendition.height) {
      return `${rendition.height}p`;
    } else if (rendition.width) {
      return `${rendition.width}p`;
    } else if (rendition.bandwidth) {
      return `${Math.round(rendition.bandwidth / 1000)}k`;
    }
    
    return 'Unknown';
  }

  formatSubtitleLabel(subtitle) {
    if (!subtitle) return 'Off';
    return subtitle.label || subtitle.language || 'Unknown';
  }

  show() {
    this.isPopupOpen = true;
    this.popupEl.style.display = 'block';
  }

  hide() {
    this.isPopupOpen = false;
    this.popupEl.style.display = 'none';
    this.showMainMenu();
  }

  toggle() {
    if (this.isPopupOpen) {
      this.hide();
    } else {
      this.show();
    }
  }
}

export default ShakaSettingsPopup;