// sholat.js — FINAL PRO SMART PRAYER TIMER
import { updateNextPrayerLabel, markActivePrayer, flashCritical } from "../ui/ui-countdown.js";

let countdownInterval = null;
let iqomahEnd = null;
let nextPrayer = null;

export async function loadPrayerTimes(coords, ui = {}) {
    const { lat, lon } = coords;
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();

    try {
        const res = await fetch(
            `https://api.aladhan.com/v1/calendar?latitude=${lat}&longitude=${lon}&method=2&month=${month}&year=${year}`
        );
        const json = await res.json();

        const today = json.data[day - 1]?.timings;
        const tomorrow = json.data[day]?.timings;
        if (!today) return;

        const clean = (t) => t.split(" ")[0];

        ui.subuh.textContent = clean(today.Fajr);
        ui.dzuhur.textContent = clean(today.Dhuhr);
        ui.ashar.textContent = clean(today.Asr);
        ui.maghrib.textContent = clean(today.Maghrib);
        ui.isya.textContent = clean(today.Isha);

        startSmartCountdown(today, tomorrow);
    } catch (err) {
        console.error("Gagal mengambil jadwal sholat:", err);
    }
}

const SHOLAT_RULES = [
    { key: "Subuh", api: "Fajr", iqomah: 10 },
    { key: "Dzuhur", api: "Dhuhr", iqomah: 15 },
    { key: "Ashar", api: "Asr", iqomah: 10 },
    { key: "Maghrib", api: "Maghrib", iqomah: 5 },
    { key: "Isya", api: "Isha", iqomah: 10 },
];

function startSmartCountdown(today, tomorrow) {
    function compute() {
        const now = new Date();
        let foundNext = null;

        for (const s of SHOLAT_RULES) {
            const start = toDate(today[s.api]);
            const endIqomah = addMinutes(start, s.iqomah);

            if (now < start) {
                // Sholat berikutnya
                foundNext = {
                    name: s.key,
                    time: start,
                    iqomah: s.iqomah
                };
                break;
            }

            if (now >= start && now <= endIqomah) {
                // Sedang berlangsung → hitung iqomah
                markActivePrayer(s.key);
                iqomahEnd = endIqomah;
                return updateIqomahCountdown();
            }
        }

        // Lewat Isya → ke Subuh besok
        if (!foundNext && tomorrow) {
            const subuhBesok = toDate(tomorrow.Fajr);
            subuhBesok.setDate(subuhBesok.getDate() + 1);
            foundNext = { name: "Subuh", time: subuhBesok, iqomah: 10 };
        }

        if (!foundNext) return;

        nextPrayer = foundNext;
        markActivePrayer(""); // reset
        updateNextPrayerCountdown();
    }

    compute();
    clearInterval(countdownInterval);
    countdownInterval = setInterval(compute, 1000);
}

const toDate = (str) => {
    const [h, m] = str.split(":").map(Number);
    const d = new Date();
    d.setHours(h, m, 0, 0);
    return d;
};

const addMinutes = (date, m) => new Date(date.getTime() + m * 60000);

const fmt = (ms) => {
    const H = Math.floor(ms / 3600000);
    const M = Math.floor((ms % 3600000) / 60000);
    const S = Math.floor((ms % 60000) / 1000);
    return `${pad(H)}:${pad(M)}:${pad(S)}`;
};

const pad = (x) => String(x).padStart(2, "0");

function updateNextPrayerCountdown() {
    const now = new Date();
    const diff = nextPrayer.time - now;
    if (diff <= 0) return;

    updateNextPrayerLabel(nextPrayer.name, fmt(diff));

    if (diff <= 60000) flashCritical("#countdownNextPrayer");
}

function updateIqomahCountdown() {
    const now = new Date();
    const diff = iqomahEnd - now;
    if (diff <= 0) return;

    const el = document.getElementById("countdownIqomah");
    if (el) el.textContent = fmt(diff);

    if (diff <= 60000) flashCritical("#countdownIqomah");
}
