// ======================================================
// countdown.js — FINAL AUTO YEAR (SMART & CLEAN)
// ======================================================

export function initRamadhanCountdown(elSelector = "#countdownRamadhan") {
  const el = document.querySelector(elSelector);
  if (!el) return;

  // ==========================
  // FORMAT WAKTU
  // ==========================
  function fmt(ms) {
    if (ms <= 0) return "0 hari";

    const d = Math.floor(ms / 86400000);
    const h = Math.floor((ms % 86400000) / 3600000);
    const m = Math.floor((ms % 3600000) / 60000);
    const s = Math.floor((ms % 60000) / 1000);

    return `${d} hari ${h} jam ${m} menit ${s} detik`;
  }

  // ==========================
  // UPDATE COUNTDOWN
  // ==========================
  function tick() {
    const now = new Date();
    const year = now.getFullYear();

    // ==========================
    // DATA TANGGAL (UPDATE SETIAP TAHUN JIKA PERLU)
    // ==========================
    const data = {
      2026: { ramadhan: "2026-02-18", lebaran: "2026-03-20" },
      2027: { ramadhan: "2027-02-07", lebaran: "2027-03-10" },
      2028: { ramadhan: "2028-01-27", lebaran: "2028-02-27" }
    };

    // fallback jika tahun belum ada
    const current = data[year] || data[2026];
    const next    = data[year + 1] || data[2027];

    const ramadhanThisYear = new Date(current.ramadhan + "T00:00:00");
    const lebaranThisYear  = new Date(current.lebaran + "T00:00:00");

    const ramadhanNextYear = new Date(next.ramadhan + "T00:00:00");
    const lebaranNextYear  = new Date(next.lebaran + "T00:00:00");

    let text = "";

    // ==========================
    // LOGIKA KONDISI
    // ==========================
    if (now < ramadhanThisYear) {
      // sebelum Ramadhan
      const r = ramadhanThisYear - now;
      const l = lebaranThisYear - now;

      text = `🌙 Menuju Ramadhan: ${fmt(r)} — 🎉 Menuju Idul Fitri: ${fmt(l)}`;

    } else if (now < lebaranThisYear) {
      // saat Ramadhan
      const l = lebaranThisYear - now;

      text = `🕌 Ramadhan sedang berlangsung — 🎉 Menuju Idul Fitri: ${fmt(l)}`;

    } else if ((now - lebaranThisYear) < 3 * 86400000) {
      // 3 hari setelah lebaran (biar masih terasa suasananya)
      text = "🎊 Selamat Idul Fitri! Mohon maaf lahir dan batin";

    } else {
      // setelah lebaran → pindah ke tahun depan
      const r = ramadhanNextYear - now;
      const l = lebaranNextYear - now;

      text = `🌙 Menanti Ramadhan berikutnya: ${fmt(r)} — 🎉 Idul Fitri berikutnya: ${fmt(l)}`;
    }

    el.textContent = text;
  }

  // ==========================
  // JALANKAN
  // ==========================
  tick();
  setInterval(tick, 1000);
}