<script>
  let surahs = $state([]);
  let selectedSurah = $state(null);
  let ayahs = $state([]);
  let arabicAyahs = $state([]);
  let loading = $state(true);
  let error = $state('');
  let showArabic = $state(true);
  let showEnglish = $state(true);
  let playingAyah = $state(null);
  let audio = $state(null);

  async function loadSurahs() {
    try {
      const res = await fetch('https://api.alquran.cloud/v1/surah');
      const data = await res.json();
      if (data.code === 200) surahs = data.data;
      loading = false;
    } catch (e) {
      error = 'Network error';
      loading = false;
    }
  }

  async function loadSurah(num) {
    loading = true;
    stopAudio();
    try {
      const [arRes, enRes] = await Promise.all([
        fetch(`https://api.alquran.cloud/v1/surah/${num}/ar.alafasy`),
        fetch(`https://api.alquran.cloud/v1/surah/${num}/en.asad`)
      ]);
      const [arData, enData] = await Promise.all([arRes.json(), enRes.json()]);
      
      if (arData.code === 200 && enData.code === 200) {
        selectedSurah = { 
          num, 
          name: enData.data.englishName, 
          english: enData.data.englishNameTranslation, 
          arabicName: arData.data.name,
          type: enData.data.revelationType 
        };
        ayahs = enData.data.ayahs;
        arabicAyahs = arData.data.ayahs;
      }
      loading = false;
    } catch (e) {
      error = 'Failed to load surah';
      loading = false;
    }
  }

  function goBack() {
    selectedSurah = null;
    ayahs = [];
    arabicAyahs = [];
    stopAudio();
  }

  function stopAudio() {
    if (audio) {
      audio.pause();
      audio = null;
    }
    playingAyah = null;
  }

  function playAyah(surahNum, ayahNum) {
    stopAudio();
    const surahStr = String(surahNum).padStart(3, '0');
    const ayahStr = String(ayahNum).padStart(3, '0');
    const url = `https://everyayah.com/data/Alafasy_128kbps/${surahStr}${ayahStr}.mp3`;
    
    audio = new Audio(url);
    playingAyah = ayahNum;
    
    audio.onended = () => {
      playingAyah = null;
      audio = null;
    };
    
    audio.onerror = () => {
      playingAyah = null;
      audio = null;
    };
    
    audio.play().catch(() => {
      playingAyah = null;
      audio = null;
    });
  }

  function togglePlay(surahNum, ayahNum) {
    if (playingAyah === ayahNum) {
      stopAudio();
    } else {
      playAyah(surahNum, ayahNum);
    }
  }

  $effect(() => { loadSurahs(); });
  $effect(() => () => stopAudio());
</script>

<div class="card">
  <h2>📖 Holy Quran</h2>

  {#if loading}
    <p class="loading">⏳ Loading…</p>
  {:else if error}
    <p class="error">{error}</p>
  {:else if selectedSurah}
    <div class="surah-header">
      <button class="secondary back-btn" onclick={goBack}>← Surahs</button>
      <div class="surah-title-block">
        <h3>{selectedSurah.name}</h3>
        <span class="surah-english">({selectedSurah.english})</span>
        <span class="surah-arabic" dir="rtl">{selectedSurah.arabicName}</span>
      </div>
      <span class="surah-type">{selectedSurah.type}</span>
      <div class="view-toggles">
        <label>
          <input type="checkbox" bind:checked={showArabic} />
          <span>Arabic</span>
        </label>
        <label>
          <input type="checkbox" bind:checked={showEnglish} />
          <span>English</span>
        </label>
      </div>
    </div>
    <div class="ayah-list">
      {#each ayahs as ayah, i}
        <div class="ayah">
          <span class="ayah-num">{ayah.numberInSurah}</span>
          <div class="ayah-content">
            {#if showArabic && arabicAyahs[i]}
              <p class="ayah-text arabic" dir="rtl">{arabicAyahs[i].text}</p>
            {/if}
            {#if showEnglish}
              <p class="ayah-text english">{ayah.text}</p>
            {/if}
          </div>
          <button 
            class="audio-btn"
            class:playing={playingAyah === ayah.numberInSurah}
            onclick={() => togglePlay(selectedSurah.num, ayah.numberInSurah)}
            aria-label={playingAyah === ayah.numberInSurah ? 'Pause' : 'Play'}
          >
            {#if playingAyah === ayah.numberInSurah}⏸{:else}▶{/if}
          </button>
        </div>
      {/each}
    </div>
  {:else}
    <div class="surah-grid">
      {#each surahs as s}
        <button class="surah-btn" onclick={() => loadSurah(s.number)}>
          <span class="surah-num">{s.number}</span>
          <div class="surah-info">
            <span class="surah-name">{s.englishName}</span>
            <span class="surah-arabic" dir="rtl">{s.name}</span>
            <span class="surah-ayahs">{s.numberOfAyahs} ayahs</span>
          </div>
        </button>
      {/each}
    </div>
  {/if}
</div>

<style>
  .loading { color: var(--text-dim); text-align: center; padding: 20px; }
  .error { color: #FF6B6B; text-align: center; padding: 10px; }

  .surah-grid {
    display: flex;
    flex-direction: column;
    gap: 4px;
    max-height: 60vh;
    overflow-y: auto;
  }
  
  .surah-btn {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    border: 1px solid var(--border);
    background: var(--bg2);
    border-radius: 12px;
    cursor: pointer;
    text-align: left;
    font-size: 0.9rem;
    transition: all 0.15s;
  }
  
  .surah-btn:hover { border-color: var(--gold); background: var(--gold-dim); }
  .surah-btn:active { background: var(--gold-dim); }
  
  .surah-num {
    font-family: 'Cinzel', serif;
    font-weight: 700;
    color: var(--gold);
    background: var(--gold-dim);
    border: 1px solid var(--border);
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    flex-shrink: 0;
  }
  
  .surah-info { flex: 1; display: flex; flex-direction: column; gap: 2px; }
  .surah-name { font-family: 'DM Sans', sans-serif; font-weight: 600; color: var(--text); }
  .surah-arabic { 
    font-family: 'DM Sans', sans-serif;
    font-size: 0.9rem;
    color: var(--gold);
    text-align: right;
    direction: rtl;
  }
  .surah-ayahs { 
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.62rem;
    letter-spacing: 0.05em;
    color: var(--text-dim);
  }
  
  .surah-header { 
    margin-bottom: 16px; 
    display: flex; 
    flex-direction: column; 
    gap: 12px; 
    align-items: flex-start;
    padding-bottom: 12px;
    border-bottom: 1px solid var(--border);
  }
  
  .surah-title-block { display: flex; flex-direction: column; gap: 4px; }
  
  .surah-title-block h3 { 
    font-family: 'Cinzel', serif;
    font-size: 1.3rem;
    font-weight: 700;
    color: var(--text);
    margin: 0;
  }
  
  .surah-english { 
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.7rem;
    letter-spacing: 0.05em;
    color: var(--gold);
  }
  
  .surah-arabic { 
    font-family: 'DM Sans', sans-serif;
    font-size: 1.1rem;
    color: var(--gold);
    direction: rtl;
    text-align: right;
  }
  
  .surah-type { 
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.6rem;
    letter-spacing: 0.1em;
    text-transform: uppercase;
    color: var(--green);
    background: var(--green-dim);
    border: 1px solid var(--border-green);
    padding: 4px 10px;
    border-radius: 4px;
  }
  
  .back-btn { padding: 8px 12px; font-size: 0.7rem; }
  
  .view-toggles {
    display: flex;
    gap: 16px;
    font-family: 'JetBrains Mono', monospace;
    font-size: 0.65rem;
    letter-spacing: 0.05em;
    color: var(--text-dim);
  }
  
  .view-toggles label {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
  }
  
  .view-toggles input[type="checkbox"] {
    width: 16px;
    height: 16px;
    accent-color: var(--gold);
    border: 1px solid var(--border);
    border-radius: 4px;
  }
  
  .ayah-list { max-height: 60vh; overflow-y: auto; }
  
  .ayah {
    display: flex;
    gap: 12px;
    padding: 14px 0;
    border-bottom: 1px solid var(--border);
    align-items: flex-start;
  }
  
  .ayah:last-child { border-bottom: none; }
  
  .ayah-num {
    font-family: 'Cinzel', serif;
    font-weight: 700;
    font-size: 0.85rem;
    color: var(--gold);
    min-width: 28px;
    text-align: center;
    flex-shrink: 0;
    margin-top: 2px;
  }
  
  .ayah-content { flex: 1; display: flex; flex-direction: column; gap: 8px; }
  
  .ayah-text { margin: 0; line-height: 1.7; }
  
  .ayah-text.arabic { 
    font-family: 'Amiri', 'Noto Naskh Arabic', serif;
    font-size: 1.25rem;
    line-height: 2;
    color: var(--gold);
    text-shadow: 0 0 10px rgba(201,168,76,0.2);
  }
  
  .ayah-text.english { 
    font-family: 'DM Sans', sans-serif;
    font-size: 0.9rem;
    color: var(--text-dim);
  }
  
  .audio-btn {
    font-family: 'Cinzel', serif;
    border: 1px solid var(--border);
    background: var(--bg2);
    border-radius: 50%;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 0.85rem;
    color: var(--gold);
    flex-shrink: 0;
    transition: all 0.15s;
  }
  
  .audio-btn:hover,
  .audio-btn.playing { 
    background: var(--gold-dim);
    border-color: var(--gold);
    transform: scale(1.05);
  }
</style>