// ======================================================
// main.js FINAL — Dashboard Masjid (Style A - Classic)
// Compatible with index.php, sidebar component & CSS baru
// ======================================================

// Fallback agar tidak error ketika PHP belum kirim variabel
window.serverNextPrayer ??= null;
window.serverNextPrayerTime ??= null;
document.addEventListener("DOMContentLoaded", () => {

  // ---------------------------------------------
  // Helper selector
  // ---------------------------------------------
  const $  = (s) => document.querySelector(s);
  const $$ = (s) => document.querySelectorAll(s);

  // ---------------------------------------------
  // SIDEBAR TOGGLE
  // ---------------------------------------------
  const sidebar = $("#sidebar");
  const wrapper = $("#content-wrapper");
  const toggleBtn = $("#toggleSidebar");

  if (toggleBtn && sidebar && wrapper) {
  toggleBtn.addEventListener("click", () => {
    sidebar.classList.toggle("closed");
    wrapper.classList.toggle("collapsed");

    localStorage.setItem(
      "sidebar_closed",
      sidebar.classList.contains("closed") ? "true" : "false"
    );
  });
}


// ---------------------------------------------
// DROPDOWN SIDEBAR — WORKS BOTH MODES
// ---------------------------------------------
$$(".sidebar-dropdown").forEach(drop => {
    const toggle = drop.querySelector(".dropdown-toggle-sidebar");
    if (!toggle) return;

    toggle.addEventListener("click", (e) => {
        e.preventDefault();
        const sidebar = $("#sidebar");

        if (sidebar.classList.contains("closed")) {
            // Mode collapsed → floating menu
            drop.classList.toggle("open");
            $$(".sidebar-dropdown.open").forEach(d => {
                if (d !== drop) d.classList.remove("open");
            });
        } 
        else {
            // Mode full → accordion
            drop.classList.toggle("open");
            $$(".sidebar-dropdown.open").forEach(d => {
                if (d !== drop) d.classList.remove("open");
            });
        }
    });
});

  // ---------------------------------------------
  // ACTIVE MENU
  // ---------------------------------------------
  const currentPath = window.location.pathname.replace(/\/+$/, "");

  $$(".sidebar-menu a").forEach((a) => {
    const linkPath = a.pathname.replace(/\/+$/, "");
    if (linkPath === currentPath) {
      a.classList.add("active");
    }
  });

  // ---------------------------------------------
  // RIPPLE EFFECT
  // ---------------------------------------------
  $$(".ripple-container").forEach((el) => {
    el.addEventListener("click", function () {
      this.classList.remove("ripple-active");
      // Force reflow
      void this.offsetWidth;
      this.classList.add("ripple-active");
    });
  });

  // ---------------------------------------------
  // FULLSCREEN TOGGLE (Persist)
  // ---------------------------------------------
  const fsBtn  = $("#btnFullscreen");
  const fsIcon = $("#iconFullscreen");

  function enableFSUI() {
    if (!fsIcon) return;
    fsIcon.classList.remove("fa-expand");
    fsIcon.classList.add("fa-compress");
  }

  function disableFSUI() {
    if (!fsIcon) return;
    fsIcon.classList.remove("fa-compress");
    fsIcon.classList.add("fa-expand");
  }

  async function requestFS() {
    try {
      await document.documentElement.requestFullscreen();
    } catch (e) {
      console.warn("Fullscreen request failed:", e);
    }
  }

  if (fsBtn) {
    // Restore state
    if (localStorage.getItem("fullscreen") === "true" && !document.fullscreenElement) {
      requestFS().then(enableFSUI);
    }

    fsBtn.addEventListener("click", () => {
      if (!document.fullscreenElement) {
        requestFS().then(() => {
          enableFSUI();
          localStorage.setItem("fullscreen", "true");
        });
      } else {
        document.exitFullscreen();
        disableFSUI();
        localStorage.setItem("fullscreen", "false");
      }
    });
  }

  document.addEventListener("fullscreenchange", () => {
    if (!document.fullscreenElement) {
      disableFSUI();
      localStorage.setItem("fullscreen", "false");
    }
  });

  // ---------------------------------------------
  // COUNTDOWN WAKTU SHOLAT
  // ---------------------------------------------
  const lblPrayer   = $("#nextPrayerLabel");
  const hiddenTime  = $("#nextPrayerTime");
  const cdElement   = $("#countdownNextPrayer");

  let countdownTimer = null;

  function startCountdown(targetIso) {
    if (!cdElement || !targetIso) return;

    const target = new Date(targetIso);
    if (isNaN(target.getTime())) {
      cdElement.textContent = "--:--:--";
      return;
    }

    if (countdownTimer) clearInterval(countdownTimer);

    function tick() {
      const now  = new Date();
      const diff = target - now;

      if (diff <= 0) {
        cdElement.textContent = "00:00:00";
        clearInterval(countdownTimer);
        return;
      }

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

      cdElement.textContent =
        `${String(h).padStart(2, "0")}:` +
        `${String(m).padStart(2, "0")}:` +
        `${String(s).padStart(2, "0")}`;
    }

    tick();
    countdownTimer = setInterval(tick, 1000);
  }

  async function fetchPrayer(lat, lon) {
    try {
      const url = `${base_url}/pages/web_dashboard/php/get_waktu_sholat.php?lat=${lat}&lon=${lon}`;
      const r   = await fetch(url, { cache: "no-store" });
      return await r.json();
    } catch (e) {
      console.warn("Fetch get_waktu_sholat error:", e);
      return null;
    }
  }

  async function initPrayer() {
    const fallbackName = serverNextPrayer || "-";
    const fallbackTime = serverNextPrayerTime || "";

    if (!lblPrayer) return;

    // Default tampilan awal
    lblPrayer.textContent = fallbackName || "-";
    if (fallbackTime) startCountdown(fallbackTime);

    if (!navigator.geolocation) {
      // Tidak support GPS → pakai data server saja
      return;
    }

    navigator.geolocation.getCurrentPosition(
      async (pos) => {
        const data = await fetchPrayer(pos.coords.latitude, pos.coords.longitude);

        if (!data || data.error || !data.next_time) {
          // Pakai fallback server
          hiddenTime && (hiddenTime.value = fallbackTime);
          if (fallbackTime) startCountdown(fallbackTime);
          return;
        }

        lblPrayer.textContent = data.next_prayer || fallbackName;
        if (hiddenTime) hiddenTime.value = data.next_time;
        startCountdown(data.next_time);
      },
      () => {
        // User tolak GPS → tetap pakai fallback server
        hiddenTime && (hiddenTime.value = fallbackTime);
        if (fallbackTime) startCountdown(fallbackTime);
      },
      { timeout: 6000 }
    );
  }

  initPrayer();

  // ---------------------------------------------
  // CHARTS
  // ---------------------------------------------
  let chartJamaah = null;
  let chartAir    = null;
  let chartDonut  = null;

  // Line chart Jamaah 7 hari
  function initChartJamaah() {
    const canvas = $("#chartJamaah");
    if (!canvas || typeof Chart === "undefined") return;

    const ctx = canvas.getContext("2d");

    chartJamaah = new Chart(ctx, {
      type: "line",
      data: {
        labels: labelsJamaah || [],
        datasets: [
          {
            label: "Total Jamaah",
            data: dataJamaah || [],
            tension: 0.35,
            fill: true,
            borderWidth: 2,
            borderColor: "rgba(59,130,246,0.9)",      // biru
            backgroundColor: "rgba(59,130,246,0.12)", // biru lembut
            pointRadius: 3,
            pointHoverRadius: 4
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false }
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: { stepSize: 1 }
          }
        }
      }
    });
  }

  // Bar + Line chart Air
  function initChartAir() {
    const canvas = $("#chartAir");
    if (!canvas || typeof Chart === "undefined") return;

    const ctx = canvas.getContext("2d");

    chartAir = new Chart(ctx, {
      type: "bar",
      data: {
        labels: labelsAir || [],
        datasets: [
          {
            type: "bar",
            label: "Penggunaan (L)",
            data: dataAirUsage || [],
            borderWidth: 0,
            backgroundColor: "rgba(16,185,129,0.85)"   // hijau
          },
          {
            type: "line",
            label: "Pemasukan Air (L)",
            data: dataAirIncome || [],
            borderWidth: 2,
            borderColor: "rgba(6,95,70,0.95)",         // hijau gelap
            backgroundColor: "transparent",
            tension: 0.35,
            yAxisID: "y"
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { position: "bottom" }
        },
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
  }

  // Donut chart Jamaah 1 bulan
  function initChartDonut() {
    const canvas = $("#chartDonutJamaah");
  if (!canvas) return;

    const ctx = canvas.getContext("2d");

    const safeData = donutDataJamaah || {
      subuh: 1, dzuhur: 0, ashar: 0, maghrib: 0, isya: 0, diluar: 0
    };

    chartDonut = new Chart(ctx, {
      type: "doughnut",
      data: {
        labels: ["Subuh", "Dzuhur", "Ashar", "Maghrib", "Isya", "Di luar"],
        datasets: [
          {
            data: [
              safeData.subuh,
              safeData.dzuhur,
              safeData.ashar,
              safeData.maghrib,
              safeData.isya,
              safeData.diluar
            ],
            backgroundColor: [
              "#3b82f6", // biru
              "#22c55e", // hijau
              "#eab308", // kuning
              "#f97316", // oranye
              "#8b5cf6", // ungu
              "#64748b"  // abu
            ]
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: "60%",
        plugins: {
          legend: { position: "bottom" }
        }
      }
    });
  }

  initChartJamaah();
  initChartAir();
  initChartDonut();

  // ---------------------------------------------
  // AUTO REFRESH AIR (setiap 5 detik)
  // ---------------------------------------------
  async function refreshAir() {
  try {
    const url = base_url + "/pages/web_dashboard/php/get_air_realtime.php";
    const r   = await fetch(url, { cache: "no-store" });
    const d   = await r.json();

    const usageEl  = $("#airUsageToday");
    const incomeEl = $("#airIncomeToday");

    if (usageEl)  usageEl.textContent  = `${d.today_usage} L`;
    if (incomeEl) incomeEl.textContent = `Pemasukan: ${d.today_income} L`;

    if (chartAir && d.last7_usage && d.last7_income) {
      chartAir.data.datasets[0].data = d.last7_usage;
      chartAir.data.datasets[1].data = d.last7_income;
      chartAir.update();
    }
  } catch (err) {
    console.warn("Air refresh failed:", err);
  }
}

  refreshAir();
  setInterval(refreshAir, 5000);

});
