// init.js — API <-> UI (final, dengan next-prayer + countdown + sumber daya)
import { fetchJamaah } from "../api/jamaah.js";
import { fetchKeuangan } from "../api/keuangan.js";
import { fetchSumberDaya } from "../api/sumberdaya.js";
import { fetchHijriForToday } from "../api/hijriah.js";

import { updateJamaahCards } from "./ui-jamaah.js";
import { updateKeuanganUI } from "./ui-keuangan.js";
import { renderSumberDaya } from "./ui-sumberdaya.js";
import { updatePrayerTimes } from "./ui-sholat.js";
import { renderJamaahChart } from "./ui-chart.js";
import { updateNextPrayerLabel } from "./ui-countdown.js";

import { detectLocation } from "../system/location.js";


// ==============================
//  UTIL: cari sholat berikutnya
// ==============================
function findNextPrayer(timings) {
  const now = new Date();

  const list = [
    { name: "Subuh",   time: timings.Fajr },
    { name: "Dzuhur",  time: timings.Dhuhr },
    { name: "Ashar",   time: timings.Asr },
    { name: "Maghrib", time: timings.Maghrib },
    { name: "Isya",    time: timings.Isha },
  ];

  for (const p of list) {
    const [h, m] = p.time.split(":");
    const t = new Date();
    t.setHours(h, m, 0, 0);
    if (t > now) return { name: p.name, date: t };
  }

  // kalau semua sudah lewat → next = Subuh besok
  const [h, m] = timings.Fajr.split(":");
  const t = new Date();
  t.setDate(t.getDate() + 1);
  t.setHours(h, m, 0, 0);
  return { name: "Subuh", date: t };
}


// ==============================
//  Ambil waktu sholat + countdown
// ==============================
async function loadPrayerTimesAndCountdown() {
  try {
    const loc = await detectLocation();
    const now = new Date();

    const res = await fetch(
      `https://api.aladhan.com/v1/calendar?latitude=${loc.lat}&longitude=${loc.lon}&method=2&month=${now.getMonth() + 1}&year=${now.getFullYear()}`
    );

    const js = await res.json();
    const today = js.data[now.getDate() - 1].timings;

    // update tabel sholat
    updatePrayerTimes(today);

    // tampilkan lokasi
    const userLocEl = document.getElementById("userLocation");
    if (userLocEl) userLocEl.textContent = loc.label || "Lokasi Anda";

    // tentukan sholat berikutnya
    const next = findNextPrayer({
      Fajr:    today.Fajr.split(" ")[0],
      Dhuhr:   today.Dhuhr.split(" ")[0],
      Asr:     today.Asr.split(" ")[0],
      Maghrib: today.Maghrib.split(" ")[0],
      Isha:    today.Isha.split(" ")[0],
    });

    // update label sholat berikutnya + countdown
    function tick() {
      const now = new Date();
      const diff = next.date - now;

      if (diff <= 0) {
        updateNextPrayerLabel("-", "--:--:--");
        return;
      }

      const hh = String(Math.floor(diff / 3600000)).padStart(2, "0");
      const mm = String(Math.floor((diff % 3600000) / 60000)).padStart(2, "0");
      const ss = String(Math.floor((diff % 60000) / 1000)).padStart(2, "0");

      updateNextPrayerLabel(next.name, `${hh}:${mm}:${ss}`);
    }

    tick();
    setInterval(tick, 1000);

  } catch (e) {
    console.warn("Prayer times error:", e);
  }
}


// ==============================
//  MAIN INIT
// ==============================
export function initUI() {
  (async () => {
    // ambil semua data awal paralel biar cepat
    const [jamaah, keu, sumber, hijri] = await Promise.all([
      fetchJamaah(),
      fetchKeuangan(),
      fetchSumberDaya(),
      fetchHijriForToday()
    ]);

    // jamaah + chart
    if (jamaah) {
      updateJamaahCards(jamaah);
      const arr = [
        jamaah.subuh,
        jamaah.dzuhur,
        jamaah.ashar,
        jamaah.maghrib,
        jamaah.isya
      ].map(x => x || 0);
      renderJamaahChart("chartJamaahHarian", arr);
    }

    // keuangan
    if (keu) updateKeuanganUI(keu);

    // sumber daya
    if (sumber?.items) renderSumberDaya(sumber.items);

    // hijriah
    if (hijri) {
      const hijriEl = document.getElementById("tanggal-hijriah");
      if (hijriEl) {
        hijriEl.textContent = `${hijri.day} ${hijri.month.en} ${hijri.year} H`;
      }
    }

    // waktu sholat + next prayer
    await loadPrayerTimesAndCountdown();
  })();

  // -------- POLLING BERKALA --------

  // jamaah: tiap 3 detik
  setInterval(async () => {
    const j = await fetchJamaah();
    if (j) updateJamaahCards(j);
  }, 3000);

  // keuangan: tiap 5 detik
  setInterval(async () => {
    const k = await fetchKeuangan();
    if (k) updateKeuanganUI(k);
  }, 5000);

  // sumber daya: tiap 30 detik
  setInterval(async () => {
    const s = await fetchSumberDaya();
    if (s?.items) renderSumberDaya(s.items);
  }, 30000);

  // lightweight “check” (kalau suatu saat mau dipakai)
  setInterval(async () => {
    try {
      await fetchSumberDaya("check");
    } catch {
      // diam saja, ini cuma heartbeat
    }
  }, 1000);

  // refresh waktu sholat tiap 1 jam
  setInterval(loadPrayerTimesAndCountdown, 3600000);
}
