// ui-sholat.js — update waktu sholat fields + Iqomah countdown

export function updatePrayerTimes(times = {}) {
  const map = { 
    Fajr: "subuhTime", 
    Dhuhr: "dzuhurTime", 
    Asr: "asharTime", 
    Maghrib: "maghribTime", 
    Isha: "isyaTime" 
  };

  const cleaned = {};

  Object.keys(map).forEach(k => {
    const el = document.getElementById(map[k]);
    if (!el) return;

    const v = times[k] ? times[k].split(" ")[0].slice(0,5) : "--:--";
    el.textContent = v;

    cleaned[k] = v; // simpan data hasil untuk iqomah logic
  });

  // Setelah waktu sholat update, jalankan countdown iqomah
  startIqomahCountdown(cleaned);
}



// =====================================================
// IQOMAH COUNTDOWN (7 menit setelah adzan terakhir TODAY)
// =====================================================
function startIqomahCountdown(times) {
  const el = document.getElementById("countdownIqomah");
  if (!el) return;

  function tick() {
    const now = new Date();
    let adzanTerakhir = null;

    Object.values(times).forEach(t => {
      const [hh, mm] = t.split(":");
      if (!hh || !mm) return;

      const d = new Date();
      d.setHours(hh, mm, 0, 0);

      if (d <= now && (!adzanTerakhir || d > adzanTerakhir)) {
        adzanTerakhir = d;
      }
    });

    if (!adzanTerakhir) {
      el.textContent = "--:--:--";
      return;
    }

    // 7 menit setelah adzan terakhir
    const target = new Date(adzanTerakhir.getTime() + 7 * 60000);
    const diff = target - now;

    if (diff <= 0) {
      el.textContent = "--:--:--";
      return;
    }

    const h = String(Math.floor(diff / 3600000)).padStart(2, "0");
    const m = String(Math.floor((diff % 3600000) / 60000)).padStart(2, "0");
    const s = String(Math.floor((diff % 60000) / 1000)).padStart(2, "0");

    el.textContent = `${h}:${m}:${s}`;
  }

  // langsung jalan
  tick();

  // update tiap detik
  setInterval(tick, 1000);
}
