import './SettingsPopup.css';

class SettingsPopup {
  constructor(player, parentButtonEl) {
    this.player = player;
    this.parentButtonEl = parentButtonEl;
    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.createElements();
    this.attachEvents();
    this.setupRenditionListener();
    this.setupSubtitleListener();
  }

  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="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </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="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
      </div>
      <div class="settings-popup-item" data-action="subtitles">
        <svg class="settings-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V6h14v12zm-5.57-4.38l-2.5 3.06-1.93-2.07-1.93 2.07-2.5-3.06L9.5 12l-1.93-2.07 2.5-3.06 1.93 2.07 1.93-2.07 2.5 3.06L14.5 12l1.93 2.07z"/>
        </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="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
      </div>
    `;
  }

  createPlaybackSpeedMenu() {
    const speedOptions = [
      { value: 0.5, label: '0.5x', selected: this.currentSpeed === 0.5 },
      { value: 0.75, label: '0.75x', selected: this.currentSpeed === 0.75 },
      { value: 1, label: 'Normal', selected: this.currentSpeed === 1 },
      { value: 1.25, label: '1.25x', selected: this.currentSpeed === 1.25 },
      { value: 1.5, label: '1.5x', selected: this.currentSpeed === 1.5 },
      { value: 2, label: '2x', selected: this.currentSpeed === 2 }
    ];

    this.playbackSpeedMenuContent = `
      <div class="settings-popup-item back-button" data-action="back">
        <svg class="settings-arrow back-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
        <span class="settings-text">Playback speed</span>
      </div>
      ${speedOptions.map(option => `
        <div class="settings-popup-item speed-item ${option.selected ? 'selected' : ''}" data-speed="${option.value}">
          ${option.selected ? `
            <svg class="check-icon" 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>
          ` : ''}
          <span class="settings-text">${option.label}</span>
        </div>
      `).join('')}
    `;
  }

  createQualityMenu() {
    // Add Auto option
    const qualityOptions = [
      { 
        value: 'auto', 
        label: 'Auto', 
        selected: !this.currentRendition || this.currentRendition.id === 'auto'
      }
    ];

    // Add available renditions
    this.renditions.forEach(rendition => {
      qualityOptions.push({
        value: rendition.id,
        label: this.formatRenditionLabel(rendition),
        selected: this.currentRendition && this.currentRendition.id === rendition.id
      });
    });

    this.qualityMenuContent = `
      <div class="settings-popup-item back-button" data-action="back">
        <svg class="settings-arrow back-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
        <span class="settings-text">Quality</span>
      </div>
      ${qualityOptions.map(option => `
        <div class="settings-popup-item quality-item ${option.selected ? 'selected' : ''}" data-quality="${option.value}">
          ${option.selected ? `
            <svg class="check-icon" 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>
          ` : ''}
          <span class="settings-text">${option.label}</span>
        </div>
      `).join('')}
    `;
  }

  createSubtitlesMenu() {
    // Add Off option
    const subtitleOptions = [
      { 
        value: 'off', 
        label: 'Off', 
        selected: !this.currentSubtitle || this.currentSubtitle.id === 'off'
      }
    ];

    // Add available subtitles
    this.subtitles.forEach(subtitle => {
      subtitleOptions.push({
        value: subtitle.id,
        label: this.formatSubtitleLabel(subtitle),
        selected: this.currentSubtitle && this.currentSubtitle.id === subtitle.id
      });
    });

    this.subtitlesMenuContent = `
      <div class="settings-popup-item back-button" data-action="back">
        <svg class="settings-arrow back-arrow" viewBox="0 0 24 24" fill="currentColor">
          <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
        </svg>
        <span class="settings-text">Subtitles</span>
      </div>
      ${subtitleOptions.map(option => `
        <div class="settings-popup-item subtitle-item ${option.selected ? 'selected' : ''}" data-subtitle="${option.value}">
          ${option.selected ? `
            <svg class="check-icon" 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>
          ` : ''}
          <span class="settings-text">${option.label}</span>
        </div>
      `).join('')}
    `;
  }

  attachEvents() {
    // Use event delegation for dynamic content
    this.popupEl.addEventListener('click', (e) => {
      e.stopPropagation();
      
      const item = e.target.closest('.settings-popup-item');
      if (!item) return;

      const action = item.dataset.action;
      const speed = item.dataset.speed;
      const quality = item.dataset.quality;
      const subtitle = item.dataset.subtitle;

      if (action === 'playback-speed') {
        this.showPlaybackSpeedMenu();
      } else if (action === 'quality') {
        this.showQualityMenu();
      } else if (action === 'subtitles') {
        this.showSubtitlesMenu();
      } else if (action === 'back') {
        this.showMainMenu();
      } else if (speed) {
        this.setPlaybackSpeed(parseFloat(speed));
      } else if (quality) {
        this.setQuality(quality);
      } else if (subtitle) {
        this.setSubtitle(subtitle);
      }
    });
  }

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

  show() {
    this.popupEl.style.display = 'block';
    this.isPopupOpen = true;
    this.currentMenu = 'main';
    
    // Update content to reflect current speed
    this.createMainMenu();
    this.showMainMenu();
    
    setTimeout(() => {
      this.outsideHandler = (evt) => {
        if (!this.parentButtonEl.contains(evt.target)) {
          this.hide();
        }
      };
      document.addEventListener('click', this.outsideHandler);
    }, 0);
  }

  hide() {
    this.popupEl.style.display = 'none';
    this.isPopupOpen = false;
    this.currentMenu = 'main';
    
    if (this.outsideHandler) {
      document.removeEventListener('click', this.outsideHandler);
      this.outsideHandler = null;
    }
  }

  showMainMenu() {
    this.currentMenu = 'main';
    this.popupEl.innerHTML = this.mainMenuContent;
  }

  showPlaybackSpeedMenu() {
    this.currentMenu = 'playback-speed';
    // Ensure content is up to date
    this.createPlaybackSpeedMenu();
    this.popupEl.innerHTML = this.playbackSpeedMenuContent;
  }

  showQualityMenu() {
    this.currentMenu = 'quality';
    // Ensure content is up to date
    this.createQualityMenu();
    this.popupEl.innerHTML = this.qualityMenuContent;
  }

  showSubtitlesMenu() {
    this.currentMenu = 'subtitles';
    // Ensure content is up to date
    this.createSubtitlesMenu();
    this.popupEl.innerHTML = this.subtitlesMenuContent;
  }

  setPlaybackSpeed(speed) {
    this.currentSpeed = speed;
    if (this.player) {
      this.player.playbackRate(speed);
    }
    // Close popup after selection
    this.hide();
  }

  setQuality(qualityId) {
    if (qualityId === 'auto') {
      this.currentRendition = null;
      this.enableAutoQuality();
    } else {
      const rendition = this.renditions.find(r => r.id === qualityId);
      if (rendition) {
        this.currentRendition = rendition;
        this.setRendition(rendition);
      }
    }
    // Close popup after selection
    this.hide();
  }

  setSubtitle(subtitleId) {
    if (subtitleId === 'off') {
      this.currentSubtitle = null;
      this.disableSubtitles();
    } else {
      const subtitle = this.subtitles.find(s => s.id === subtitleId);
      if (subtitle) {
        this.currentSubtitle = subtitle;
        this.enableSubtitle(subtitle);
      }
    }
    // Close popup after selection
    this.hide();
  }

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

    // Listen for loadedmetadata to get renditions
    this.player.on('loadedmetadata', () => {
      this.updateRenditions();
    });

    // Listen for source changes
    this.player.on('loadstart', () => {
      this.updateRenditions();
    });
  }

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

    // Listen for loadedmetadata to get subtitles
    this.player.on('loadedmetadata', () => {
      this.updateSubtitles();
    });

    // Listen for source changes
    this.player.on('loadstart', () => {
      this.updateSubtitles();
    });

    // Listen for text track changes
    this.player.on('texttrackchange', () => {
      this.updateCurrentSubtitle();
    });
  }

  updateRenditions() {
    try {
      // Try using qualityLevels API first
      if (this.player.qualityLevels && this.player.qualityLevels()) {
        const qualityLevels = this.player.qualityLevels();
        console.log('Quality levels object:', qualityLevels);
        console.log('Quality levels type:', typeof qualityLevels);
        console.log('Quality levels length:', qualityLevels?.length);
        
        // Check if it's an array or has a length property
        if (Array.isArray(qualityLevels) && qualityLevels.length > 0) {
          this.renditions = qualityLevels.map((level, index) => ({
            id: `quality-${index}`,
            bandwidth: level.bandwidth,
            width: level.width,
            height: level.height,
            index: index,
            qualityLevel: level
          }));
          
          // Sort by bandwidth (highest first)
          this.renditions.sort((a, b) => b.bandwidth - a.bandwidth);
          
          console.log('Available renditions from qualityLevels:', this.renditions);
          return;
        } else if (qualityLevels && qualityLevels.length > 0) {
          // Try to convert to array if it has length but is not array
          console.log('Converting qualityLevels to array...');
          const levelsArray = [];
          for (let i = 0; i < qualityLevels.length; i++) {
            if (qualityLevels[i]) {
              levelsArray.push(qualityLevels[i]);
            }
          }
          
          if (levelsArray.length > 0) {
            this.renditions = levelsArray.map((level, index) => ({
              id: `quality-${index}`,
              bandwidth: level.bandwidth,
              width: level.width,
              height: level.height,
              index: index,
              qualityLevel: level
            }));
            
            // Sort by bandwidth (highest first)
            this.renditions.sort((a, b) => b.bandwidth - a.bandwidth);
            
            console.log('Available renditions from qualityLevels (converted):', this.renditions);
            return;
          }
        }
        
        console.log('Quality levels is not usable, trying VHS...');
      }
      
      // Fallback to VHS representations
      const tech = this.player.tech();
      if (tech && tech.vhs) {
        const vhs = tech.vhs;
        
        if (vhs.representations && vhs.representations()) {
          const rawReps = vhs.representations();
          console.log('Raw representations:', rawReps);
          
          this.renditions = rawReps.map((rep, index) => ({
            id: `rendition-${index}`,
            bandwidth: rep.bandwidth,
            width: rep.width,
            height: rep.height,
            resolution: rep.resolution,
            index: index,
            representation: rep
          }));
          
          // Sort by bandwidth (highest first)
          this.renditions.sort((a, b) => b.bandwidth - a.bandwidth);
          
          console.log('Available renditions from VHS:', this.renditions);
        }
      }
    } catch (error) {
      console.warn('Could not get renditions:', error);
    }
  }

  formatRenditionLabel(rendition) {
    if (!rendition) return 'Auto';
    
    if (rendition.height) {
      return `${rendition.height}p`;
    } else if (rendition.bandwidth) {
      const mbps = (rendition.bandwidth / 1000000).toFixed(1);
      return `${mbps} Mbps`;
    } else {
      return 'Unknown';
    }
  }

  setRendition(rendition) {
    try {
      console.log('Setting rendition:', rendition);
      
      // Try using qualityLevels API first
      if (this.player.qualityLevels && this.player.qualityLevels()) {
        const qualityLevels = this.player.qualityLevels();
        console.log('Current quality levels:', qualityLevels);
        
        // Disable all quality levels first
        if (Array.isArray(qualityLevels)) {
          qualityLevels.forEach((level, index) => {
            level.enabled = false;
          });
        } else if (qualityLevels && qualityLevels.length > 0) {
          // Handle non-array qualityLevels object
          for (let i = 0; i < qualityLevels.length; i++) {
            if (qualityLevels[i]) {
              qualityLevels[i].enabled = false;
            }
          }
        }
        
        // Enable only the selected quality level
        if (rendition.qualityLevel) {
          rendition.qualityLevel.enabled = true;
          console.log('Enabled quality level:', rendition.qualityLevel);
        }
        
        console.log('Quality levels after change:', qualityLevels);
        return;
      }
      
      // Fallback to VHS representations
      const tech = this.player.tech();
      if (tech && tech.vhs && rendition.representation) {
        const vhs = tech.vhs;
        const reps = vhs.representations();
        console.log('Current representations before change:', reps);
        
        reps.forEach((rep, index) => {
          if (rep === rendition.representation) {
            console.log(`Enabling rendition ${index}:`, rep);
            rep.enabled = true;
          } else {
            console.log(`Disabling rendition ${index}:`, rep);
            rep.enabled = false;
          }
        });
        
        console.log('Representations after change:', reps);
        console.log('Set rendition to:', rendition);
        
        // Force VHS to update
        if (vhs.trigger) {
          vhs.trigger('renditionchange');
        }
      }
    } catch (error) {
      console.warn('Could not set rendition:', error);
    }
  }

  enableAutoQuality() {
    try {
      console.log('Enabling auto quality');
      
      // Try using qualityLevels API first
      if (this.player.qualityLevels && this.player.qualityLevels()) {
        const qualityLevels = this.player.qualityLevels();
        console.log('Current quality levels for auto:', qualityLevels);
        
        // Enable all quality levels for auto selection
        if (Array.isArray(qualityLevels)) {
          qualityLevels.forEach(level => {
            level.enabled = true;
          });
        } else if (qualityLevels && qualityLevels.length > 0) {
          // Handle non-array qualityLevels object
          for (let i = 0; i < qualityLevels.length; i++) {
            if (qualityLevels[i]) {
              qualityLevels[i].enabled = true;
            }
          }
        }
        
        console.log('Enabled auto quality via qualityLevels');
        return;
      }
      
      // Fallback to VHS representations
      const tech = this.player.tech();
      if (tech && tech.vhs) {
        const vhs = tech.vhs;
        if (vhs.representations) {
          vhs.representations().forEach(rep => {
            rep.enabled = true;
          });
        }
        console.log('Enabled auto quality via VHS');
      }
    } catch (error) {
      console.warn('Could not enable auto quality:', error);
    }
  }

  updateSubtitles() {
    try {
      const textTracks = this.player.textTracks();
      console.log('Text tracks:', textTracks);
      
      // Debug each track
      for (let i = 0; i < textTracks.length; i++) {
        const track = textTracks[i];
        console.log(`Track ${i}:`, {
          id: track.id,
          language: track.language,
          label: track.label,
          kind: track.kind,
          mode: track.mode,
          src: track.src
        });
      }
      
      this.subtitles = Array.from(textTracks)
        .filter(track => track.kind === 'captions' || track.kind === 'subtitles')
        .map((track, index) => ({
          id: `subtitle-${index}`,
          language: track.language || 'unknown',
          label: track.label || track.language || `Subtitle ${index + 1}`,
          kind: track.kind,
          index: index,
          textTrack: track
        }));
      
      console.log('Available subtitles:', this.subtitles);
      
      // Update current subtitle based on active track
      this.updateCurrentSubtitle();
    } catch (error) {
      console.warn('Could not get subtitles:', error);
    }
  }

  updateCurrentSubtitle() {
    try {
      const textTracks = this.player.textTracks();
      const activeTrack = Array.from(textTracks).find(track => 
        track.mode === 'showing' && (track.kind === 'captions' || track.kind === 'subtitles')
      );
      
      if (activeTrack) {
        this.currentSubtitle = this.subtitles.find(subtitle => 
          subtitle.textTrack === activeTrack
        );
      } else {
        this.currentSubtitle = null;
      }
      
      console.log('Current subtitle:', this.currentSubtitle);
    } catch (error) {
      console.warn('Could not update current subtitle:', error);
    }
  }

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

  enableSubtitle(subtitle) {
    try {
      console.log('Enabling subtitle:', subtitle);
      
      // Disable all text tracks first
      const textTracks = this.player.textTracks();
      Array.from(textTracks).forEach(track => {
        if (track.kind === 'captions' || track.kind === 'subtitles') {
          track.mode = 'disabled';
        }
      });
      
      // Enable the selected subtitle track
      if (subtitle.textTrack) {
        subtitle.textTrack.mode = 'showing';
        console.log('Enabled subtitle track:', subtitle.textTrack);
      }
    } catch (error) {
      console.warn('Could not enable subtitle:', error);
    }
  }

  disableSubtitles() {
    try {
      console.log('Disabling subtitles');
      
      const textTracks = this.player.textTracks();
      Array.from(textTracks).forEach(track => {
        if (track.kind === 'captions' || track.kind === 'subtitles') {
          track.mode = 'disabled';
        }
      });
      
      console.log('Disabled all subtitles');
    } catch (error) {
      console.warn('Could not disable subtitles:', error);
    }
  }
}

export default SettingsPopup;


