// Application State
const state = {
  activeView: 'viewHome',
  currentSurahId: 18, // Default to Al-Kahf
  currentSurahData: null,
  activeAyahIndex: 1,
  selectedReciter: window.RECITERS ? window.RECITERS[0] : { id: "ar.dussary", name: "ياسر الدوسري", serverId: "Yasser_Ad-Dussary_128kbps" },
  isPlaying: false,
  autoNextAyah: true,
  autoScroll: true,
  playbackSpeed: 1,
  showTranslation: true,
  fontSize: 28,
  theme: 'dark',
  zenMode: false,
  activeTafsirEdition: 'ar.muyassar',
  bookmarks: [],
  lastRead: { surahId: 18, ayahNum: 1, time: Date.now() },
  azkarCategory: 'morning',
  azkarProgress: {},
  tasbihCount: 0,
  tasbihZikr: 'سُبْحَانَ اللَّهِ',
  cachedSurahs: {},
  prayerCity: 'Cairo,Egypt',
  prayerTimesData: null,
  prayerCountdownTimer: null,
  khatmah: {
    mode: 'reading', // 'reading' or 'listening'
    planDays: 30,
    readSurahs: [],
    listenedSurahs: [],
    listeningReciterId: 'ar.dussary',
    streakDays: 1,
    lastActiveDate: new Date().toDateString()
  }
};

// Audio Engine
const audioPlayer = document.getElementById('audioEngine');

// Web Audio API for gentle feedback sounds
let audioCtx = null;
function playBeep(freq = 600, duration = 0.08) {
  try {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    if (audioCtx.state === 'suspended') audioCtx.resume();
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = 'sine';
    osc.frequency.value = freq;
    gain.gain.setValueAtTime(0.08, audioCtx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.0001, audioCtx.currentTime + duration);
    osc.connect(gain);
    gain.connect(audioCtx.destination);
    osc.start();
    osc.stop(audioCtx.currentTime + duration);
  } catch (e) {}
}

// Arabic Digits Formatter
function toArabicDigits(num) {
  const arabicDigits = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
  return String(num).replace(/[0-9]/g, w => arabicDigits[+w]);
}

// Hijri Date Calculation
function updateHijriDates() {
  try {
    const today = new Date();
    const options = { day: 'numeric', month: 'long', year: 'numeric', calendar: 'islamic-umalqura' };
    let hijriStr = new Intl.DateTimeFormat('ar-SA-u-ca-islamic', options).format(today);
    
    // Add "هـ" suffix if not present
    if (!hijriStr.includes('هـ')) hijriStr += ' هـ';

    const topEl = document.getElementById('hijriDateDisplay');
    const heroEl = document.getElementById('heroHijriDate');
    const prayerPill = document.getElementById('prayerSectionHijriPill');

    if (topEl) topEl.textContent = hijriStr;
    if (heroEl) heroEl.textContent = hijriStr;
    if (prayerPill) prayerPill.textContent = hijriStr;
  } catch (e) {
    const fallback = '١٥ رمضان ١٤٤٥ هـ';
    const topEl = document.getElementById('hijriDateDisplay');
    if (topEl) topEl.textContent = fallback;
  }
}

// Initialize on DOM Ready
document.addEventListener('DOMContentLoaded', () => {
  loadSavedState();
  initTheme();
  updateHijriDates();
  setupEventListeners();
  renderSurahsList();
  renderJuzsList();
  renderRecitersList();
  renderAzkarCategories();
  renderAzkarCards('morning');
  renderBookmarksList();
  initKhatmahModule();
  initPrayerTimesModule();
  updateHeroLastReadBanner();
  updateSidebarProgress();
  setupAudioListeners();
});

// Load state from localStorage
function loadSavedState() {
  const savedBookmarks = localStorage.getItem('quran_bookmarks');
  if (savedBookmarks) {
    try { state.bookmarks = JSON.parse(savedBookmarks); } catch (e) {}
  }

  const savedLastRead = localStorage.getItem('quran_last_read');
  if (savedLastRead) {
    try { state.lastRead = JSON.parse(savedLastRead); } catch (e) {}
  }

  const savedTheme = localStorage.getItem('quran_theme');
  if (savedTheme) {
    state.theme = savedTheme;
  }

  const savedFontSize = localStorage.getItem('quran_font_size');
  if (savedFontSize) {
    state.fontSize = parseInt(savedFontSize);
    document.documentElement.style.setProperty('--quran-font-size', `${state.fontSize}px`);
    const sizeDisplay = document.getElementById('fontSizeDisplay');
    if (sizeDisplay) sizeDisplay.textContent = `${state.fontSize}px`;
    const settingsSlider = document.getElementById('settingsFontSizeSlider');
    if (settingsSlider) settingsSlider.value = state.fontSize;
    const settingsLabel = document.getElementById('settingsFontSizeLabel');
    if (settingsLabel) settingsLabel.textContent = `${state.fontSize}px`;
  }

  const savedReciterId = localStorage.getItem('quran_reciter_id');
  if (savedReciterId && window.RECITERS) {
    const found = window.RECITERS.find(r => r.id === savedReciterId);
    if (found) state.selectedReciter = found;
  }

  const savedTasbih = localStorage.getItem('quran_tasbih_count');
  if (savedTasbih) {
    state.tasbihCount = parseInt(savedTasbih) || 0;
    const tasbihEl = document.getElementById('tasbihCounterNum');
    if (tasbihEl) tasbihEl.textContent = state.tasbihCount;
  }

  const savedKhatmah = localStorage.getItem('quran_khatmah_data');
  if (savedKhatmah) {
    try {
      const parsed = JSON.parse(savedKhatmah);
      state.khatmah = { ...state.khatmah, ...parsed };
    } catch (e) {}
  }

  const savedCity = localStorage.getItem('quran_prayer_city');
  if (savedCity) {
    state.prayerCity = savedCity;
    const citySelect = document.getElementById('prayerCitySelect');
    if (citySelect) citySelect.value = savedCity;
  }
}

// Theme handling
function initTheme() {
  document.documentElement.setAttribute('data-theme', state.theme);
  updateThemeActiveButtons();
}

function setTheme(themeName) {
  state.theme = themeName;
  document.documentElement.setAttribute('data-theme', themeName);
  localStorage.setItem('quran_theme', themeName);
  updateThemeActiveButtons();
  showToast(`تم تغيير المظهر إلى النمط ${themeName === 'dark' ? 'الداكن' : themeName === 'sepia' ? 'الورقي' : 'الأصيل'}`);
}

function updateThemeActiveButtons() {
  document.querySelectorAll('.theme-select-btn').forEach(btn => {
    if (btn.dataset.setTheme === state.theme) {
      btn.classList.add('border-primary', 'shadow-md');
      btn.classList.remove('border-border-subtle');
    } else {
      btn.classList.remove('border-primary', 'shadow-md');
      btn.classList.add('border-border-subtle');
    }
  });
}

// ================= NAVIGATION & ROUTING =================
function switchView(viewId) {
  document.querySelectorAll('.view-panel').forEach(panel => {
    panel.classList.add('hidden');
  });

  const target = document.getElementById(viewId);
  if (target) {
    target.classList.remove('hidden');
    state.activeView = viewId;
  }

  document.querySelectorAll('.nav-item').forEach(btn => {
    if (btn.dataset.target === viewId) {
      btn.classList.add('bg-primary-container', 'text-on-primary', 'font-bold', 'shadow-sm');
      btn.classList.remove('text-on-surface-variant');
    } else {
      btn.classList.remove('bg-primary-container', 'text-on-primary', 'font-bold', 'shadow-sm');
      btn.classList.add('text-on-surface-variant');
    }
  });

  if (viewId !== 'viewReader' && state.zenMode) {
    toggleZenMode(false);
  }
}

window.quickOpenAzkar = (catId) => {
  state.azkarCategory = catId;
  switchView('viewAzkar');
  renderAzkarCategories();
  renderAzkarCards(catId);
};

// Arabic normalization utility for accurate searching
function normalizeArabic(text) {
  if (!text) return '';
  return text
    .replace(/[\u064B-\u065F\u0670\u06D6-\u06ED]/g, '') // Remove Tashkeel, Sukun, Tanween & Quranic stop marks
    .replace(/[إأآا]/g, 'ا')
    .replace(/ى/g, 'ي')
    .replace(/ة/g, 'ه')
    .replace(/ؤ/g, 'و')
    .replace(/ئ/g, 'ي')
    .trim()
    .toLowerCase();
}

let searchDebounceTimer = null;

// ================= SURAH & JUZ & AYAH RENDERING & SEARCH =================
function renderSurahsList(filterQuery = '', typeFilter = 'all') {
  const container = document.getElementById('surahsGrid');
  const ayahResultsContainer = document.getElementById('ayahSearchResultsContainer');
  const clearBtn = document.getElementById('clearSearchBtn');
  if (!container || !window.SURAHS_DATA) return;

  const rawQuery = filterQuery.trim();
  const normQuery = normalizeArabic(rawQuery);
  const isNumeric = /^\d+$/.test(rawQuery);

  if (clearBtn) {
    clearBtn.classList.toggle('hidden', rawQuery.length === 0);
  }

  const filtered = window.SURAHS_DATA.filter(s => {
    const matchesName = normalizeArabic(s.name).includes(normQuery);
    const matchesEng = s.englishName.toLowerCase().includes(rawQuery.toLowerCase());
    const matchesTrans = s.englishTranslation.toLowerCase().includes(rawQuery.toLowerCase());
    const matchesNum = isNumeric && s.id.toString() === rawQuery;

    const matchesQuery = !rawQuery || matchesName || matchesEng || matchesTrans || matchesNum;
    const matchesType = typeFilter === 'all' || s.revelationType === typeFilter;
    return matchesQuery && matchesType;
  });

  if (filtered.length === 0) {
    if (rawQuery.length < 2) {
      container.innerHTML = `
        <div class="col-span-full py-16 text-center text-on-surface-variant">
          <span class="material-symbols-outlined text-4xl mb-2 opacity-50">search_off</span>
          <p class="font-bold text-base">لم نجد أي سورة مطابقة لبحثك</p>
          <p class="text-xs opacity-80 mt-1">جرب البحث باسم السورة أو رقمها (مثال: الكهف أو 18)</p>
        </div>
      `;
    } else {
      container.innerHTML = ''; // Keep surahs container clean while showing ayah search results
    }
  } else {
    container.innerHTML = filtered.map(surah => {
      const isLastRead = state.lastRead && state.lastRead.surahId === surah.id;
      const progressPercent = isLastRead ? Math.min(100, Math.round((state.lastRead.ayahNum / surah.versesCount) * 100)) : 0;

      return `
        <div class="surah-card group relative bg-surface p-5 rounded-2xl border border-border-subtle hover:border-primary/40 shadow-sm cursor-pointer overflow-hidden flex flex-col justify-between"
             data-surah-id="${surah.id}">
          
          <div class="absolute right-0 top-0 bottom-0 w-1.5 bg-transparent group-hover:bg-primary transition-colors"></div>

          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-3">
              <div class="ayah-number-badge">
                <svg viewBox="0 0 40 40">
                  <path d="M20 2L32.7279 7.27208L38 20L32.7279 32.7279L20 38L7.27208 32.7279L2 20L7.27208 7.27208L20 2Z" />
                </svg>
                <span>${surah.id}</span>
              </div>
              
              <div>
                <h4 class="font-display-title font-bold text-lg text-on-surface group-hover:text-primary transition-colors">
                  سُورَةُ ${surah.name}
                </h4>
                <p class="text-xs text-on-surface-variant opacity-80 font-body">${surah.englishName} • ${surah.englishTranslation}</p>
              </div>
            </div>

            <span class="px-2.5 py-1 rounded-full text-[11px] font-bold ${surah.revelationType === 'مكية' ? 'bg-primary/10 text-primary' : 'bg-tertiary/15 text-tertiary'}">
              ${surah.revelationType}
            </span>
          </div>

          <div class="flex items-center justify-between text-xs text-on-surface-variant pt-2 border-t border-border-subtle">
            <span class="flex items-center gap-1">
              <span class="material-symbols-outlined text-[15px] opacity-70">notes</span>
              ${surah.versesCount} آية
            </span>
            <span class="flex items-center gap-1 font-semibold text-primary">
              <span>الجزء ${surah.juz}</span>
              <span class="material-symbols-outlined text-[16px] group-hover:-translate-x-1 transition-transform">arrow_back</span>
            </span>
          </div>

          <div class="h-1 w-full bg-surface-container-highest rounded-full overflow-hidden mt-3">
            <div class="h-full bg-gold-accent transition-all duration-300" style="width: ${progressPercent}%;"></div>
          </div>
        </div>
      `;
    }).join('');

    container.querySelectorAll('.surah-card').forEach(card => {
      card.addEventListener('click', () => {
        const surahId = parseInt(card.dataset.surahId);
        openSurahReader(surahId);
      });
    });
  }

  // Trigger Full Ayah Search if query is 2+ characters
  if (rawQuery.length >= 2) {
    if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
    searchDebounceTimer = setTimeout(() => {
      searchQuranVerses(rawQuery, filtered.length);
    }, 280);
  } else {
    if (ayahResultsContainer) {
      ayahResultsContainer.classList.add('hidden');
      ayahResultsContainer.innerHTML = '';
    }
  }
}

// Global Ayah Full-text Search Engine
async function searchQuranVerses(rawQuery, matchedSurahsCount = 0) {
  const container = document.getElementById('ayahSearchResultsContainer');
  if (!container) return;

  container.classList.remove('hidden');
  container.innerHTML = `
    <div class="p-8 text-center bg-surface rounded-3xl border border-border-subtle space-y-3">
      <div class="w-8 h-8 border-3 border-primary border-t-transparent rounded-full animate-spin mx-auto"></div>
      <p class="text-xs font-bold text-primary">جاري البحث في آيات القرآن الكريم عن «${rawQuery}»...</p>
    </div>
  `;

  try {
    const res = await fetch(`https://api.alquran.cloud/v1/search/${encodeURIComponent(rawQuery)}/all/ar`);
    if (!res.ok) throw new Error('Search API error');
    const json = await res.json();
    const matches = json.data && json.data.matches ? json.data.matches : [];

    renderAyahSearchResults(matches, rawQuery, matchedSurahsCount);
  } catch (err) {
    console.warn('Quran search API error:', err);
    container.innerHTML = `
      <div class="p-6 text-center bg-surface rounded-3xl border border-border-subtle text-on-surface-variant">
        <p class="text-xs font-bold">تعذر البحث السحابي في الآيات، تأكد من اتصالك بالإنترنت.</p>
      </div>
    `;
  }
}

function renderAyahSearchResults(matches, query, matchedSurahsCount) {
  const container = document.getElementById('ayahSearchResultsContainer');
  if (!container) return;

  if (matches.length === 0) {
    if (matchedSurahsCount === 0) {
      container.innerHTML = `
        <div class="p-12 text-center bg-surface rounded-3xl border border-border-subtle space-y-3">
          <span class="material-symbols-outlined text-4xl text-on-surface-variant opacity-50">search_off</span>
          <h4 class="font-bold text-base text-on-surface">لم نجد أي آية أو سورة مطابقة لـ «${query}»</h4>
          <p class="text-xs text-on-surface-variant">تأكد من كتابة الكلمات بشكل صحيح أو جرب البحث بكلمة أخرى من الآية.</p>
        </div>
      `;
    } else {
      container.innerHTML = '';
      container.classList.add('hidden');
    }
    return;
  }

  const normQ = normalizeArabic(query);
  const words = normQ.split(' ').filter(w => w.length > 1);

  container.innerHTML = `
    <div class="space-y-4 pt-4 border-t border-border-subtle">
      <div class="flex items-center justify-between">
        <h3 class="font-display-title text-lg font-bold text-gold-accent flex items-center gap-2">
          <span class="material-symbols-outlined text-gold-accent">menu_book</span>
          <span>نتائج البحث في الآيات الكريمة (${matches.length} آية)</span>
        </h3>
        <span class="text-xs font-semibold text-primary bg-primary/10 border border-primary/25 px-3 py-1 rounded-full">
          تم العثور على «${query}»
        </span>
      </div>

      <div class="space-y-3">
        ${matches.map(m => {
          const surahNum = m.surah.number;
          const ayahNum = m.numberInSurah;
          const surahMeta = window.SURAHS_DATA ? window.SURAHS_DATA.find(s => s.id === surahNum) : null;
          const surahName = surahMeta ? surahMeta.name : m.surah.name;
          const revType = surahMeta ? surahMeta.revelationType : (m.surah.revelationType === 'Meccan' ? 'مكية' : 'مدنية');
          const juzNum = surahMeta ? surahMeta.juz : 1;

          // Highlight matching words in verse
          let highlightedText = m.text;
          words.forEach(w => {
            const regex = new RegExp(`(${w})`, 'gi');
            highlightedText = highlightedText.replace(regex, '<mark class="bg-primary/20 text-primary font-bold px-1 py-0.5 rounded border border-primary/40">$1</mark>');
          });

          return `
            <div class="bg-surface p-6 rounded-3xl border border-border-subtle hover:border-gold-accent/50 shadow-sm space-y-3.5 transition-all">
              <div class="flex items-center justify-between border-b border-border-subtle pb-2.5">
                <div class="flex items-center gap-2.5">
                  <div class="w-8 h-8 rounded-xl bg-gold-accent/15 text-gold-accent flex items-center justify-center font-bold text-xs">
                    ${ayahNum}
                  </div>
                  <div>
                    <span class="font-bold text-sm text-on-surface">سورة ${surahName}</span>
                    <span class="text-xs text-on-surface-variant opacity-75 mr-2">الآية ${ayahNum} • الجزء ${juzNum} • ${revType}</span>
                  </div>
                </div>

                <div class="flex items-center gap-2">
                  <button class="px-4 py-1.5 rounded-xl bg-primary text-slate-950 font-bold text-xs shadow-sm hover:bg-primary-glow transition-all flex items-center gap-1.5"
                          onclick="openSurahReader(${surahNum}, ${ayahNum})">
                    <span>قراءة في المصحف</span>
                    <span class="material-symbols-outlined text-[16px]">auto_stories</span>
                  </button>

                  <button class="w-8 h-8 rounded-xl bg-surface-container hover:bg-surface-container-high text-primary flex items-center justify-center transition-colors"
                          title="استماع للآية" onclick="window.playSearchResultAyah(${surahNum}, ${ayahNum})">
                    <span class="material-symbols-outlined text-[18px]">play_arrow</span>
                  </button>
                </div>
              </div>

              <p class="font-quran-script text-base md:text-lg leading-loose text-on-surface text-right select-text" dir="rtl">
                ${highlightedText}
                <span class="ayah-number-badge inline-block mr-1">
                  <svg viewBox="0 0 40 40">
                    <path d="M20 2L32.7279 7.27208L38 20L32.7279 32.7279L20 38L7.27208 32.7279L2 20L7.27208 7.27208L20 2Z" />
                  </svg>
                  <span>${ayahNum}</span>
                </span>
              </p>
            </div>
          `;
        }).join('')}
      </div>
    </div>
  `;
}

window.playSearchResultAyah = (surahId, ayahNum) => {
  openSurahReader(surahId, ayahNum).then(() => {
    playAyahAudio(surahId, ayahNum);
  });
};

function renderJuzsList() {
  const container = document.getElementById('juzsGrid');
  if (!container || !window.JUZ_DATA) return;

  container.innerHTML = window.JUZ_DATA.map(j => {
    const startSurah = window.SURAHS_DATA.find(s => s.id === j.startSurah);
    const endSurah = window.SURAHS_DATA.find(s => s.id === j.endSurah);

    return `
      <div class="juz-card group bg-surface p-5 rounded-2xl border border-border-subtle hover:border-primary/40 shadow-sm cursor-pointer transition-all hover:-translate-y-1"
           data-start-surah="${j.startSurah}" data-start-ayah="${j.startAyah}">
        <div class="flex items-center justify-between mb-3">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-primary-container text-on-primary flex items-center justify-center font-bold text-sm shadow-sm">
              ${j.juz}
            </div>
            <div>
              <h4 class="font-display-title font-bold text-base text-on-surface group-hover:text-primary transition-colors">
                ${j.name}
              </h4>
              <p class="text-xs text-on-surface-variant">من سورة ${startSurah?.name || ''} إلى ${endSurah?.name || ''}</p>
            </div>
          </div>
          <span class="material-symbols-outlined text-primary group-hover:-translate-x-1 transition-transform">arrow_back</span>
        </div>
      </div>
    `;
  }).join('');

  container.querySelectorAll('.juz-card').forEach(card => {
    card.addEventListener('click', () => {
      const surahId = parseInt(card.dataset.startSurah);
      const ayahNum = parseInt(card.dataset.startAyah);
      openSurahReader(surahId, ayahNum);
    });
  });
}

// ================= QURAN READER VIEW =================
async function openSurahReader(surahId, startAyahNum = 1) {
  state.currentSurahId = surahId;
  state.activeAyahIndex = startAyahNum;
  
  const surah = window.SURAHS_DATA.find(s => s.id === surahId);
  if (!surah) return;

  switchView('viewReader');

  document.getElementById('readerSurahTitle').textContent = `سورة ${surah.name}`;
  document.getElementById('readerSurahMeta').textContent = `${surah.revelationType} • ${surah.versesCount} آيات • الجزء ${surah.juz} • الصفحة ${surah.page}`;
  document.getElementById('readerHeroSurahName').textContent = `سُورَةُ ${surah.name}`;
  document.getElementById('readerHeroSurahSub').textContent = `${surah.englishName} (${surah.englishTranslation}) • ${surah.versesCount} Verses`;
  
  const bannerReciterLabel = document.getElementById('readerReciterNameBanner');
  if (bannerReciterLabel) bannerReciterLabel.textContent = state.selectedReciter.name;

  // Bind Full Surah buttons specifically to this Surah
  const fullSurahTopBtn = document.getElementById('playFullSurahTopBtn');
  const fullSurahBannerBtn = document.getElementById('playFullSurahBannerBtn');
  if (fullSurahTopBtn) {
    fullSurahTopBtn.onclick = (e) => {
      e.stopPropagation();
      playFullSurah(surahId);
    };
  }
  if (fullSurahBannerBtn) {
    fullSurahBannerBtn.onclick = (e) => {
      e.stopPropagation();
      playFullSurah(surahId);
    };
  }

  const bismillahBanner = document.getElementById('bismillahBanner');
  if (surahId === 9 || surahId === 1) {
    bismillahBanner.classList.add('hidden');
  } else {
    bismillahBanner.classList.remove('hidden');
  }

  saveLastRead(surahId, startAyahNum);
  renderAyahJumpBar(surah.versesCount);
  await loadSurahVerses(surahId, startAyahNum);
}

function renderAyahJumpBar(totalVerses) {
  const jumpList = document.getElementById('ayahJumpList');
  if (!jumpList) return;

  const step = totalVerses > 100 ? 10 : totalVerses > 50 ? 5 : 1;
  const jumps = [];
  for (let i = 1; i <= totalVerses; i += step) {
    jumps.push(i);
  }
  if (jumps[jumps.length - 1] !== totalVerses) {
    jumps.push(totalVerses);
  }

  jumpList.innerHTML = jumps.map(num => `
    <button class="ayah-jump-btn w-9 h-8 rounded-lg text-xs font-bold text-on-surface-variant hover:bg-surface-container-highest hover:text-primary transition-colors ${num === state.activeAyahIndex ? 'bg-primary text-on-primary shadow-sm' : 'bg-surface'}"
            data-ayah="${num}">
      ${num}
    </button>
  `).join('');

  jumpList.querySelectorAll('.ayah-jump-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const ayah = parseInt(btn.dataset.ayah);
      scrollToAyah(ayah);
    });
  });
}

async function loadSurahVerses(surahId, targetAyah = 1) {
  const container = document.getElementById('versesList');
  if (!container) return;

  container.innerHTML = `
    <div class="py-20 text-center space-y-3">
      <div class="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto"></div>
      <p class="font-bold text-primary text-sm">جاري تحميل آيات المصحف الشريف والتفسير...</p>
    </div>
  `;

  try {
    let surahData = state.cachedSurahs[surahId];
    if (!surahData) {
      const res = await fetch(`https://api.alquran.cloud/v1/surah/${surahId}/editions/quran-uthmani,en.sahih,ar.muyassar`);
      if (!res.ok) throw new Error('API fetch error');
      const json = await res.json();
      surahData = {
        arabic: json.data[0].ayahs,
        english: json.data[1].ayahs,
        tafsir: json.data[2].ayahs
      };
      state.cachedSurahs[surahId] = surahData;
    }

    state.currentSurahData = surahData;
    renderVersesContent(surahData, targetAyah);
  } catch (err) {
    console.warn('Using offline scripture generator for Surah', surahId);
    generateFallbackSurah(surahId, targetAyah);
  }
}

function renderVersesContent(surahData, targetAyah = 1) {
  const container = document.getElementById('versesList');
  if (!container) return;

  const { arabic, english, tafsir } = surahData;

  container.innerHTML = arabic.map((ayah, idx) => {
    const ayahNumberInSurah = ayah.numberInSurah;
    const isBookmarked = state.bookmarks.some(b => b.surahId === state.currentSurahId && b.ayahNum === ayahNumberInSurah);
    const engText = english && english[idx] ? english[idx].text : '';
    const tafsirText = tafsir && tafsir[idx] ? tafsir[idx].text : '';

    return `
      <div id="ayah-row-${ayahNumberInSurah}" 
           class="ayah-row group bg-surface-container-lowest p-6 md:p-8 rounded-3xl border border-border-subtle shadow-sm hover:shadow-md transition-all relative space-y-4"
           data-ayah-num="${ayahNumberInSurah}"
           data-ayah-global="${ayah.number}">

        <div class="flex items-center justify-between border-b border-border-subtle pb-3">
          <div class="flex items-center gap-2">
            <div class="ayah-number-badge">
              <svg viewBox="0 0 40 40">
                <path d="M20 2L32.7279 7.27208L38 20L32.7279 32.7279L20 38L7.27208 32.7279L2 20L7.27208 7.27208L20 2Z" />
              </svg>
              <span>${ayahNumberInSurah}</span>
            </div>
            <span class="text-xs font-semibold text-on-surface-variant">الآية ${ayahNumberInSurah}</span>
          </div>

          <div class="flex items-center gap-1">
            <button class="play-ayah-btn w-8 h-8 rounded-lg hover:bg-primary-container hover:text-on-primary text-on-surface-variant flex items-center justify-center transition-colors"
                    title="استماع لهذه الآية" data-surah="${state.currentSurahId}" data-ayah="${ayahNumberInSurah}" data-global="${ayah.number}">
              <span class="material-symbols-outlined text-[20px]">play_arrow</span>
            </button>

            <button class="bookmark-ayah-btn w-8 h-8 rounded-lg hover:bg-surface-container-high ${isBookmarked ? 'text-tertiary' : 'text-on-surface-variant'} flex items-center justify-center transition-colors"
                    title="حفظ علامة مرجعية" data-surah="${state.currentSurahId}" data-ayah="${ayahNumberInSurah}">
              <span class="material-symbols-outlined text-[20px] ${isBookmarked ? 'filled' : ''}">bookmark</span>
            </button>

            <button class="show-tafsir-btn w-8 h-8 rounded-lg hover:bg-surface-container-high text-on-surface-variant flex items-center justify-center transition-colors"
                    title="عرض التفسير" data-surah="${state.currentSurahId}" data-ayah="${ayahNumberInSurah}">
              <span class="material-symbols-outlined text-[20px]">menu_book</span>
            </button>

            <button class="copy-ayah-btn w-8 h-8 rounded-lg hover:bg-surface-container-high text-on-surface-variant flex items-center justify-center transition-colors"
                    title="نسخ نص الآية" data-text="${ayah.text}">
              <span class="material-symbols-outlined text-[18px]">content_copy</span>
            </button>
          </div>
        </div>

        <p class="font-quran-script text-on-surface text-right leading-loose select-text" dir="rtl">
          ${ayah.text}
          <span class="ayah-number-badge">
            <svg viewBox="0 0 40 40">
              <path d="M20 2L32.7279 7.27208L38 20L32.7279 32.7279L20 38L7.27208 32.7279L2 20L7.27208 7.27208L20 2Z" />
            </svg>
            <span>${ayahNumberInSurah}</span>
          </span>
        </p>

        <div class="translation-box text-left pt-2 border-t border-border-subtle/50 text-xs md:text-sm text-on-surface-variant font-body select-text ${state.showTranslation ? '' : 'hidden'}">
          <p class="leading-relaxed opacity-90">${engText}</p>
        </div>

        <div id="tafsir-data-${ayahNumberInSurah}" class="hidden" data-tafsir="${encodeURIComponent(tafsirText)}" data-arabic="${encodeURIComponent(ayah.text)}"></div>
      </div>
    `;
  }).join('');

  setupVerseCardEvents();

  if (targetAyah > 1) {
    setTimeout(() => scrollToAyah(targetAyah), 200);
  }
}

function generateFallbackSurah(surahId, targetAyah) {
  const surah = window.SURAHS_DATA.find(s => s.id === surahId);
  const container = document.getElementById('versesList');
  if (!container || !surah) return;

  const mockVerses = [];
  for (let i = 1; i <= surah.versesCount; i++) {
    mockVerses.push({
      numberInSurah: i,
      number: i,
      text: i === 1 && surahId !== 9 && surahId !== 1 ? `بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ` : `آية كريمة من سورة ${surah.name} المباركة (الآية ${i}).`
    });
  }

  renderVersesContent({
    arabic: mockVerses,
    english: mockVerses.map(v => ({ text: `Verse ${v.numberInSurah} of Surah ${surah.englishName}.` })),
    tafsir: mockVerses.map(v => ({ text: `تفسير الآية الكريمة رقم ${v.numberInSurah} من سورة ${surah.name}.` }))
  }, targetAyah);
}

function setupVerseCardEvents() {
  document.querySelectorAll('.play-ayah-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const surahId = parseInt(btn.dataset.surah) || state.currentSurahId;
      const ayahNum = parseInt(btn.dataset.ayah);
      playAyahAudio(surahId, ayahNum);
    });
  });

  document.querySelectorAll('.bookmark-ayah-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const ayahNum = parseInt(btn.dataset.ayah);
      toggleBookmark(state.currentSurahId, ayahNum);
    });
  });

  document.querySelectorAll('.show-tafsir-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const ayahNum = parseInt(btn.dataset.ayah);
      displayTafsirForAyah(ayahNum);
    });
  });

  document.querySelectorAll('.copy-ayah-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      e.stopPropagation();
      const text = btn.dataset.text;
      navigator.clipboard.writeText(text).then(() => {
        showToast('تم نسخ نص الآية إلى الحافظة');
      });
    });
  });
}

function scrollToAyah(ayahNum) {
  state.activeAyahIndex = ayahNum;
  saveLastRead(state.currentSurahId, ayahNum);

  const row = document.getElementById(`ayah-row-${ayahNum}`);
  if (row) {
    row.scrollIntoView({ behavior: 'smooth', block: 'center' });
    row.classList.add('active-audio-ayah');
    setTimeout(() => {
      if (!state.isPlaying) row.classList.remove('active-audio-ayah');
    }, 2000);
  }

  document.querySelectorAll('.ayah-jump-btn').forEach(btn => {
    if (parseInt(btn.dataset.ayah) === ayahNum) {
      btn.classList.add('bg-primary', 'text-on-primary', 'shadow-sm');
      btn.classList.remove('bg-surface');
    } else {
      btn.classList.remove('bg-primary', 'text-on-primary', 'shadow-sm');
      btn.classList.add('bg-surface');
    }
  });
}

function displayTafsirForAyah(ayahNum) {
  const tafsirPanel = document.getElementById('tafsirPanel');
  const tafsirContent = document.getElementById('tafsirContent');
  if (!tafsirPanel || !tafsirContent) return;

  const dataEl = document.getElementById(`tafsir-data-${ayahNum}`);
  const surah = window.SURAHS_DATA.find(s => s.id === state.currentSurahId);

  tafsirPanel.classList.remove('hidden');

  if (dataEl) {
    const rawTafsir = decodeURIComponent(dataEl.dataset.tafsir || '');
    const rawArabic = decodeURIComponent(dataEl.dataset.arabic || '');

    tafsirContent.innerHTML = `
      <div class="space-y-4">
        <div class="p-4 rounded-2xl bg-surface border border-border-subtle space-y-2">
          <div class="text-xs font-bold text-primary">سورة ${surah?.name || ''} - الآية ${ayahNum}</div>
          <p class="font-quran-script text-sm leading-relaxed text-on-surface">${rawArabic}</p>
        </div>

        <div class="space-y-2">
          <h5 class="text-xs font-bold text-on-surface-variant uppercase">شرح ومعنى الآية:</h5>
          <div class="bg-surface-container p-4 rounded-2xl border border-border-subtle leading-relaxed text-sm text-on-surface">
            ${rawTafsir || 'لا يتوفر تفسير إلكتروني لهذه الآية حالياً.'}
          </div>
        </div>
      </div>
    `;
  }
}

// ================= AUDIO PLAYER ENGINE =================
function getAyahAudioUrl(surahId, ayahNum, reciter) {
  const padSurah = String(surahId).padStart(3, '0');
  const padAyah = String(ayahNum).padStart(3, '0');
  const serverId = reciter.serverId;
  return `https://everyayah.com/data/${serverId}/${padSurah}${padAyah}.mp3`;
}

function playAyahAudio(surahId, ayahNum) {
  const surah = window.SURAHS_DATA.find(s => s.id === surahId);
  if (!surah) return;

  state.currentSurahId = surahId;
  state.activeAyahIndex = ayahNum;

  const audioUrl = getAyahAudioUrl(surahId, ayahNum, state.selectedReciter);
  audioPlayer.src = audioUrl;
  audioPlayer.playbackRate = state.playbackSpeed;
  audioPlayer.play().then(() => {
    state.isPlaying = true;
    updateAudioPlayerUI();
    highlightActiveAyah(ayahNum);
  }).catch(err => {
    console.error('Audio playback error:', err);
    showToast('تعذر تحميل تلاوة هذه الآية، تأكد من اتصال الإنترنت');
  });

  document.getElementById('playerAyahTitle').textContent = `سورة ${surah.name} - الآية ${ayahNum}`;
  document.getElementById('playerReciterLabel').textContent = state.selectedReciter.name;
}

function playFullSurah(surahId = state.currentSurahId) {
  state.autoNextAyah = true;
  const surah = window.SURAHS_DATA.find(s => s.id === surahId);
  if (!surah) return;

  playAyahAudio(surahId, 1);
  showToast(`جاري تشغيل سورة ${surah.name} كاملة بصوت ${state.selectedReciter.name}`);
}

function highlightActiveAyah(ayahNum) {
  document.querySelectorAll('.ayah-row').forEach(row => {
    row.classList.remove('active-audio-ayah');
  });

  const activeRow = document.getElementById(`ayah-row-${ayahNum}`);
  if (activeRow) {
    activeRow.classList.add('active-audio-ayah');
    if (state.autoScroll) {
      activeRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }

  document.querySelectorAll('.ayah-jump-btn').forEach(btn => {
    if (parseInt(btn.dataset.ayah) === ayahNum) {
      btn.classList.add('bg-primary', 'text-on-primary');
    }
  });
}

function setupAudioListeners() {
  const playPauseBtn = document.getElementById('playerPlayPauseBtn');
  const nextBtn = document.getElementById('playerNextAyahBtn');
  const prevBtn = document.getElementById('playerPrevAyahBtn');
  const progressSlider = document.getElementById('playerProgress');
  const speedBtn = document.getElementById('playerSpeedBtn');
  const volumeSlider = document.getElementById('playerVolume');
  const autoNextToggle = document.getElementById('playerAutoNextToggle');

  playPauseBtn.addEventListener('click', () => {
    if (!audioPlayer.src || audioPlayer.src === window.location.href) {
      playAyahAudio(state.currentSurahId, state.activeAyahIndex || 1);
      return;
    }

    if (audioPlayer.paused) {
      audioPlayer.play();
      state.isPlaying = true;
    } else {
      audioPlayer.pause();
      state.isPlaying = false;
    }
    updateAudioPlayerUI();
  });

  nextBtn.addEventListener('click', () => playNextAyah());
  prevBtn.addEventListener('click', () => playPrevAyah());

  audioPlayer.addEventListener('timeupdate', () => {
    if (audioPlayer.duration) {
      const pct = (audioPlayer.currentTime / audioPlayer.duration) * 100;
      progressSlider.value = pct;
      document.getElementById('playerCurrentTime').textContent = formatTime(audioPlayer.currentTime);
      document.getElementById('playerDuration').textContent = formatTime(audioPlayer.duration);
    }
  });

  progressSlider.addEventListener('input', () => {
    if (audioPlayer.duration) {
      audioPlayer.currentTime = (progressSlider.value / 100) * audioPlayer.duration;
    }
  });

  audioPlayer.addEventListener('ended', () => {
    if (state.autoNextAyah) {
      playNextAyah();
    } else {
      state.isPlaying = false;
      updateAudioPlayerUI();
    }
  });

  const speeds = [1, 1.25, 1.5, 0.75];
  let speedIdx = 0;
  speedBtn.addEventListener('click', () => {
    speedIdx = (speedIdx + 1) % speeds.length;
    state.playbackSpeed = speeds[speedIdx];
    audioPlayer.playbackRate = state.playbackSpeed;
    speedBtn.textContent = `${state.playbackSpeed}x`;
  });

  volumeSlider.addEventListener('input', () => {
    audioPlayer.volume = parseFloat(volumeSlider.value);
  });

  autoNextToggle.addEventListener('click', () => {
    state.autoNextAyah = !state.autoNextAyah;
    autoNextToggle.classList.toggle('text-primary', state.autoNextAyah);
    showToast(state.autoNextAyah ? 'تم تفعيل التلاوة المتتالية للآيات' : 'تم إيقاف التلاوة المتتالية');
  });

  // Play Full Surah buttons
  const fullSurahTopBtn = document.getElementById('playFullSurahTopBtn');
  const fullSurahBannerBtn = document.getElementById('playFullSurahBannerBtn');

  if (fullSurahTopBtn) {
    fullSurahTopBtn.addEventListener('click', () => playFullSurah(state.currentSurahId));
  }
  if (fullSurahBannerBtn) {
    fullSurahBannerBtn.addEventListener('click', () => playFullSurah(state.currentSurahId));
  }
}

function playNextAyah() {
  const surah = window.SURAHS_DATA.find(s => s.id === state.currentSurahId);
  if (!surah) return;

  if (state.activeAyahIndex < surah.versesCount) {
    playAyahAudio(state.currentSurahId, state.activeAyahIndex + 1);
  } else if (state.currentSurahId < 114) {
    openSurahReader(state.currentSurahId + 1, 1).then(() => {
      playAyahAudio(state.currentSurahId + 1, 1);
    });
  }
}

function playPrevAyah() {
  if (state.activeAyahIndex > 1) {
    playAyahAudio(state.currentSurahId, state.activeAyahIndex - 1);
  } else if (state.currentSurahId > 1) {
    const prevSurah = window.SURAHS_DATA.find(s => s.id === state.currentSurahId - 1);
    if (prevSurah) {
      openSurahReader(prevSurah.id, prevSurah.versesCount).then(() => {
        playAyahAudio(prevSurah.id, prevSurah.versesCount);
      });
    }
  }
}

function updateAudioPlayerUI() {
  const playIcon = document.getElementById('playPauseIcon');
  if (state.isPlaying) {
    playIcon.textContent = 'pause';
  } else {
    playIcon.textContent = 'play_arrow';
  }
}

function formatTime(secs) {
  if (isNaN(secs)) return '00:00';
  const m = Math.floor(secs / 60);
  const s = Math.floor(secs % 60);
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

// ================= PRAYER TIMES MODULE =================
const PRAYER_NAMES_AR = {
  Fajr: 'الفجر',
  Sunrise: 'الشروق',
  Dhuhr: 'الظهر',
  Asr: 'العصر',
  Maghrib: 'المغرب',
  Isha: 'العشاء'
};

async function initPrayerTimesModule() {
  const citySelect = document.getElementById('prayerCitySelect');
  if (citySelect) {
    citySelect.addEventListener('change', (e) => {
      state.prayerCity = e.target.value;
      localStorage.setItem('quran_prayer_city', state.prayerCity);
      fetchPrayerTimes();
    });
  }

  const quickBtn = document.getElementById('quickPrayerTimesBtn');
  if (quickBtn) {
    quickBtn.addEventListener('click', () => switchView('viewPrayerTimes'));
  }

  await fetchPrayerTimes();
}

async function fetchPrayerTimes() {
  const parts = state.prayerCity.split(',');
  const city = parts[0] ? parts[0].trim() : 'Cairo';
  const country = parts[1] ? parts[1].trim() : 'Egypt';

  const cityLabel = document.getElementById('prayerCurrentCityLabel');
  if (cityLabel) cityLabel.textContent = getCityArabicName(city);

  try {
    const res = await fetch(`https://api.aladhan.com/v1/timingsByCity?city=${encodeURIComponent(city)}&country=${encodeURIComponent(country)}&method=5`);
    if (!res.ok) throw new Error('API error');
    const json = await res.json();
    state.prayerTimesData = json.data.timings;
    renderPrayerTimes(json.data.timings);
  } catch (err) {
    console.warn('Using offline prayer schedule calculation for', city);
    const fallbackTimings = getFallbackPrayerTimes(city);
    state.prayerTimesData = fallbackTimings;
    renderPrayerTimes(fallbackTimings);
  }
}

function getCityArabicName(cityName) {
  const names = {
    Cairo: 'القاهرة',
    Alexandria: 'الإسكندرية',
    Giza: 'الجيزة',
    Makkah: 'مكة المكرمة',
    Madinah: 'المدينة المنورة',
    Riyadh: 'الرياض',
    Jerusalem: 'القدس الشريف',
    Dubai: 'دبي',
    Amman: 'عَمّان',
    Kuwait: 'الكويت',
    Doha: 'الدوحة',
    Casablanca: 'الدار البيضاء',
    Algiers: 'الجزائر',
    Tunis: 'تونس',
    Baghdad: 'بغداد',
    Istanbul: 'إسطنبول'
  };
  return names[cityName] || cityName;
}

function getFallbackPrayerTimes(city) {
  return {
    Fajr: "04:30",
    Sunrise: "06:15",
    Dhuhr: "12:00",
    Asr: "15:45",
    Maghrib: "18:30",
    Isha: "20:00"
  };
}

function renderPrayerTimes(timings) {
  const prayerKeys = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
  
  // Format times in 12h format with Arabic AM/PM
  prayerKeys.forEach(key => {
    const raw = timings[key] || "12:00";
    const [h, m] = raw.split(':').map(Number);
    const period = h >= 12 ? 'م' : 'ص';
    const h12 = h % 12 || 12;
    const formatted = `${toArabicDigits(String(h12).padStart(2, '0'))}:${toArabicDigits(String(m).padStart(2, '0'))} ${period}`;
    
    const el = document.getElementById(`time-${key}`);
    if (el) el.textContent = formatted;
  });

  startPrayerCountdownTicker(timings);
}

function startPrayerCountdownTicker(timings) {
  if (state.prayerCountdownTimer) clearInterval(state.prayerCountdownTimer);

  function updateTicker() {
    const now = new Date();
    const currentMins = now.getHours() * 60 + now.getMinutes() + now.getSeconds() / 60;
    
    const prayers = [
      { key: 'Fajr', name: 'الفجر', mins: parseTimeToMinutes(timings.Fajr) },
      { key: 'Sunrise', name: 'الشروق', mins: parseTimeToMinutes(timings.Sunrise) },
      { key: 'Dhuhr', name: 'الظهر', mins: parseTimeToMinutes(timings.Dhuhr) },
      { key: 'Asr', name: 'العصر', mins: parseTimeToMinutes(timings.Asr) },
      { key: 'Maghrib', name: 'المغرب', mins: parseTimeToMinutes(timings.Maghrib) },
      { key: 'Isha', name: 'العشاء', mins: parseTimeToMinutes(timings.Isha) }
    ];

    let nextPrayer = prayers.find(p => p.mins > currentMins);
    let diffMins = 0;

    if (!nextPrayer) {
      // Next is tomorrow's Fajr
      nextPrayer = prayers[0];
      diffMins = (24 * 60 - currentMins) + nextPrayer.mins;
    } else {
      diffMins = nextPrayer.mins - currentMins;
    }

    const diffSecs = Math.max(0, Math.floor(diffMins * 60));
    const h = Math.floor(diffSecs / 3600);
    const m = Math.floor((diffSecs % 3600) / 60);
    const s = diffSecs % 60;
    const countdownStr = `متبقي: ${toArabicDigits(String(h).padStart(2, '0'))}:${toArabicDigits(String(m).padStart(2, '0'))}:${toArabicDigits(String(s).padStart(2, '0'))}`;

    // Update Next Prayer Hero Card
    const nameLarge = document.getElementById('nextPrayerNameLarge');
    const timeLarge = document.getElementById('nextPrayerTimeLarge');
    const countdownEl = document.getElementById('nextPrayerCountdownText');
    const sidebarBadge = document.getElementById('sidebarNextPrayerBadge');
    const headerName = document.getElementById('headerNextPrayerName');
    const headerCountdown = document.getElementById('headerNextPrayerCountdown');
    const quickPrayerTime = document.getElementById('quickNextPrayerTime');

    if (nameLarge) nameLarge.textContent = nextPrayer.name;
    if (timeLarge) {
      const raw = timings[nextPrayer.key] || "12:00";
      const clean = String(raw).trim().split(' ')[0];
      const [th, tm] = clean.split(':').map(Number);
      const period = th >= 12 ? 'م' : 'ص';
      const h12 = th % 12 || 12;
      timeLarge.textContent = `${toArabicDigits(String(h12).padStart(2, '0'))}:${toArabicDigits(String(tm).padStart(2, '0'))} ${period}`;
    }
    if (countdownEl) countdownEl.textContent = countdownStr;
    if (sidebarBadge) sidebarBadge.textContent = nextPrayer.name;
    if (headerName) headerName.textContent = nextPrayer.name;
    if (headerCountdown) headerCountdown.textContent = `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
    if (quickPrayerTime) quickPrayerTime.textContent = `${nextPrayer.name} ${timings[nextPrayer.key]}`;

    // Reset all 6 prayer rows to default
    prayers.forEach(p => {
      const row = document.getElementById(`prayer-row-${p.key}`);
      const nameEl = document.getElementById(`prayer-name-${p.key}`);
      const iconBox = document.getElementById(`prayer-icon-box-${p.key}`);
      const timeEl = document.getElementById(`time-${p.key}`);
      
      if (row) {
        row.className = 'prayer-time-row flex items-center justify-between p-4 rounded-2xl bg-surface-container-low border border-border-subtle hover:border-primary/40 transition-all';
      }
      if (nameEl) {
        nameEl.textContent = p.key === 'Sunrise' ? 'الشروق' : `صلاة ${p.name}`;
        nameEl.className = 'text-sm font-bold text-on-surface';
      }
      if (iconBox) {
        iconBox.className = 'w-10 h-10 rounded-xl bg-surface-container text-on-surface-variant flex items-center justify-center';
      }
      if (timeEl) {
        timeEl.className = 'font-display-title font-bold text-base text-on-surface';
      }
    });

    // Highlight the actual next upcoming prayer
    const nextRow = document.getElementById(`prayer-row-${nextPrayer.key}`);
    const nextNameEl = document.getElementById(`prayer-name-${nextPrayer.key}`);
    const nextIconBox = document.getElementById(`prayer-icon-box-${nextPrayer.key}`);
    const nextTimeEl = document.getElementById(`time-${nextPrayer.key}`);

    if (nextRow) {
      nextRow.className = 'prayer-time-row flex items-center justify-between p-4 rounded-2xl bg-primary/15 border-2 border-primary text-primary shadow-md transition-all scale-[1.01]';
    }
    if (nextNameEl) {
      nextNameEl.textContent = nextPrayer.key === 'Sunrise' ? 'الشروق (القادم)' : `صلاة ${nextPrayer.name} (القادمة)`;
      nextNameEl.className = 'text-sm font-bold text-primary';
    }
    if (nextIconBox) {
      nextIconBox.className = 'w-10 h-10 rounded-xl bg-primary text-slate-950 flex items-center justify-center font-bold';
    }
    if (nextTimeEl) {
      nextTimeEl.className = 'font-display-title font-bold text-lg text-primary';
    }
  }

  updateTicker();
  state.prayerCountdownTimer = setInterval(updateTicker, 1000);
}

function parseTimeToMinutes(timeStr) {
  if (!timeStr) return 0;
  const clean = String(timeStr).trim().split(' ')[0];
  const parts = clean.split(':');
  const h = parseInt(parts[0], 10) || 0;
  const m = parseInt(parts[1], 10) || 0;
  return h * 60 + m;
}

// ================= KHATMAH TRACKER SYSTEM =================
function initKhatmahModule() {
  renderReadingKhatmah();
  renderListeningKhatmah();
  setupKhatmahEventListeners();
}

function renderReadingKhatmah() {
  const readCount = state.khatmah.readSurahs.length;
  const total = 114;
  const pct = Math.round((readCount / total) * 100);

  // Update ring and labels
  const ring = document.getElementById('readingKhatmahRing');
  const pctEl = document.getElementById('readingKhatmahPct');
  const sumEl = document.getElementById('readingKhatmahSummary');
  const planDaysLabel = document.getElementById('khatmahPlanDaysLabel');
  const streakEl = document.getElementById('khatmahStreakDays');

  if (ring) {
    const offset = 263.8 - (263.8 * pct) / 100;
    ring.style.strokeDashoffset = offset;
  }
  if (pctEl) pctEl.textContent = `${pct}%`;
  if (sumEl) sumEl.textContent = `${readCount} من ${total} سورة مكتملة`;
  if (planDaysLabel) planDaysLabel.textContent = `${state.khatmah.planDays} يوماً`;
  if (streakEl) streakEl.textContent = `${state.khatmah.streakDays} أيام`;

  // Determine today's recommended reading wird
  const firstUnread = window.SURAHS_DATA.find(s => !state.khatmah.readSurahs.includes(s.id)) || window.SURAHS_DATA[0];
  const wirdTitleEl = document.getElementById('khatmahTodayWirdTitle');
  if (wirdTitleEl && firstUnread) {
    wirdTitleEl.textContent = `ورد اليوم: سورة ${firstUnread.name} (الجزء ${firstUnread.juz})`;
  }

  // Update active plan button highlight
  document.querySelectorAll('.khatmah-plan-btn').forEach(btn => {
    if (parseInt(btn.dataset.planDays) === state.khatmah.planDays) {
      btn.className = 'khatmah-plan-btn p-4 rounded-2xl border-2 border-primary bg-primary/5 text-right transition-all';
    } else {
      btn.className = 'khatmah-plan-btn p-4 rounded-2xl border-2 border-border-subtle bg-surface-container-low text-right hover:border-primary transition-all';
    }
  });

  renderKhatmahSurahsChecklist();
}

function renderKhatmahSurahsChecklist() {
  const container = document.getElementById('khatmahSurahsChecklist');
  if (!container || !window.SURAHS_DATA) return;

  container.innerHTML = window.SURAHS_DATA.map(surah => {
    const isChecked = state.khatmah.readSurahs.includes(surah.id);
    return `
      <div class="flex items-center justify-between p-2.5 rounded-xl border border-border-subtle bg-surface hover:border-primary/40 transition-colors ${isChecked ? 'bg-primary/5 border-primary/40' : ''}">
        <div class="flex items-center gap-2.5 flex-1 min-w-0">
          <input type="checkbox" class="khatmah-read-cb w-4 h-4 accent-primary cursor-pointer rounded" 
                 data-surah-id="${surah.id}" ${isChecked ? 'checked' : ''}>
          <span class="text-xs font-bold text-on-surface truncate cursor-pointer hover:text-primary"
                onclick="window.openKhatmahSurah(${surah.id})">
            ${surah.id}. سورة ${surah.name}
          </span>
        </div>
        <span class="text-[10px] text-on-surface-variant flex-shrink-0 opacity-70">جـ ${surah.juz}</span>
      </div>
    `;
  }).join('');

  container.querySelectorAll('.khatmah-read-cb').forEach(cb => {
    cb.addEventListener('change', (e) => {
      const id = parseInt(cb.dataset.surahId);
      toggleKhatmahSurahRead(id, cb.checked);
    });
  });
}

function toggleKhatmahSurahRead(surahId, isRead) {
  if (isRead) {
    if (!state.khatmah.readSurahs.includes(surahId)) {
      state.khatmah.readSurahs.push(surahId);
      playBeep(800, 0.06);
    }
  } else {
    state.khatmah.readSurahs = state.khatmah.readSurahs.filter(id => id !== surahId);
  }

  saveKhatmahState();
  renderReadingKhatmah();

  if (state.khatmah.readSurahs.length === 114) {
    playBeep(1200, 0.4);
    showToast('مبارك! لقد أتممت ختم القرآن الكريم كاملاً، تقبل الله منك!');
    document.getElementById('khatmDuaModal').classList.remove('hidden');
  }
}

function renderListeningKhatmah() {
  const listenCount = state.khatmah.listenedSurahs.length;
  const total = 114;
  const pct = Math.round((listenCount / total) * 100);

  const ring = document.getElementById('listeningKhatmahRing');
  const pctEl = document.getElementById('listeningKhatmahPct');
  const sumEl = document.getElementById('listeningKhatmahSummary');
  const badge = document.getElementById('listeningReciterBadge');

  if (ring) {
    const offset = 263.8 - (263.8 * pct) / 100;
    ring.style.strokeDashoffset = offset;
  }
  if (pctEl) pctEl.textContent = `${pct}%`;
  if (sumEl) sumEl.textContent = `${listenCount} من ${total} سورة مسموعة`;

  const reciter = window.RECITERS.find(r => r.id === state.khatmah.listeningReciterId) || window.RECITERS[0];
  if (badge) badge.textContent = `بصوت الشيخ ${reciter.name}`;

  const firstUnlistened = window.SURAHS_DATA.find(s => !state.khatmah.listenedSurahs.includes(s.id)) || window.SURAHS_DATA[0];
  const wirdTitleEl = document.getElementById('listeningTodayWirdTitle');
  if (wirdTitleEl && firstUnlistened) {
    wirdTitleEl.textContent = `ورد الاستماع: سورة ${firstUnlistened.name} (الجزء ${firstUnlistened.juz})`;
  }

  renderListeningRecitersGrid();
  renderKhatmahListeningChecklist();
}

function renderListeningRecitersGrid() {
  const container = document.getElementById('listeningRecitersGrid');
  if (!container || !window.RECITERS) return;

  container.innerHTML = window.RECITERS.map(r => {
    const isSelected = r.id === state.khatmah.listeningReciterId;
    return `
      <div class="p-3.5 rounded-2xl border-2 cursor-pointer transition-all flex items-center justify-between ${isSelected ? 'border-primary bg-primary/10 shadow-sm' : 'border-border-subtle bg-surface hover:border-primary/40'}"
           onclick="window.selectListeningKhatmahReciter('${r.id}')">
        <div class="flex items-center gap-3">
          <div class="w-9 h-9 rounded-xl ${isSelected ? 'bg-primary text-on-primary' : 'bg-surface-container text-on-surface-variant'} flex items-center justify-center">
            <span class="material-symbols-outlined text-[20px]">record_voice_over</span>
          </div>
          <div>
            <div class="text-xs font-bold text-on-surface">${r.name}</div>
            <div class="text-[10px] text-on-surface-variant opacity-80">${r.subtext}</div>
          </div>
        </div>
        ${isSelected ? '<span class="material-symbols-outlined text-primary text-[18px]">check_circle</span>' : ''}
      </div>
    `;
  }).join('');
}

window.selectListeningKhatmahReciter = (reciterId) => {
  state.khatmah.listeningReciterId = reciterId;
  const found = window.RECITERS.find(r => r.id === reciterId);
  if (found) {
    state.selectedReciter = found;
  }
  saveKhatmahState();
  renderListeningKhatmah();
  showToast(`تم اختيار الشيخ ${found?.name || ''} لختمة الاستماع`);
};

function renderKhatmahListeningChecklist() {
  const container = document.getElementById('khatmahListeningChecklist');
  if (!container || !window.SURAHS_DATA) return;

  container.innerHTML = window.SURAHS_DATA.map(surah => {
    const isChecked = state.khatmah.listenedSurahs.includes(surah.id);
    return `
      <div class="flex items-center justify-between p-2.5 rounded-xl border border-border-subtle bg-surface hover:border-primary/40 transition-colors ${isChecked ? 'bg-emerald-500/10 border-emerald-500/40' : ''}">
        <div class="flex items-center gap-2.5 flex-1 min-w-0">
          <input type="checkbox" class="khatmah-listen-cb w-4 h-4 accent-emerald-600 cursor-pointer rounded" 
                 data-surah-id="${surah.id}" ${isChecked ? 'checked' : ''}>
          <span class="text-xs font-bold text-on-surface truncate cursor-pointer hover:text-emerald-700"
                onclick="window.playKhatmahSurahAudio(${surah.id})">
            ${surah.id}. سورة ${surah.name}
          </span>
        </div>
        <button class="w-6 h-6 rounded-lg hover:bg-surface-container flex items-center justify-center text-primary"
                title="تشغيل" onclick="window.playKhatmahSurahAudio(${surah.id})">
          <span class="material-symbols-outlined text-[16px]">play_arrow</span>
        </button>
      </div>
    `;
  }).join('');

  container.querySelectorAll('.khatmah-listen-cb').forEach(cb => {
    cb.addEventListener('change', (e) => {
      const id = parseInt(cb.dataset.surahId);
      toggleKhatmahSurahListen(id, cb.checked);
    });
  });
}

function toggleKhatmahSurahListen(surahId, isListened) {
  if (isListened) {
    if (!state.khatmah.listenedSurahs.includes(surahId)) {
      state.khatmah.listenedSurahs.push(surahId);
      playBeep(800, 0.06);
    }
  } else {
    state.khatmah.listenedSurahs = state.khatmah.listenedSurahs.filter(id => id !== surahId);
  }

  saveKhatmahState();
  renderListeningKhatmah();

  if (state.khatmah.listenedSurahs.length === 114) {
    playBeep(1200, 0.4);
    showToast('مبارك! لقد أتممت ختمة الاستماع لكامل القرآن الكريم!');
  }
}

window.openKhatmahSurah = (surahId) => {
  openSurahReader(surahId, 1);
};

window.playKhatmahSurahAudio = (surahId) => {
  openSurahReader(surahId, 1).then(() => {
    playAyahAudio(surahId, 1);
  });
};

function saveKhatmahState() {
  localStorage.setItem('quran_khatmah_data', JSON.stringify(state.khatmah));
}

function setupKhatmahEventListeners() {
  const modeReadBtn = document.getElementById('khatmahModeReadBtn');
  const modeListenBtn = document.getElementById('khatmahModeListenBtn');
  const readSection = document.getElementById('readingKhatmahSection');
  const listenSection = document.getElementById('listeningKhatmahSection');

  modeReadBtn.addEventListener('click', () => {
    state.khatmah.mode = 'reading';
    modeReadBtn.className = 'khatmah-mode-btn px-6 py-2 rounded-xl bg-primary text-on-primary font-bold text-xs flex items-center gap-2 shadow-sm transition-all';
    modeListenBtn.className = 'khatmah-mode-btn px-6 py-2 rounded-xl text-on-surface-variant hover:text-on-surface text-xs font-semibold flex items-center gap-2 transition-all';
    readSection.classList.remove('hidden');
    listenSection.classList.add('hidden');
  });

  modeListenBtn.addEventListener('click', () => {
    state.khatmah.mode = 'listening';
    modeListenBtn.className = 'khatmah-mode-btn px-6 py-2 rounded-xl bg-primary text-on-primary font-bold text-xs flex items-center gap-2 shadow-sm transition-all';
    modeReadBtn.className = 'khatmah-mode-btn px-6 py-2 rounded-xl text-on-surface-variant hover:text-on-surface text-xs font-semibold flex items-center gap-2 transition-all';
    listenSection.classList.remove('hidden');
    readSection.classList.add('hidden');
  });

  document.querySelectorAll('.khatmah-plan-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      state.khatmah.planDays = parseInt(btn.dataset.planDays);
      saveKhatmahState();
      renderReadingKhatmah();
      showToast(`تم تعيين خطة الختم في ${state.khatmah.planDays} يوماً`);
    });
  });

  // Start reading wird
  document.getElementById('startTodayReadingWirdBtn').addEventListener('click', () => {
    const firstUnread = window.SURAHS_DATA.find(s => !state.khatmah.readSurahs.includes(s.id)) || window.SURAHS_DATA[0];
    openSurahReader(firstUnread.id, 1);
  });

  // Start listening wird
  document.getElementById('startListeningWirdBtn').addEventListener('click', () => {
    const firstUnlistened = window.SURAHS_DATA.find(s => !state.khatmah.listenedSurahs.includes(s.id)) || window.SURAHS_DATA[0];
    openSurahReader(firstUnlistened.id, 1).then(() => {
      playAyahAudio(firstUnlistened.id, 1);
    });
  });

  // Mark all read
  document.getElementById('markAllReadBtn').addEventListener('click', () => {
    state.khatmah.readSurahs = window.SURAHS_DATA.map(s => s.id);
    saveKhatmahState();
    renderReadingKhatmah();
    showToast('تم تحديد جميع السور كمقروءة');
  });

  // Reset read progress
  document.getElementById('resetReadProgressBtn').addEventListener('click', () => {
    state.khatmah.readSurahs = [];
    saveKhatmahState();
    renderReadingKhatmah();
    showToast('تمت إعادة ضبط ختمة القراءة بنجاح');
  });

  // Reset listen progress
  document.getElementById('resetListenProgressBtn').addEventListener('click', () => {
    state.khatmah.listenedSurahs = [];
    saveKhatmahState();
    renderListeningKhatmah();
    showToast('تمت إعادة ضبط ختمة الاستماع بنجاح');
  });

  // Khatm Dua Modal
  const duaModal = document.getElementById('khatmDuaModal');
  document.getElementById('openKhatmDuaBtn').addEventListener('click', () => {
    duaModal.classList.remove('hidden');
  });
  document.getElementById('closeKhatmDuaBtn').addEventListener('click', () => {
    duaModal.classList.add('hidden');
  });
  document.getElementById('closeKhatmDuaBtn2').addEventListener('click', () => {
    duaModal.classList.add('hidden');
  });
  duaModal.addEventListener('click', (e) => {
    if (e.target === duaModal) duaModal.classList.add('hidden');
  });
}

// ================= AZKAR & TASBIH SYSTEM =================
function renderAzkarCategories() {
  const container = document.getElementById('azkarCategoriesList');
  if (!container || !window.AZKAR_CATEGORIES) return;

  container.innerHTML = window.AZKAR_CATEGORIES.map(cat => {
    const isActive = cat.id === state.azkarCategory;
    return `
      <button class="azkar-cat-btn w-full flex items-center justify-between p-3.5 rounded-2xl font-medium text-xs transition-all ${isActive ? 'bg-primary text-on-primary shadow-md' : 'bg-surface hover:bg-surface-container text-on-surface'}"
              data-cat-id="${cat.id}">
        <div class="flex items-center gap-2.5">
          <span class="material-symbols-outlined text-[20px]">${cat.icon}</span>
          <span class="font-bold">${cat.name}</span>
        </div>
        <span class="text-[11px] opacity-75">${cat.count}</span>
      </button>
    `;
  }).join('');

  container.querySelectorAll('.azkar-cat-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const catId = btn.dataset.catId;
      state.azkarCategory = catId;
      renderAzkarCategories();
      renderAzkarCards(catId);
    });
  });
}

function renderAzkarCards(catId) {
  const container = document.getElementById('azkarCardsList');
  if (!window.AZKAR_CATEGORIES || !window.AZKAR_DATA) return;
  const cat = window.AZKAR_CATEGORIES.find(c => c.id === catId);
  if (!container || !cat) return;

  document.getElementById('currentAzkarCategoryTitle').textContent = cat.name;

  const items = window.AZKAR_DATA[catId] || [];
  if (items.length === 0) {
    container.innerHTML = `<p class="text-center text-on-surface-variant py-10">لا توجد أذكار في هذه الفئة حالياً.</p>`;
    return;
  }

  container.innerHTML = items.map(item => {
    const currentProgress = state.azkarProgress[item.id] || 0;
    const isCompleted = currentProgress >= item.count;
    const remaining = Math.max(0, item.count - currentProgress);

    return `
      <div id="zkr-card-${item.id}" class="bg-surface p-6 rounded-3xl border border-border-subtle shadow-sm space-y-4 transition-all ${isCompleted ? 'border-primary/50 bg-primary/5' : ''}">
        <p class="font-quran-script text-base md:text-lg leading-relaxed text-on-surface font-semibold select-text" dir="rtl">
          ${item.text}
        </p>

        <div class="text-xs text-on-surface-variant font-body bg-surface-container-low p-3 rounded-xl border border-border-subtle flex items-start gap-2">
          <span class="material-symbols-outlined text-tertiary text-[16px] flex-shrink-0 mt-0.5">verified</span>
          <p>${item.fadl}</p>
        </div>

        <div class="flex items-center justify-between pt-2 border-t border-border-subtle">
          <span class="text-xs font-bold text-on-surface-variant">
            التكرار: <span class="text-primary font-bold">${item.count}</span> مرات
          </span>

          <button class="zkr-count-btn px-6 py-2.5 rounded-2xl font-bold text-xs flex items-center gap-2 transition-transform active:scale-95 shadow-sm ${isCompleted ? 'bg-primary text-on-primary' : 'bg-surface-container-high hover:bg-primary-container hover:text-on-primary text-on-surface'}"
                  data-zkr-id="${item.id}" data-max="${item.count}">
            <span class="material-symbols-outlined text-[18px]">${isCompleted ? 'check_circle' : 'touch_app'}</span>
            <span class="counter-label">${isCompleted ? 'تم الإنجاز' : `باقي ${remaining}`}</span>
          </button>
        </div>
      </div>
    `;
  }).join('');

  container.querySelectorAll('.zkr-count-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const zkrId = btn.dataset.zkrId;
      const max = parseInt(btn.dataset.max);
      let cur = state.azkarProgress[zkrId] || 0;

      if (cur < max) {
        cur++;
        state.azkarProgress[zkrId] = cur;
        playBeep(700, 0.05);

        const card = document.getElementById(`zkr-card-${zkrId}`);
        const label = btn.querySelector('.counter-label');
        const icon = btn.querySelector('.material-symbols-outlined');

        if (cur >= max) {
          playBeep(1000, 0.15);
          label.textContent = 'تم الإنجاز';
          icon.textContent = 'check_circle';
          btn.className = 'zkr-count-btn px-6 py-2.5 rounded-2xl font-bold text-xs flex items-center gap-2 bg-primary text-on-primary shadow-sm';
          if (card) {
            card.classList.add('border-primary/50', 'bg-primary/5');
          }
        } else {
          label.textContent = `باقي ${max - cur}`;
        }

        updateDailyAzkarProgress();
      }
    });
  });

  updateDailyAzkarProgress();
}

function updateDailyAzkarProgress() {
  if (!window.AZKAR_DATA) return;
  const currentItems = window.AZKAR_DATA[state.azkarCategory] || [];
  if (currentItems.length === 0) return;

  let completedCount = 0;
  currentItems.forEach(item => {
    if ((state.azkarProgress[item.id] || 0) >= item.count) {
      completedCount++;
    }
  });

  const pct = Math.round((completedCount / currentItems.length) * 100);
  const ring = document.getElementById('azkarProgressRing');
  const pctEl = document.getElementById('azkarProgressPct');
  const labelEl = document.getElementById('azkarDailyLabel');

  if (pctEl) pctEl.textContent = `${pct}%`;
  if (labelEl) labelEl.textContent = `أنجزت ${completedCount} من أصل ${currentItems.length} أذكار`;
  if (ring) {
    const offset = 251.2 - (251.2 * pct) / 100;
    ring.style.strokeDashoffset = offset;
  }
}

// Standalone Electronic Tasbeeh
function setupTasbihTool() {
  const countNum = document.getElementById('tasbihCounterNum');
  const tasbihBtn = document.getElementById('mainTasbihBtn');
  const resetBtn = document.getElementById('resetTasbihBtn');
  const phraseEl = document.getElementById('tasbihZikrPhrase');

  tasbihBtn.addEventListener('click', () => {
    state.tasbihCount++;
    countNum.textContent = state.tasbihCount;
    playBeep(850, 0.04);
    localStorage.setItem('quran_tasbih_count', state.tasbihCount);

    if (state.tasbihCount % 33 === 0) {
      playBeep(1200, 0.2);
      showToast(`تم إتمام ${state.tasbihCount} تسبيحة ما شاء الله!`);
    }
  });

  resetBtn.addEventListener('click', () => {
    state.tasbihCount = 0;
    countNum.textContent = '0';
    localStorage.setItem('quran_tasbih_count', '0');
    playBeep(400, 0.08);
  });

  document.querySelectorAll('.tasbih-phrase-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const zikr = btn.dataset.zikr;
      state.tasbihZikr = zikr;
      phraseEl.textContent = zikr;
    });
  });
}

// ================= BOOKMARKS & FAVORITES =================
function toggleBookmark(surahId, ayahNum) {
  const surah = window.SURAHS_DATA.find(s => s.id === surahId);
  if (!surah) return;

  const existingIdx = state.bookmarks.findIndex(b => b.surahId === surahId && b.ayahNum === ayahNum);
  if (existingIdx >= 0) {
    state.bookmarks.splice(existingIdx, 1);
    showToast('تمت إزالة العلامة المرجعية');
  } else {
    state.bookmarks.unshift({
      surahId,
      surahName: surah.name,
      ayahNum,
      date: new Date().toLocaleDateString('ar-EG')
    });
    showToast(`تم حفظ علامة مرجعية: سورة ${surah.name} آية ${ayahNum}`);
  }

  localStorage.setItem('quran_bookmarks', JSON.stringify(state.bookmarks));
  renderBookmarksList();

  const bookmarkBtn = document.querySelector(`#ayah-row-${ayahNum} .bookmark-ayah-btn`);
  if (bookmarkBtn) {
    const isNowBookmarked = existingIdx < 0;
    bookmarkBtn.classList.toggle('text-tertiary', isNowBookmarked);
    const icon = bookmarkBtn.querySelector('.material-symbols-outlined');
    if (icon) icon.classList.toggle('filled', isNowBookmarked);
  }
}

function renderBookmarksList() {
  const container = document.getElementById('bookmarksListContainer');
  const favsGrid = document.getElementById('favsGrid');
  if (!container) return;

  if (state.bookmarks.length === 0) {
    const emptyHtml = `
      <div class="py-16 text-center text-on-surface-variant bg-surface rounded-3xl border border-border-subtle p-8">
        <span class="material-symbols-outlined text-4xl mb-2 opacity-50">bookmark_border</span>
        <p class="font-bold text-base">لا توجد علامات مرجعية محفوظة حتى الآن</p>
        <p class="text-xs opacity-75 mt-1">انقر على أيقونة الإشارة المرجعية بجانب أي آية أثناء القراءة لحفظها هنا.</p>
      </div>
    `;
    container.innerHTML = emptyHtml;
    if (favsGrid) favsGrid.innerHTML = emptyHtml;
    return;
  }

  const itemsHtml = state.bookmarks.map((bm, idx) => `
    <div class="bg-surface p-5 rounded-2xl border border-border-subtle shadow-sm flex items-center justify-between hover:border-primary/40 transition-colors">
      <div class="flex items-center gap-3 cursor-pointer" onclick="window.openBookmarkedAyah(${bm.surahId}, ${bm.ayahNum})">
        <div class="w-10 h-10 rounded-xl bg-tertiary/15 text-tertiary flex items-center justify-center font-bold">
          <span class="material-symbols-outlined text-[20px] filled">bookmark</span>
        </div>
        <div>
          <h4 class="font-display-title font-bold text-sm text-on-surface hover:text-primary transition-colors">
            سورة ${bm.surahName} - الآية ${bm.ayahNum}
          </h4>
          <p class="text-[11px] text-on-surface-variant opacity-75">حُفظت في ${bm.date}</p>
        </div>
      </div>

      <div class="flex items-center gap-2">
        <button class="px-4 py-2 rounded-xl bg-primary text-on-primary font-bold text-xs shadow-sm hover:bg-primary-container transition-all flex items-center gap-1"
                onclick="window.openBookmarkedAyah(${bm.surahId}, ${bm.ayahNum})">
          <span>قراءة</span>
          <span class="material-symbols-outlined text-[16px]">arrow_back</span>
        </button>
        <button class="w-8 h-8 rounded-lg hover:bg-red-50 text-red-500 flex items-center justify-center transition-colors"
                title="حذف" onclick="window.deleteBookmark(${idx})">
          <span class="material-symbols-outlined text-[18px]">delete</span>
        </button>
      </div>
    </div>
  `).join('');

  container.innerHTML = itemsHtml;
  if (favsGrid) favsGrid.innerHTML = itemsHtml;
}

window.openBookmarkedAyah = (surahId, ayahNum) => {
  openSurahReader(surahId, ayahNum);
};

window.deleteBookmark = (index) => {
  state.bookmarks.splice(index, 1);
  localStorage.setItem('quran_bookmarks', JSON.stringify(state.bookmarks));
  renderBookmarksList();
  showToast('تم حذف العلامة المرجعية');
};

// ================= LAST READ & PROGRESS =================
function saveLastRead(surahId, ayahNum) {
  state.lastRead = {
    surahId,
    ayahNum,
    time: Date.now()
  };
  localStorage.setItem('quran_last_read', JSON.stringify(state.lastRead));
  updateHeroLastReadBanner();
  updateSidebarProgress();
}

function updateHeroLastReadBanner() {
  if (!window.SURAHS_DATA) return;
  const surah = window.SURAHS_DATA.find(s => s.id === state.lastRead.surahId);
  if (!surah) return;

  const titleEl = document.getElementById('heroLastReadTitle');
  const subEl = document.getElementById('heroLastReadSubtitle');
  if (titleEl) titleEl.textContent = `سورة ${surah.name}`;
  if (subEl) subEl.textContent = `الآية ${state.lastRead.ayahNum} • الجزء ${surah.juz} • الصفحة ${surah.page}`;
}

function updateSidebarProgress() {
  if (!window.SURAHS_DATA) return;
  const surah = window.SURAHS_DATA.find(s => s.id === state.lastRead.surahId);
  if (!surah) return;

  const pct = Math.min(100, Math.round((state.lastRead.ayahNum / surah.versesCount) * 100));
  const bar = document.getElementById('sidebarProgressBar');
  const pctEl = document.getElementById('sidebarProgressPct');
  const labelEl = document.getElementById('sidebarLastReadLabel');

  if (bar) bar.style.width = `${pct}%`;
  if (pctEl) pctEl.textContent = `${pct}%`;
  if (labelEl) labelEl.textContent = `سورة ${surah.name} (آية ${state.lastRead.ayahNum})`;
}

// ================= RECITERS & SETTINGS =================
function renderRecitersList() {
  const dropdown = document.getElementById('reciterListContainer');
  const select = document.getElementById('settingsReciterSelect');
  if (!dropdown || !select || !window.RECITERS) return;

  dropdown.innerHTML = window.RECITERS.map(r => `
    <button class="w-full p-2.5 rounded-xl text-right hover:bg-surface-container-high transition-colors flex items-center justify-between text-xs ${r.id === state.selectedReciter.id ? 'bg-primary/10 text-primary font-bold' : 'text-on-surface'}"
            data-reciter-id="${r.id}">
      <div>
        <div class="font-bold">${r.name}</div>
        <div class="text-[10px] text-on-surface-variant opacity-75">${r.subtext}</div>
      </div>
      ${r.id === state.selectedReciter.id ? '<span class="material-symbols-outlined text-[16px] text-primary">check</span>' : ''}
    </button>
  `).join('');

  select.innerHTML = window.RECITERS.map(r => `
    <option value="${r.id}" ${r.id === state.selectedReciter.id ? 'selected' : ''}>${r.name} (${r.subtext})</option>
  `).join('');

  dropdown.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', () => {
      const reciterId = btn.dataset.reciterId;
      selectReciter(reciterId);
      document.getElementById('reciterDropdown').classList.add('hidden');
    });
  });
}

function selectReciter(reciterId) {
  if (!window.RECITERS) return;
  const found = window.RECITERS.find(r => r.id === reciterId);
  if (!found) return;

  state.selectedReciter = found;
  localStorage.setItem('quran_reciter_id', found.id);
  document.getElementById('currentReciterName').textContent = found.name;
  document.getElementById('playerReciterLabel').textContent = found.name;
  
  const bannerReciterLabel = document.getElementById('readerReciterNameBanner');
  if (bannerReciterLabel) bannerReciterLabel.textContent = found.name;

  renderRecitersList();
  showToast(`تم اختيار القارئ: ${found.name}`);

  if (state.isPlaying) {
    playAyahAudio(state.currentSurahId, state.activeAyahIndex);
  }
}

function toggleZenMode(forcedState) {
  state.zenMode = typeof forcedState === 'boolean' ? forcedState : !state.zenMode;
  const sidebar = document.getElementById('mainSidebar');

  if (state.zenMode) {
    if (sidebar) sidebar.classList.add('hidden');
    showToast('تم تفعيل وضع القراءة المركزة (Zen Mode)');
  } else {
    if (sidebar) sidebar.classList.remove('hidden');
  }
}

function showToast(message) {
  const toast = document.getElementById('toastNotification');
  const text = document.getElementById('toastMessage');
  if (!toast || !text) return;

  text.textContent = message;
  toast.classList.remove('opacity-0');
  toast.classList.add('opacity-100');

  setTimeout(() => {
    toast.classList.remove('opacity-100');
    toast.classList.add('opacity-0');
  }, 2400);
}

// ================= GLOBAL EVENT LISTENERS =================
function setupEventListeners() {
  document.querySelectorAll('.nav-item').forEach(btn => {
    btn.addEventListener('click', () => {
      switchView(btn.dataset.target);
    });
  });

  const searchInput = document.getElementById('globalSearchInput');
  const clearSearchBtn = document.getElementById('clearSearchBtn');

  searchInput.addEventListener('input', () => {
    const q = searchInput.value;
    if (state.activeView !== 'viewHome') {
      switchView('viewHome');
    }
    renderSurahsList(q);
  });

  if (clearSearchBtn) {
    clearSearchBtn.addEventListener('click', () => {
      searchInput.value = '';
      clearSearchBtn.classList.add('hidden');
      renderSurahsList('');
      searchInput.focus();
    });
  }

  const tabSurahsBtn = document.getElementById('tabSurahsBtn');
  const tabJuzsBtn = document.getElementById('tabJuzsBtn');
  const tabFavsBtn = document.getElementById('tabFavsBtn');
  const surahsGrid = document.getElementById('surahsGrid');
  const juzsGrid = document.getElementById('juzsGrid');
  const favsGrid = document.getElementById('favsGrid');

  function setHomeTab(activeTab) {
    [tabSurahsBtn, tabJuzsBtn, tabFavsBtn].forEach(b => {
      b.className = 'tab-btn px-6 py-2 rounded-xl text-on-surface-variant hover:text-on-surface text-sm font-medium transition-all';
    });
    [surahsGrid, juzsGrid, favsGrid].forEach(g => g.classList.add('hidden'));

    if (activeTab === 'surahs') {
      tabSurahsBtn.className = 'tab-btn px-6 py-2 rounded-xl bg-primary text-on-primary font-bold text-sm shadow-sm transition-all';
      surahsGrid.classList.remove('hidden');
    } else if (activeTab === 'juzs') {
      tabJuzsBtn.className = 'tab-btn px-6 py-2 rounded-xl bg-primary text-on-primary font-bold text-sm shadow-sm transition-all';
      juzsGrid.classList.remove('hidden');
    } else if (activeTab === 'favs') {
      tabFavsBtn.className = 'tab-btn px-6 py-2 rounded-xl bg-primary text-on-primary font-bold text-sm shadow-sm transition-all';
      favsGrid.classList.remove('hidden');
      renderBookmarksList();
    }
  }

  tabSurahsBtn.addEventListener('click', () => setHomeTab('surahs'));
  tabJuzsBtn.addEventListener('click', () => setHomeTab('juzs'));
  tabFavsBtn.addEventListener('click', () => setHomeTab('favs'));

  document.querySelectorAll('.type-filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.type-filter-btn').forEach(b => {
        b.className = 'type-filter-btn px-3 py-1.5 rounded-lg text-xs font-medium text-on-surface-variant hover:bg-surface-container';
      });
      btn.className = 'type-filter-btn px-3 py-1.5 rounded-lg text-xs font-semibold bg-surface-container-high text-on-surface';
      renderSurahsList(searchInput.value, btn.dataset.filter);
    });
  });

  document.getElementById('heroResumeBtn').addEventListener('click', () => {
    openSurahReader(state.lastRead.surahId, state.lastRead.ayahNum);
  });
  document.getElementById('heroPlayBtn').addEventListener('click', () => {
    openSurahReader(state.lastRead.surahId, state.lastRead.ayahNum).then(() => {
      playAyahAudio(state.lastRead.surahId, state.lastRead.ayahNum);
    });
  });

  document.getElementById('readerBackBtn').addEventListener('click', () => {
    switchView('viewHome');
  });

  document.getElementById('fontIncreaseBtn').addEventListener('click', () => {
    if (state.fontSize < 44) {
      state.fontSize += 2;
      updateFontSize();
    }
  });
  document.getElementById('fontDecreaseBtn').addEventListener('click', () => {
    if (state.fontSize > 20) {
      state.fontSize -= 2;
      updateFontSize();
    }
  });

  function updateFontSize() {
    document.documentElement.style.setProperty('--quran-font-size', `${state.fontSize}px`);
    document.getElementById('fontSizeDisplay').textContent = `${state.fontSize}px`;
    document.getElementById('settingsFontSizeSlider').value = state.fontSize;
    document.getElementById('settingsFontSizeLabel').textContent = `${state.fontSize}px`;
    localStorage.setItem('quran_font_size', state.fontSize);
  }

  document.getElementById('toggleTranslationBtn').addEventListener('click', () => {
    state.showTranslation = !state.showTranslation;
    document.querySelectorAll('.translation-box').forEach(el => {
      el.classList.toggle('hidden', !state.showTranslation);
    });
    showToast(state.showTranslation ? 'تم إظهار الترجمة الإنجليزية' : 'تم إخفاء الترجمة الإنجليزية');
  });

  document.getElementById('toggleTafsirDrawerBtn').addEventListener('click', () => {
    const panel = document.getElementById('tafsirPanel');
    panel.classList.toggle('hidden');
    if (!panel.classList.contains('hidden')) {
      displayTafsirForAyah(state.activeAyahIndex || 1);
    }
  });
  document.getElementById('closeTafsirBtn').addEventListener('click', () => {
    document.getElementById('tafsirPanel').classList.add('hidden');
  });

  document.getElementById('themeToggleBtn').addEventListener('click', () => {
    const nextTheme = state.theme === 'parchment' ? 'dark' : state.theme === 'dark' ? 'sepia' : 'parchment';
    setTheme(nextTheme);
  });

  document.getElementById('zenModeToggleBtn').addEventListener('click', () => {
    toggleZenMode();
  });

  const reciterQuickBtn = document.getElementById('reciterQuickBtn');
  const reciterDropdown = document.getElementById('reciterDropdown');
  reciterQuickBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    reciterDropdown.classList.toggle('hidden');
  });
  document.addEventListener('click', () => {
    reciterDropdown.classList.add('hidden');
  });

  const settingsModal = document.getElementById('settingsModal');
  document.getElementById('openSettingsBtn').addEventListener('click', () => {
    settingsModal.classList.remove('hidden');
  });
  document.getElementById('closeSettingsBtn').addEventListener('click', () => {
    settingsModal.classList.add('hidden');
  });
  settingsModal.addEventListener('click', (e) => {
    if (e.target === settingsModal) settingsModal.classList.add('hidden');
  });

  document.querySelectorAll('.theme-select-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      setTheme(btn.dataset.setTheme);
    });
  });

  document.getElementById('settingsReciterSelect').addEventListener('change', (e) => {
    selectReciter(e.target.value);
  });

  document.getElementById('settingsFontSizeSlider').addEventListener('input', (e) => {
    state.fontSize = parseInt(e.target.value);
    updateFontSize();
  });

  document.getElementById('clearBookmarksBtn').addEventListener('click', () => {
    if (confirm('هل أنت متأكد من مسح جميع العلامات المرجعية؟')) {
      state.bookmarks = [];
      localStorage.removeItem('quran_bookmarks');
      renderBookmarksList();
      showToast('تم مسح جميع العلامات المرجعية');
    }
  });

  document.getElementById('resetCategoryAzkarBtn').addEventListener('click', () => {
    if (window.AZKAR_DATA) {
      const items = window.AZKAR_DATA[state.azkarCategory] || [];
      items.forEach(i => {
        delete state.azkarProgress[i.id];
      });
      renderAzkarCards(state.azkarCategory);
      showToast('تمت إعادة ضبط عدادات هذه الفئة');
    }
  });

  document.getElementById('resetAllDataBtn').addEventListener('click', () => {
    if (confirm('هل ترغب في إعادة ضبط جميع الإعدادات وسجل القراءة والمحفوظات؟')) {
      localStorage.clear();
      window.location.reload();
    }
  });

  setupTasbihTool();
}
