document.addEventListener('DOMContentLoaded', function () {
    // Active Link Highlighting
    const currentPath = window.location.pathname.replace(/\/+$/, '');
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    navLinks.forEach(link => {
        const href = link.getAttribute('href').split('?')[0];
        const linkPath = href.replace(/\/+$/, '');
        if (currentPath.endsWith(linkPath) || (linkPath === 'index.php' && currentPath === '/')) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    // Add some animation effects on cards on hover/scroll
    const cards = document.querySelectorAll('.service-card, .animated-card, .certification-card');
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    cards.forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
        observer.observe(card);
    });

    // Theme Toggle (Light/Dark Mode)
    const themeToggle = document.getElementById('theme-toggle');
    const themeIcon = themeToggle ? themeToggle.querySelector('.theme-icon') : null;
    const htmlElement = document.documentElement;
    
    // Function to apply theme and update icon
    const applyTheme = (theme) => {
        htmlElement.setAttribute('data-theme', theme);
        if (themeIcon) {
            themeIcon.textContent = theme === 'dark' ? '☀️' : '🌙';
        }
        localStorage.setItem('theme', theme);
    };
    
    // Toggle theme on button click
    if (themeToggle) {
        themeToggle.addEventListener('click', function () {
            const currentTheme = htmlElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            applyTheme(newTheme);
        });
    }
    
    // Apply initial theme on load (the script in header.php already sets the attribute)
    const initialTheme = localStorage.getItem('theme') || 'light';
    if (themeIcon) {
        themeIcon.textContent = initialTheme === 'dark' ? '☀️' : '🌙';
    }

    // Image Slider Functionality
    const sliderItems = document.querySelectorAll('.slider-item');
    const sliderIndicators = document.querySelectorAll('.indicator');
    const sliderPrev = document.querySelector('.slider-prev');
    const sliderNext = document.querySelector('.slider-next');
    
    let currentSlide = 0;
    let autoSlideInterval;
    
    function showSlide(index) {
        // Remove active class from all slides and indicators
        sliderItems.forEach(item => item.classList.remove('active'));
        sliderIndicators.forEach(indicator => indicator.classList.remove('active'));
        
        // Add active class to current slide and indicator
        if (sliderItems[index]) {
            sliderItems[index].classList.add('active');
        }
        if (sliderIndicators[index]) {
            sliderIndicators[index].classList.add('active');
        }
    }
    
    function nextSlide() {
        currentSlide = (currentSlide + 1) % sliderItems.length;
        showSlide(currentSlide);
        resetAutoSlide();
    }
    
    function prevSlide() {
        currentSlide = (currentSlide - 1 + sliderItems.length) % sliderItems.length;
        showSlide(currentSlide);
        resetAutoSlide();
    }
    
    function goToSlide(index) {
        currentSlide = index;
        showSlide(currentSlide);
        resetAutoSlide();
    }
    
    function startAutoSlide() {
        autoSlideInterval = setInterval(() => {
            nextSlide();
        }, 5000); // Change slide every 5 seconds
    }
    
    function resetAutoSlide() {
        clearInterval(autoSlideInterval);
        startAutoSlide();
    }
    
    // Add event listeners to slider controls
    if (sliderPrev) {
        sliderPrev.addEventListener('click', prevSlide);
    }
    
    if (sliderNext) {
        sliderNext.addEventListener('click', nextSlide);
    }
    
    sliderIndicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => goToSlide(index));
    });
    
    // Start auto-slide if there are slides
    if (sliderItems.length > 1) {
        startAutoSlide();
    }
});

const pageLoadStartTime = Date.now();
window.addEventListener('load', function() {
    const preloader = document.getElementById('page-loader');
    if (preloader) {
        // Check if the preloader has been shown in this session
        if (!sessionStorage.getItem('preloaderShown')) {
            const loadTime = Date.now() - pageLoadStartTime;
            const minDisplayTime = 1000; // 1 second
            const remainingTime = Math.max(0, minDisplayTime - loadTime);

            setTimeout(() => {
                preloader.style.display = 'none';
                sessionStorage.setItem('preloaderShown', 'true'); // Mark as shown

                // Play a subtle sound effect on first load
                try {
                    const loadSound = new Audio('https://cdn.pixabay.com/download/audio/2022/03/10/audio_c848a63499.mp3?filename=success-1-6297.mp3');
                    loadSound.volume = 0.2; // Set volume to be subtle
                    loadSound.play();
                } catch (e) { /* Fails silently if browser blocks autoplay */ }

            }, remainingTime);
        } else {
            preloader.style.display = 'none'; // Hide immediately on subsequent loads
        }
        // Welcome Modal Logic - Show after page is fully loaded
        const path = window.location.pathname;
        const isHomePage = path.endsWith('/') || path.endsWith('index.php') || path.endsWith('/public/');
        if (isHomePage) {
            const welcomeModalEl = document.getElementById('welcomeModal');
            if (welcomeModalEl) {
                const welcomeModal = new bootstrap.Modal(welcomeModalEl);
                if (welcomeModal) {
                    setTimeout(() => {
                        welcomeModal.show();
                    }, 2000);
                }
            }
        }
    }
});

// This code was missing from the previous consolidation
document.addEventListener('DOMContentLoaded', function() {
    // Animated Stats Counter
    const statsSection = document.querySelector('.stats-section');
    if (statsSection) {
        const counters = document.querySelectorAll('.stat-number');
        const speed = 200;

        const animateCounter = (counter) => {
            const originalText = counter.innerText;
            const target = +counter.getAttribute('data-target');
            counter.innerText = '0';

            const updateCount = () => {
                const count = +counter.innerText.replace(/,/g, '');
                const inc = target / speed;

                if (count < target) {
                    counter.innerText = Math.ceil(count + inc).toLocaleString();
                    setTimeout(updateCount, 15);
                } else {
                    counter.innerText = originalText;
                }
            };
            updateCount();
        };

        const statsObserver = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting) {
                counters.forEach(animateCounter);
                statsObserver.disconnect();
            }
        }, { threshold: 0.5 });
        statsObserver.observe(statsSection);
    }

    // Hero Slider Auto-Cycle
    const heroSliderContainer = document.querySelector('.hero-slider-container');
    if (heroSliderContainer) {
        const slides = heroSliderContainer.querySelectorAll('.hero-slide');
        if (slides.length > 1) {
            let currentSlide = 0;
            setInterval(() => {
                if (document.visibilityState === 'visible') {
                    slides[currentSlide].classList.remove('active');
                    currentSlide = (currentSlide + 1) % slides.length;
                    slides[currentSlide].classList.add('active');
                }
            }, 5000);
        }
    }

    // Page Loader on Navigation
    const pageLoader = document.getElementById('page-loader');
    if (pageLoader) {
        const navLinksForLoader = document.querySelectorAll('.navbar-nav .nav-link, .footer-links a, .explore-card');
        navLinksForLoader.forEach(link => {
            link.addEventListener('click', function(e) {
                const href = link.getAttribute('href');
                if (href && href.indexOf('#') === -1 && link.hostname === window.location.hostname) {
                    pageLoader.style.display = 'flex';
                }
            });
        });
    }

    // Scroll to Top/Bottom Button Logic
    const scrollBtn = document.getElementById('scroll-btn');
    if (scrollBtn) {
        const scrollIcon = scrollBtn.querySelector('i');
        window.addEventListener('scroll', function() {
            const scrollPosition = window.scrollY || document.documentElement.scrollTop;
            const pageHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;

            if (scrollPosition > 100) {
                scrollBtn.classList.add('visible');
            } else {
                scrollBtn.classList.remove('visible');
            }

            if (scrollPosition > pageHeight / 2) {
                scrollIcon.className = 'bi bi-arrow-up';
                scrollBtn.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' });
            } else {
                scrollIcon.className = 'bi bi-arrow-down';
                scrollBtn.onclick = () => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
            }
        });
    }
});
