﻿// ✅ Store carousel state globally to prevent multiple timers running simultaneously
let eventCarouselInterval = null;

// ✅ Initialize event carousel
function initEventCarousel() {
    console.log('🎠 Initializing event carousel...');

    // Clear any existing interval before starting a new one
    if (eventCarouselInterval) {
        clearInterval(eventCarouselInterval);
        eventCarouselInterval = null;
    }

    const slides = document.querySelectorAll('.carousel-slide');
    const dots = document.querySelectorAll('.carousel-dot');

    if (slides.length === 0) {
        console.log('No carousel slides found');
        return;
    }

    let currentSlide = 0;

    function showSlide(index) {
        slides.forEach((slide, i) => {
            slide.classList.remove('active');
            if (dots[i]) dots[i].classList.remove('active');
        });

        if (slides[index]) {
            slides[index].classList.add('active');
            if (dots[index]) dots[index].classList.add('active');
        }
    }

    // Force show the first slide immediately
    showSlide(0);

    // Auto advance every 5 seconds
    eventCarouselInterval = setInterval(() => {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }, 5000);

    // Manual dot controls
    dots.forEach((dot, index) => {
        // Use onclick to ensure we don't stack event listeners on re-init
        dot.onclick = () => {
            currentSlide = index;
            showSlide(currentSlide);

            // Reset timer on manual click to give user time to read
            clearInterval(eventCarouselInterval);
            eventCarouselInterval = setInterval(() => {
                currentSlide = (currentSlide + 1) % slides.length;
                showSlide(currentSlide);
            }, 5000);
        };
    });

    console.log('✅ Carousel initialized with', slides.length, 'slides');
}

// ✅ Reinitialize all Slick sliders
function reinitializeSliders() {
    console.log('🔄 Starting slider reinitialization...');

    // Destroy existing slick instances first
    if (window.jQuery && $.fn.slick) {
        $('.slick-initialized').each(function () {
            $(this).slick('unslick');
        });
    }

    // Reinitialize slide-3 (blog section)
    if ($('.slide-3').length) {
        $('.slide-3').slick({
            infinite: true,
            speed: 300,
            slidesToShow: 3,
            slidesToScroll: 1,
            autoplay: true,
            autoplaySpeed: 5000,
            dots: false,
            arrows: true,
            responsive: [
                { breakpoint: 1200, settings: { slidesToShow: 2, slidesToScroll: 1 } },
                { breakpoint: 767, settings: { slidesToShow: 1, slidesToScroll: 1 } }
            ]
        });
    }

    // Reinitialize slide-1 (home slider)
    if (typeof window.initHomeSlider === 'function' && $('.slide-1').length) {
        window.initHomeSlider();
    }

    // Reinitialize slide-2
    if ($('.slide-2').length) {
        $('.slide-2').slick({
            infinite: true,
            slidesToShow: 2,
            slidesToScroll: 2,
            responsive: [{ breakpoint: 991, settings: { slidesToShow: 1, slidesToScroll: 1 } }]
        });
    }

    // Reinitialize slide-4
    if ($('.slide-4').length) {
        $('.slide-4').slick({
            infinite: false,
            slidesToShow: 4,
            slidesToScroll: 1,
            autoplay: true,
            responsive: [
                { breakpoint: 1200, settings: { slidesToShow: 3 } },
                { breakpoint: 991, settings: { slidesToShow: 2 } },
                { breakpoint: 586, settings: { slidesToShow: 1 } }
            ]
        });
    }

    // ✅ Crucial: Initialize the custom Event Carousel if the slides exist in DOM
    if (document.querySelector('.carousel-slide')) {
        initEventCarousel();
    }

    console.log('✅ Slider reinitialization complete');
}

// ✅ Initialize Jarallax
function initJarallax() {
    if (typeof jarallax !== "undefined") {
        jarallax(document.querySelectorAll('.jarallax'), {
            speed: 0.3
        });
    }
}

// ✅ Main page loader function
async function loadPage(page) {
    try {
        console.log(`📄 Loading page: ${page}`);

        // Update URL
        updateURL(page);

        const response = await fetch(`/Home/LoadPage?page=${page}`);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

        const html = await response.text();
        const container = document.getElementById("maincontnet");

        if (!container) return;

        // Inject content
        container.innerHTML = html;
        window.scrollTo(0, 0);

        // Update active menu item
        document.querySelectorAll("[data-page]").forEach(a => a.classList.remove("active"));
        const activeLink = document.querySelector(`[data-page="${page}"]`);
        if (activeLink) activeLink.classList.add("active");

        // ✅ Wait for DOM and give a small buffer for Browser rendering
        setTimeout(() => {
            if (window.lazySizes) lazySizes.loader.checkElems();

            reinitializeSliders();
            initJarallax();

            if (typeof initOwlCarousel === 'function') {
                initOwlCarousel();
            }

            console.log('✅ Page initialization complete');
        }, 300);

    } catch (error) {
        console.error('❌ Error loading page:', error);
    }
}

// ✅ Event Listeners
document.addEventListener('DOMContentLoaded', function () {
    // Determine initial page from URL or default to home
    const path = window.location.pathname.split('/').pop() || "home";
    loadPage(path);
});

document.addEventListener("click", function (e) {
    const a = e.target.closest("[data-page]");
    if (a) {
        e.preventDefault();
        const page = a.getAttribute("data-page");
        loadPage(page);
    }
});

window.addEventListener('popstate', function (e) {
    if (e.state && e.state.page) {
        loadPage(e.state.page);
    }
});

function updateURL(page) {
    const newURL = `/Home/${page}`;
    if (window.location.pathname !== newURL) {
        history.pushState({ page: page }, '', newURL);
    }
}