export function updateCarousel(events) {
    const container = document.querySelector("#carouselMasjid .carousel-inner");
    if (!container) return;

    container.innerHTML = "";
    const eventCount = events.length;

    let slides = [];

    if (eventCount === 0) {
        slides = defaultSlides();
    } 
    else if (eventCount <= 4) {
        slides = [
            ...events.map(e => eventSlide(e)),
            ...defaultSlides()
        ];
    } 
    else {
        slides = events.map(e => eventSlide(e));
    }

    slides.forEach((slide, i) => {
        slide.classList.add("carousel-item");
        if (i === 0) slide.classList.add("active");
        container.appendChild(slide);
    });
}

function eventSlide(e) {
    const div = document.createElement("div");
    div.innerHTML = `
        <img src="${e.foto}" class="d-block w-100" alt="Event">
        <div class="carousel-caption">
            <h5>${e.nama}</h5>
            <p>${e.deskripsi.substring(0, 50)}...</p>
        </div>
    `;
    return div;
}

function defaultSlides() {
    return [
        {
            title: "Masjid Saat Dzuhur",
            desc: "Langit cerah dan semangat ibadah.",
            img: "/assets/img/src/masjiddzuhur.jpeg"
        },
        {
            title: "Masjid Saat Subuh",
            desc: "Keheningan cahaya biru pagi.",
            img: "/assets/img/src/masjidsubuh.jpg"
        },
        {
            title: "Masjid Saat Ashar",
            desc: "Bayangan menari di pelataran.",
            img: "/assets/img/src/masjidashar.jpg"
        },
        {
            title: "Masjid Saat Maghrib",
            desc: "Jingga yang menenangkan.",
            img: "/assets/img/src/masjidmaghrib.jpg"
        },
        {
            title: "Masjid Saat Isya",
            desc: "Tenang dalam gelap malam.",
            img: "/assets/img/src/masjidisya.jpg"
        }
    ].map(s => {
        const div = document.createElement("div");
        div.innerHTML = `
            <img src="${s.img}" class="d-block w-100" alt="Masjid">
            <div class="carousel-caption">
                <h5>${s.title}</h5>
                <p>${s.desc}</p>
            </div>
        `;
        return div;
    });
}
