// ======================================================
// main.js — FINAL ULTRA CLEAN + SMART CAROUSEL
// ======================================================
import { initSystem } from "./system/init.js";
import { initUI } from "./ui/init.js";
import { detectLocation } from "./system/location.js";

console.log("%c[Monitoring] main loaded", "color:#7dd3fc; font-weight:700;");

// Path Base Website
const baseUrl = window.location.origin;

document.addEventListener("DOMContentLoaded", () => {

  // ========== INIT CORE SYSTEM ==========
  initSystem();
  initUI();
  console.log("[Monitoring] UI initialized");

  // ======================================================
  // SMART CAROUSEL — Event Prioritized
  // ======================================================
  async function updateCarousel() {
    const carouselInner = document.querySelector("#carouselMasjid .carousel-inner");
    if (!carouselInner) return;

    try {
      const res = await fetch(window.API_BASE + "events_upcoming.php");
      const events = await res.json();
      console.log("[Carousel] Events loaded:", events);

      // Jika tidak ada event aktif → gunakan default slide
      if (!events || events.length === 0) return;

      // Jika ada event → hapus semua slide default
      carouselInner.innerHTML = "";

      events.forEach((event, index) => {
        const div = document.createElement("div");
        div.className = `carousel-item ${index === 0 ? "active" : ""}`;

        const imgSrc =
          event.foto && event.foto !== ""
            ? `${baseUrl}/assets/img/kegiatan/${event.foto}`
            : `${baseUrl}/assets/img/src/masjid-event.jpg`;

        div.innerHTML = `
          <img src="${imgSrc}" class="d-block w-100" alt="${event.nama_kegiatan}">
          <div class="carousel-caption">
            <h5>${event.nama_kegiatan}</h5>
            <p>${event.deskripsi ? event.deskripsi : ""}</p>
          </div>
        `;

        carouselInner.appendChild(div);
      });

      console.log("%c[Carousel] Event Slides Applied!", "color:#22c55e; font-weight:700;");

    } catch (err) {
      console.warn("[Carousel] Error loading events:", err);
    }
  }

  updateCarousel(); // Jalankan Smart Carousel 🔥


  // ======================================================
  // Logging Lokasi
  // ======================================================
  detectLocation().then(loc => {
    console.log("Lokasi terdeteksi:", loc);

    const label = encodeURIComponent(loc.label ?? "Unknown");

    fetch("/app/auth/save_access.php", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: `lat=${loc.lat}&lon=${loc.lon}&label=${label}`
    })
    .then(() => console.log("%cAccess logged!", "color:#4ade80; font-weight:600;"))
    .catch(err => console.warn("Log gagal:", err));
  });

});
