// Quran Speler JavaScript
class QuranPlayer {
  constructor() {
    console.log('QuranPlayer constructor called');
    this.currentIndex = 0;
    this.isPlaying = false;
    this.currentReciter = '';
    this.audio = document.getElementById('quranAudio');
    this.suras = this.getSuraList();
    this.reciters = this.getReciterList();
    this.loadingTimeout = null;
    
    console.log('Suras loaded:', this.suras.length);
    console.log('Reciters loaded:', this.reciters.length);
    
    this.init();
  }

  init() {
    console.log('Initializing QuranPlayer...');
    this.setupEventListeners();
    this.populateReciters();
    this.renderSuraGrid();
    this.setupAudioEvents();
    console.log('QuranPlayer initialized successfully');
  }

  getSuraList() {
    return [
      { number: 1, arabic: "الفاتحة", dutch: "Al-Faatihah", file: "001" },
      { number: 2, arabic: "البقرة", dutch: "Al-Baqarah", file: "002" },
      { number: 3, arabic: "آل عمران", dutch: "Aali-Imraan", file: "003" },
      { number: 4, arabic: "النساء", dutch: "An-Nisaa", file: "004" },
      { number: 5, arabic: "المائدة", dutch: "Al-Ma'idah", file: "005" },
      { number: 6, arabic: "الأنعام", dutch: "Al-An'aam", file: "006" },
      { number: 7, arabic: "الأعراف", dutch: "Al-A'raaf", file: "007" },
      { number: 8, arabic: "الأنفال", dutch: "Al-Anfaal", file: "008" },
      { number: 9, arabic: "التوبة", dutch: "At-Tawbah", file: "009" },
      { number: 10, arabic: "يونس", dutch: "Yoonus", file: "010" },
      { number: 11, arabic: "هود", dutch: "Hood", file: "011" },
      { number: 12, arabic: "يوسف", dutch: "Yoosuf", file: "012" },
      { number: 13, arabic: "الرعد", dutch: "Ar-Ra'd", file: "013" },
      { number: 14, arabic: "إبراهيم", dutch: "Ibraheem", file: "014" },
      { number: 15, arabic: "الحجر", dutch: "Al-Hijr", file: "015" },
      { number: 16, arabic: "النحل", dutch: "An-Nahl", file: "016" },
      { number: 17, arabic: "الإسراء", dutch: "Al-Israa", file: "017" },
      { number: 18, arabic: "الكهف", dutch: "Al-Kahf", file: "018" },
      { number: 19, arabic: "مريم", dutch: "Maryam", file: "019" },
      { number: 20, arabic: "طه", dutch: "Taa Haa", file: "020" },
      { number: 21, arabic: "الأنبياء", dutch: "Al-Anbiyaa", file: "021" },
      { number: 22, arabic: "الحج", dutch: "Al-Hajj", file: "022" },
      { number: 23, arabic: "المؤمنون", dutch: "Al-Mu'minoon", file: "023" },
      { number: 24, arabic: "النور", dutch: "An-Noor", file: "024" },
      { number: 25, arabic: "الفرقان", dutch: "Al-Furqaan", file: "025" },
      { number: 26, arabic: "الشعراء", dutch: "Ash-Shu'araa", file: "026" },
      { number: 27, arabic: "النمل", dutch: "An-Naml", file: "027" },
      { number: 28, arabic: "القصص", dutch: "Al-Qasas", file: "028" },
      { number: 29, arabic: "العنكبوت", dutch: "Al-Ankaboot", file: "029" },
      { number: 30, arabic: "الروم", dutch: "Ar-Room", file: "030" },
      { number: 31, arabic: "لقمان", dutch: "Luqmaan", file: "031" },
      { number: 32, arabic: "السجدة", dutch: "As-Sajdah", file: "032" },
      { number: 33, arabic: "الأحزاب", dutch: "Al-Ahzaab", file: "033" },
      { number: 34, arabic: "سبأ", dutch: "Saba", file: "034" },
      { number: 35, arabic: "فاطر", dutch: "Faatir", file: "035" },
      { number: 36, arabic: "يس", dutch: "Yaa Seen", file: "036" },
      { number: 37, arabic: "الصافات", dutch: "As-Saaffaat", file: "037" },
      { number: 38, arabic: "ص", dutch: "Saad", file: "038" },
      { number: 39, arabic: "الزمر", dutch: "Az-Zumar", file: "039" },
      { number: 40, arabic: "غافر", dutch: "Ghaafir", file: "040" },
      { number: 41, arabic: "فصلت", dutch: "Fussilat", file: "041" },
      { number: 42, arabic: "الشورى", dutch: "Ash-Shooraa", file: "042" },
      { number: 43, arabic: "الزخرف", dutch: "Az-Zukhruf", file: "043" },
      { number: 44, arabic: "الدخان", dutch: "Ad-Dukhaan", file: "044" },
      { number: 45, arabic: "الجاثية", dutch: "Al-Jaathiyah", file: "045" },
      { number: 46, arabic: "الأحقاف", dutch: "Al-Ahqaaf", file: "046" },
      { number: 47, arabic: "محمد", dutch: "Muhammad", file: "047" },
      { number: 48, arabic: "الفتح", dutch: "Al-Fath", file: "048" },
      { number: 49, arabic: "الحجرات", dutch: "Al-Hujuraat", file: "049" },
      { number: 50, arabic: "ق", dutch: "Qaaf", file: "050" },
      { number: 51, arabic: "الذاريات", dutch: "Adh-Dhaariyaat", file: "051" },
      { number: 52, arabic: "الطور", dutch: "At-Toor", file: "052" },
      { number: 53, arabic: "النجم", dutch: "An-Najm", file: "053" },
      { number: 54, arabic: "القمر", dutch: "Al-Qamar", file: "054" },
      { number: 55, arabic: "الرحمن", dutch: "Ar-Rahmaan", file: "055" },
      { number: 56, arabic: "الواقعة", dutch: "Al-Waaqi'ah", file: "056" },
      { number: 57, arabic: "الحديد", dutch: "Al-Hadeed", file: "057" },
      { number: 58, arabic: "المجادلة", dutch: "Al-Mujaadilah", file: "058" },
      { number: 59, arabic: "الحشر", dutch: "Al-Hashr", file: "059" },
      { number: 60, arabic: "الممتحنة", dutch: "Al-Mumtahanah", file: "060" },
      { number: 61, arabic: "الصف", dutch: "As-Saff", file: "061" },
      { number: 62, arabic: "الجمعة", dutch: "Al-Jumu'ah", file: "062" },
      { number: 63, arabic: "المنافقون", dutch: "Al-Munaafiqoon", file: "063" },
      { number: 64, arabic: "التغابن", dutch: "At-Taghaabun", file: "064" },
      { number: 65, arabic: "الطلاق", dutch: "At-Talaaq", file: "065" },
      { number: 66, arabic: "التحريم", dutch: "At-Tahreem", file: "066" },
      { number: 67, arabic: "الملك", dutch: "Al-Mulk", file: "067" },
      { number: 68, arabic: "القلم", dutch: "Al-Qalam", file: "068" },
      { number: 69, arabic: "الحاقة", dutch: "Al-Haaqqah", file: "069" },
      { number: 70, arabic: "المعارج", dutch: "Al-Ma'aarij", file: "070" },
      { number: 71, arabic: "نوح", dutch: "Nooh", file: "071" },
      { number: 72, arabic: "الجن", dutch: "Al-Jinn", file: "072" },
      { number: 73, arabic: "المزمل", dutch: "Al-Muzzammil", file: "073" },
      { number: 74, arabic: "المدثر", dutch: "Al-Muddaththir", file: "074" },
      { number: 75, arabic: "القيامة", dutch: "Al-Qiyaamah", file: "075" },
      { number: 76, arabic: "الإنسان", dutch: "Al-Insaan", file: "076" },
      { number: 77, arabic: "المرسلات", dutch: "Al-Mursalaat", file: "077" },
      { number: 78, arabic: "النبأ", dutch: "An-Naba", file: "078" },
      { number: 79, arabic: "النازعات", dutch: "An-Naazi'aat", file: "079" },
      { number: 80, arabic: "عبس", dutch: "Abasa", file: "080" },
      { number: 81, arabic: "التكوير", dutch: "At-Takweer", file: "081" },
      { number: 82, arabic: "الانفطار", dutch: "Al-Infitaar", file: "082" },
      { number: 83, arabic: "المطففين", dutch: "Al-Mutaffifeen", file: "083" },
      { number: 84, arabic: "الانشقاق", dutch: "Al-Inshiqaaq", file: "084" },
      { number: 85, arabic: "البروج", dutch: "Al-Burooj", file: "085" },
      { number: 86, arabic: "الطارق", dutch: "At-Taariq", file: "086" },
      { number: 87, arabic: "الأعلى", dutch: "Al-A'laa", file: "087" },
      { number: 88, arabic: "الغاشية", dutch: "Al-Ghaashiyah", file: "088" },
      { number: 89, arabic: "الفجر", dutch: "Al-Fajr", file: "089" },
      { number: 90, arabic: "البلد", dutch: "Al-Balad", file: "090" },
      { number: 91, arabic: "الشمس", dutch: "Ash-Shams", file: "091" },
      { number: 92, arabic: "الليل", dutch: "Al-Layl", file: "092" },
      { number: 93, arabic: "الضحى", dutch: "Ad-Duhaa", file: "093" },
      { number: 94, arabic: "الشرح", dutch: "Ash-Sharh", file: "094" },
      { number: 95, arabic: "التين", dutch: "At-Teen", file: "095" },
      { number: 96, arabic: "العلق", dutch: "Al-Alaq", file: "096" },
      { number: 97, arabic: "القدر", dutch: "Al-Qadr", file: "097" },
      { number: 98, arabic: "البينة", dutch: "Al-Bayyinah", file: "098" },
      { number: 99, arabic: "الزلزلة", dutch: "Az-Zalzalah", file: "099" },
      { number: 100, arabic: "العاديات", dutch: "Al-Aadiyaat", file: "100" },
      { number: 101, arabic: "القارعة", dutch: "Al-Qaari'ah", file: "101" },
      { number: 102, arabic: "التكاثر", dutch: "At-Takaathur", file: "102" },
      { number: 103, arabic: "العصر", dutch: "Al-Asr", file: "103" },
      { number: 104, arabic: "الهمزة", dutch: "Al-Humazah", file: "104" },
      { number: 105, arabic: "الفيل", dutch: "Al-Feel", file: "105" },
      { number: 106, arabic: "قريش", dutch: "Quraysh", file: "106" },
      { number: 107, arabic: "الماعون", dutch: "Al-Maa'oon", file: "107" },
      { number: 108, arabic: "الكوثر", dutch: "Al-Kawthar", file: "108" },
      { number: 109, arabic: "الكافرون", dutch: "Al-Kaafiroon", file: "109" },
      { number: 110, arabic: "النصر", dutch: "An-Nasr", file: "110" },
      { number: 111, arabic: "المسد", dutch: "Al-Masad", file: "111" },
      { number: 112, arabic: "الإخلاص", dutch: "Al-Ikhlaas", file: "112" },
      { number: 113, arabic: "الفلق", dutch: "Al-Falaq", file: "113" },
      { number: 114, arabic: "الناس", dutch: "An-Naas", file: "114" }
    ];
  }

  getReciterList() {
    return [
      { id: "abdulbaset_mujawwad", name: "AbdulBaset AbdulSamad", arabic: "عبد الباسط عبد الصمد" },
      { id: "muhammad_ayyoob_hq", name: "Muhammad Ayyoob", arabic: "محمد أيوب" },
      { id: "abdurrahmaan_as-sudays", name: "Abdur-Rahman as-Sudais", arabic: "عبد الرحمن السديس" },
      { id: "maher_almu3aiqly/year1440", name: "Maher Al-Muaiqly", arabic: "ماهر المعيقلي" },
      { id: "fares", name: "Fares Abbad", arabic: "فارس عباد" },
      { id: "ahmed_ibn_3ali_al-3ajamy", name: "Ahmed ibn Ali al-Ajmy", arabic: "أحمد بن علي العجمي" },
      { id: "sa3d_al-ghaamidi/complete", name: "Saad Al-Ghamdi", arabic: "سعد الغامدي" },
      { id: "sa3ood_al-shuraym", name: "Sa'ud ash-Shuraym", arabic: "سعود الشريم" },
      { id: "khaalid_al-qahtaanee", name: "Khalid al-Qahtani", arabic: "خالد القحطاني" },
      { id: "mahmood_khaleel_al-husaree_iza3a", name: "Mahmoud Khaleel Al-Husary", arabic: "محمود خليل الحصري" },
      { id: "minshawi_mujawwad", name: "Muhammad Siddiq al-Minshawi", arabic: "محمد صديق المنشاوي" },
      { id: "abu_bakr_ash-shatri_tarawee7", name: "Abu Bakr al-Shatri", arabic: "أبو بكر الشاطري" }
    ];
  }

  setupEventListeners() {
    // Reciteur selectie
    document.getElementById('reciterSelect').addEventListener('change', (e) => {
      this.currentReciter = e.target.value;
      this.updateReciterDisplay();
      console.log('Reciter selected:', this.currentReciter);
    });

    // Zoekfunctionaliteit
    document.getElementById('suraSearch').addEventListener('input', (e) => {
      this.filterSuras(e.target.value);
    });

    // Player controls
    document.getElementById('playBtn').addEventListener('click', () => this.togglePlay());
    document.getElementById('prevBtn').addEventListener('click', () => this.previousSura());
    document.getElementById('nextBtn').addEventListener('click', () => this.nextSura());
    
    // Direct play button
    document.getElementById('directPlayBtn').addEventListener('click', () => this.directPlay());

    // Progress bar
    document.getElementById('progressBar').addEventListener('input', (e) => {
      this.seekTo(e.target.value);
    });
  }

  populateReciters() {
    const select = document.getElementById('reciterSelect');
    console.log('Populating reciters...', this.reciters);
    
    this.reciters.forEach(reciter => {
      const option = document.createElement('option');
      option.value = reciter.id;
      option.textContent = `${reciter.name} - ${reciter.arabic}`;
      select.appendChild(option);
    });
    
    console.log('Reciters populated, total options:', select.children.length);
  }

  renderSuraGrid() {
    const grid = document.getElementById('suraGrid');
    grid.innerHTML = '';

    this.suras.forEach((sura, index) => {
      const suraItem = document.createElement('div');
      suraItem.className = 'sura-item';
      suraItem.dataset.index = index;
      
      suraItem.innerHTML = `
        <div class="sura-number">Sura ${sura.number}</div>
        <div class="sura-name-arabic">${sura.arabic}</div>
        <div class="sura-name-dutch">${sura.dutch}</div>
      `;

      suraItem.addEventListener('click', () => this.selectSura(index));
      grid.appendChild(suraItem);
    });
  }

  filterSuras(searchTerm) {
    const items = document.querySelectorAll('.sura-item');
    const term = searchTerm.toLowerCase();

    items.forEach((item, index) => {
      const sura = this.suras[index];
      const matches = sura.dutch.toLowerCase().includes(term) || 
                     sura.arabic.includes(term) || 
                     sura.number.toString().includes(term);
      
      item.style.display = matches ? 'block' : 'none';
    });
  }

  selectSura(index) {
    if (!this.currentReciter) {
      alert('Selecteer eerst een reciteur');
      return;
    }

    this.currentIndex = index;
    this.updateActiveSura();
    this.loadCurrentSura();
  }

  updateActiveSura() {
    document.querySelectorAll('.sura-item').forEach((item, index) => {
      item.classList.toggle('active', index === this.currentIndex);
    });
  }

  clearLoadingTimeout() {
    if (this.loadingTimeout) {
      clearTimeout(this.loadingTimeout);
      this.loadingTimeout = null;
    }
  }

  hideLoading() {
    this.clearLoadingTimeout();
    document.querySelector('.player-section').classList.remove('loading');
  }

  showLoading() {
    document.querySelector('.player-section').classList.add('loading');
    
    // Timeout na 10 seconden
    this.loadingTimeout = setTimeout(() => {
      console.log('Loading timeout - hiding loading state');
      this.hideLoading();
    }, 10000);
  }

  loadCurrentSura() {
    const sura = this.suras[this.currentIndex];
    const url = `https://download.quranicaudio.com/quran/${this.currentReciter}/${sura.file}.mp3`;
    
    console.log('Loading sura:', url);
    
    // Reset audio element
    this.audio.pause();
    this.audio.currentTime = 0;
    
    // Show loading state
    this.showLoading();
    
    // Set crossorigin attribute voor CORS
    this.audio.crossOrigin = "anonymous";
    this.audio.preload = "metadata";
    this.audio.src = url;
    
    this.updateSuraInfo();
    
    // Force load
    this.audio.load();
    
    // Auto-play als er al iets speelde
    if (this.isPlaying) {
      // Wacht even voordat we proberen af te spelen
      setTimeout(() => {
        this.audio.play().catch(e => {
          console.log('Auto-play geblokkeerd:', e);
          this.isPlaying = false;
          this.updatePlayButton();
          this.hideLoading();
        });
      }, 500);
    }
  }

  updateSuraInfo() {
    const sura = this.suras[this.currentIndex];
    const reciter = this.reciters.find(r => r.id === this.currentReciter);
    
    document.getElementById('currentSuraName').textContent = `${sura.arabic} - ${sura.dutch}`;
    document.getElementById('currentReciter').textContent = reciter ? reciter.name : 'Onbekende reciteur';
  }

  updateReciterDisplay() {
    const reciter = this.reciters.find(r => r.id === this.currentReciter);
    if (reciter && this.suras[this.currentIndex]) {
      this.updateSuraInfo();
    }
  }

  togglePlay() {
    if (!this.currentReciter || !this.audio.src) {
      alert('Selecteer eerst een reciteur en sura');
      return;
    }

    if (this.isPlaying) {
      this.audio.pause();
    } else {
      // Toon loading als audio nog niet klaar is
      if (this.audio.readyState < 3) {
        this.showLoading();
      }
      
      this.audio.play().catch(e => {
        console.error('Fout bij afspelen:', e);
        this.hideLoading();
        alert('Kon audio niet afspelen. Controleer je internetverbinding.');
      });
    }
  }

  updatePlayButton() {
    const playBtn = document.getElementById('playBtn');
    const icon = playBtn.querySelector('.material-icons');
    icon.textContent = this.isPlaying ? 'pause' : 'play_arrow';
  }

  previousSura() {
    if (this.currentIndex > 0) {
      this.selectSura(this.currentIndex - 1);
    }
  }

  nextSura() {
    if (this.currentIndex < this.suras.length - 1) {
      this.selectSura(this.currentIndex + 1);
    }
  }

  seekTo(percentage) {
    if (this.audio.duration) {
      this.audio.currentTime = (this.audio.duration * percentage) / 100;
    }
  }

  directPlay() {
    if (!this.currentReciter || this.currentIndex === undefined) {
      alert('Selecteer eerst een reciteur en sura');
      return;
    }
    
    const sura = this.suras[this.currentIndex];
    const url = `https://download.quranicaudio.com/quran/${this.currentReciter}/${sura.file}.mp3`;
    
    console.log('Opening direct play:', url);
    window.open(url, '_blank');
  }

  showDirectPlayOption() {
    document.getElementById('directPlayBtn').style.display = 'flex';
  }

  setupAudioEvents() {
    this.audio.addEventListener('loadstart', () => {
      console.log('Audio loading started');
      this.showLoading();
    });

    this.audio.addEventListener('loadedmetadata', () => {
      console.log('Audio metadata loaded');
      this.hideLoading();
    });

    this.audio.addEventListener('loadeddata', () => {
      console.log('Audio data loaded');
      this.hideLoading();
    });

    this.audio.addEventListener('canplay', () => {
      console.log('Audio can play');
      this.hideLoading();
    });

    this.audio.addEventListener('canplaythrough', () => {
      console.log('Audio can play through');
      this.hideLoading();
    });

    this.audio.addEventListener('play', () => {
      console.log('Audio started playing');
      this.isPlaying = true;
      this.updatePlayButton();
      this.hideLoading();
      document.querySelectorAll('.sura-item')[this.currentIndex]?.classList.add('playing');
    });

    this.audio.addEventListener('pause', () => {
      console.log('Audio paused');
      this.isPlaying = false;
      this.updatePlayButton();
      document.querySelectorAll('.sura-item')[this.currentIndex]?.classList.remove('playing');
    });

    this.audio.addEventListener('timeupdate', () => {
      if (this.audio.duration) {
        const progress = (this.audio.currentTime / this.audio.duration) * 100;
        document.getElementById('progressBar').value = progress;
        
        document.getElementById('currentTime').textContent = this.formatTime(this.audio.currentTime);
        document.getElementById('totalTime').textContent = this.formatTime(this.audio.duration);
      }
    });

    this.audio.addEventListener('ended', () => {
      console.log('Audio ended');
      this.nextSura();
    });

    this.audio.addEventListener('error', (e) => {
      console.error('Audio error:', e, this.audio.error);
      this.hideLoading();
      this.showDirectPlayOption(); // Toon direct play optie bij fout
      
      let errorMsg = 'Fout bij laden van audio.';
      if (this.audio.error) {
        switch(this.audio.error.code) {
          case 1:
            errorMsg = 'Audio laden afgebroken.';
            break;
          case 2:
            errorMsg = 'Netwerk fout bij laden audio.';
            break;
          case 3:
            errorMsg = 'Audio formaat niet ondersteund.';
            break;
          case 4:
            errorMsg = 'Audio bestand niet gevonden.';
            break;
        }
      }
      alert(errorMsg + ' Probeer de "Direct afspelen" knop of een andere reciteur.');
    });

    this.audio.addEventListener('waiting', () => {
      console.log('Audio waiting/buffering');
      this.showLoading();
    });

    this.audio.addEventListener('playing', () => {
      console.log('Audio playing (after buffering)');
      this.hideLoading();
    });

    this.audio.addEventListener('stalled', () => {
      console.log('Audio stalled');
      this.hideLoading();
    });

    this.audio.addEventListener('suspend', () => {
      console.log('Audio suspended');
      this.hideLoading();
    });

    this.audio.addEventListener('abort', () => {
      console.log('Audio aborted');
      this.hideLoading();
    });

    // Timeout voor loading state
    this.audio.addEventListener('loadstart', () => {
      setTimeout(() => {
        if (document.querySelector('.player-section').classList.contains('loading')) {
          console.log('Loading took too long, showing direct play option');
          this.hideLoading();
          this.showDirectPlayOption();
        }
      }, 8000); // 8 seconden timeout
    });
  }

  formatTime(seconds) {
    if (isNaN(seconds)) return '0:00';
    
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }
}

// Initialiseer de Quran speler wanneer de pagina geladen is
document.addEventListener('DOMContentLoaded', () => {
  console.log('DOM loaded, initializing QuranPlayer...');
  new QuranPlayer();
}); 