'use strict';

// Wait for the page to fully load
window.addEventListener('load', function () {
    'use strict';
    const loader = document.querySelector('.loader-container');

    // Add the hide class to fade out the loader
    loader.classList.add('hide');

    // Remove the loader from the DOM after the transition
    loader.addEventListener('transitionend', function () {
        'use strict';
        loader.remove();
    });
});

// Hero Initialize animations
window.addEventListener('load', () => {
    const revealElements = document.querySelectorAll('.reveal-up');
    revealElements.forEach(el => {
        el.style.animationPlayState = 'running';
    });
});

// Hero Parallax effect
window.addEventListener('scroll', () => {
    const scrolled = window.pageYOffset;
    const floatingElements = document.querySelectorAll('.floating-element');

    floatingElements.forEach((element, index) => {
        const speed = (index + 1) * 0.5;
        element.style.transform = `translateY(${scrolled * speed}px)`;
    });
});

// Enhanced word rotation with letter-by-letter animation
let currentIndex = 0;

function animateWord() {
    const wordElements = document.querySelectorAll('.word-animation');
    
    // Check if we have any word elements
    if (wordElements.length === 0) {
        return;
    }
    
    const currentWord = document.getElementById(`word-${currentIndex}`);
    const nextIndex = (currentIndex + 1) % wordElements.length;
    const nextWord = document.getElementById(`word-${nextIndex}`);

    // Check if elements exist
    if (!currentWord) {
        return;
    }
    
    if (!nextWord) {
        return;
    }

    // Animate current word out
    currentWord.classList.remove('active');
    currentWord.classList.add('slide-out-up');

    setTimeout(() => {
        // Reset current word position
        currentWord.classList.remove('slide-out-up');
        currentWord.classList.add('slide-in-down');

        // Animate next word in
        nextWord.classList.remove('slide-in-down');
        nextWord.classList.add('active');

        // Add letter bounce animation
        const letters = nextWord.querySelectorAll('.word-letter');
        letters.forEach((letter, index) => {
            setTimeout(() => {
                letter.classList.add('letter-bounce');
                setTimeout(() => {
                    letter.classList.remove('letter-bounce');
                }, 600);
            }, index * 100);
        });

        currentIndex = nextIndex;
    }, 400);
}

// Number counter animation
function animateCounter(element, target) {
    const duration = 2000;
    const start = 0;
    const increment = target / (duration / 16);
    let current = start;

    const timer = setInterval(() => {
        current += increment;
        if (current >= target) {
            element.textContent = target + (element.parentNode.textContent.includes('M+') ? 'M+' : '');
            clearInterval(timer);
        } else {
            element.textContent = Math.floor(current) + (element.parentNode.textContent.includes('M+') ? 'M+' : '');
        }
    }, 16);
}

// Initialize animations when page loads
window.addEventListener('load', () => {

    // Start word rotation
    setTimeout(() => {
        setInterval(animateWord, 3000);
    }, 2000);

    // Start counter animations
    setTimeout(() => {
        document.querySelectorAll('.counter').forEach(counter => {
            const target = parseInt(counter.getAttribute('data-target'));
            animateCounter(counter, target);
        });
    }, 1500);
});

// Add scroll-triggered animations
const observerOptions = {
    threshold: 0.3,
    rootMargin: '0px 0px -100px 0px'
};

const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.animationPlayState = 'running';
        }
    });
}, observerOptions);

// Observe all animated elements
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.slide-up-enhanced').forEach(el => {
        observer.observe(el);
    });
});
//End hero 
document.addEventListener('DOMContentLoaded', function () {
    'use strict';
    const options = {
        root: null,
        rootMargin: '0px',
        threshold: 0.1
    };

    const revealCallback = (entries, observer) => {
        'use strict';
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('reveal-visible');
                // Once revealed, no need to observe anymore
                observer.unobserve(entry.target);
            }
        });
    };

    const observer = new IntersectionObserver(revealCallback, options);

    // Observe all reveal-trigger elements
    document.querySelectorAll('.reveal-trigger').forEach(element => {
        observer.observe(element);
    });
});

// Handle reveals on dynamic content
function initializeReveals() {
    'use strict';
    const options = {
        root: null,
        rootMargin: '0px',
        threshold: 0.1
    };

    const observer = new IntersectionObserver((entries) => {
        'use strict';
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('reveal-visible');
                observer.unobserve(entry.target);
            }
        });
    }, options);

    document.querySelectorAll('.reveal-trigger').forEach(reveal => {
        // Reset the element's state
        reveal.classList.remove('reveal-visible');
        observer.observe(reveal);
    });
}

// Initialize on page load
window.addEventListener('load', initializeReveals);

document.addEventListener('DOMContentLoaded', () => {
    'use strict';
    const filterButtons = document.querySelectorAll('.filter-btn');

    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            'use strict';
            // Update button styles
            filterButtons.forEach(btn => {
                btn.classList.remove('active-tab');
                //   btn.classList.add('active-tab');
            });
            button.classList.remove('active-tab');
            button.classList.add('active-tab');

            // Filter gallery items
            const category = button.getAttribute('data-category');
            const items = document.querySelectorAll('#galleryGrid > div');

            items.forEach(item => {
                if (category === 'all' || item.getAttribute('data-category') === category) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    });
});

// Function to initialize animations for large screens and handle small screens
function initAnimations() {
    'use strict';
    // For screens larger than 1024px, use intersection observer
    if (window.innerWidth > 1024) {
        const observer = new IntersectionObserver((entries) => {
            'use strict';
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('is-visible');
                }
            });
        }, { threshold: 0.1 });

        document.querySelectorAll('.fade-in-effect').forEach(
            section => observer.observe(section)
        );
    }
    // For smaller screens, add 'is-visible' class by default
    else {
        document.querySelectorAll('.fade-in-effect').forEach(
            section => section.classList.add('is-visible')
        );
    }
}

// Initialize animations on page load
document.addEventListener("DOMContentLoaded", initAnimations);

// For Elementor editor
jQuery(window).on('elementor/frontend/init', function () {
    'use strict';
    elementorFrontend.hooks.addAction('frontend/element_ready/widget', initAnimations);
});

document.addEventListener('DOMContentLoaded', function () {
    'use strict';
    const menuToggle = document.querySelector('.menu-toggle');
    const mainNav = document.querySelector('.main-navigation .menu');
    const subMenuParents = document.querySelectorAll('.menu-item-has-children > a');

    // Toggle mobile menu
    if (menuToggle) {
        menuToggle.addEventListener('click', function () {
            'use strict';
            this.classList.toggle('active');
            if (mainNav) {
                mainNav.classList.toggle('active');
            }
        });
    }

    // Handle submenu toggles
    subMenuParents.forEach(item => {
        const arrowElement = item.querySelector('.the-arrow');
        const navLink = item.querySelector('.nav_link');

        // Add click handler for arrow
        if (arrowElement) {
            arrowElement.addEventListener('click', function (e) {
                'use strict';
                if (window.innerWidth <= 768) {
                    e.preventDefault();
                    e.stopPropagation(); // Prevent event bubbling
                    item.classList.toggle('active');
                    const subMenu = item.nextElementSibling;
                    if (subMenu) {
                        subMenu.classList.toggle('active');
                    }
                }
            });
        }

        // Add click handler for nav link
        if (navLink) {
            navLink.addEventListener('click', function (e) {
                'use strict';
                if (window.innerWidth <= 768) {
                    e.stopPropagation(); // Prevent event bubbling
                    // Allow default behavior for navigation
                }
            });
        }

        // Prevent default behavior on parent anchor only if clicking the arrow
        item.addEventListener('click', function (e) {
            'use strict';
            if (window.innerWidth <= 768 && e.target.closest('.the-arrow')) {
                e.preventDefault();
            }
        });
    });

    // Close mobile menu on window resize
    window.addEventListener('resize', function () {
        'use strict';
        if (window.innerWidth > 768) {
            if (menuToggle) {
                menuToggle.classList.remove('active');
            }
            if (mainNav) {
                mainNav.classList.remove('active');
            }
            document.querySelectorAll('.sub-menu.active').forEach(menu => {
                menu.classList.remove('active');
            });
            document.querySelectorAll('.menu-item-has-children > a.active').forEach(item => {
                item.classList.remove('active');
            });
        }
    });
});

//Gallery Popup
document.addEventListener('DOMContentLoaded', function () {
    'use strict';
    // Get all gallery items
    const galleryItems = document.querySelectorAll('#galleryGrid .group');
    const popup = document.getElementById('galleryPopup');
    const popupImage = document.getElementById('popupImage');
    const imageTitle = document.getElementById('imageTitle');
    const imageDescription = document.getElementById('imageDescription');
    const categoryDot = document.getElementById('categoryDot');
    const categoryName = document.getElementById('categoryName');
    const closeBtn = document.getElementById('closePopup');
    const prevBtn = document.getElementById('prevImage');
    const nextBtn = document.getElementById('nextImage');

    let currentIndex = 0;
    let visibleItems = [...galleryItems]; // All items initially

    // Filter functionality (existing)
    const filterButtons = document.querySelectorAll('.filter-btn');

    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            // Update active button
            filterButtons.forEach(btn => btn.classList.remove('active-tab'));
            button.classList.add('active-tab');

            const category = button.dataset.category;

            // Filter items
            visibleItems = [...galleryItems].filter(item => {
                if (category === 'all') return true;
                return item.dataset.category === category;
            });

            // Show/hide items based on filter
            galleryItems.forEach(item => {
                if (category === 'all' || item.dataset.category === category) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        });
    });

    // Open popup when clicking on a gallery item
    galleryItems.forEach((item, index) => {
        item.addEventListener('click', () => {
            const imgElement = item.querySelector('img');
            const titleElement = item.querySelector('h3');
            const descriptionElement = item.querySelector('p');
            const categoryElement = item.querySelector('.text-white.text-sm');
            const categoryDotStyle = item.querySelector('.w-2.h-2').getAttribute('style');

            // Get data from the clicked item
            // Get the original image URL (highest resolution) from srcset if available
            const srcset = imgElement.getAttribute('srcset');
            let imgSrc;

            if (srcset) {
                // Extract the highest resolution image from srcset
                const srcsetEntries = srcset.split(',').map(entry => entry.trim());
                const highestResEntry = srcsetEntries[0]; // First entry is usually the highest resolution
                imgSrc = highestResEntry.split(' ')[0]; // Get just the URL part
            } else {
                imgSrc = imgElement.getAttribute('src');
            }

            const title = titleElement.textContent;
            const description = descriptionElement.textContent;
            const category = categoryElement.textContent;

            // Set current index for navigation
            currentIndex = visibleItems.indexOf(item);

            // Prepare image loading
            const img = new Image();

            // Show loading state if needed
            popupImage.style.opacity = '0';

            // When image is loaded, update popup
            img.onload = function () {
                // Populate the popup with data
                popupImage.setAttribute('src', imgSrc);
                imageTitle.textContent = title;
                imageDescription.textContent = description;
                categoryDot.setAttribute('style', categoryDotStyle);
                categoryName.textContent = category;

                // Show the image
                popupImage.style.opacity = '1';
            };

            // Start loading the image
            img.src = imgSrc;

            // Show the popup immediately (image will fade in when loaded)
            popup.classList.remove('opacity-0', 'pointer-events-none');
            document.body.classList.add('overflow-hidden'); // Prevent scrolling
        });
    });

    // Close popup
    if (closeBtn) {
        closeBtn.addEventListener('click', closePopup);
        popup.addEventListener('click', (e) => {
            if (e.target === popup) closePopup();
        });

        // Close on Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closePopup();
            if (e.key === 'ArrowLeft') navigateImage(-1);
            if (e.key === 'ArrowRight') navigateImage(1);
        });
    }

    function closePopup() {
        popup.classList.add('opacity-0', 'pointer-events-none');
        document.body.classList.remove('overflow-hidden');
    }

    // Navigate between images
    if (prevBtn) {
        prevBtn.addEventListener('click', () => navigateImage(-1));
        nextBtn.addEventListener('click', () => navigateImage(1));
    }

    function navigateImage(direction) {
        currentIndex = (currentIndex + direction + visibleItems.length) % visibleItems.length;
        const newItem = visibleItems[currentIndex];

        // Get data from the new item
        const imgElement = newItem.querySelector('img');
        const titleElement = newItem.querySelector('h3');
        const descriptionElement = newItem.querySelector('p');
        const categoryElement = newItem.querySelector('.text-white.text-sm');
        const categoryDotStyle = newItem.querySelector('.w-2.h-2').getAttribute('style');

        // Create a transition effect
        popupImage.style.opacity = '0';

        // Get the highest resolution image from srcset if available
        const srcset = imgElement.getAttribute('srcset');
        let imgSrc;

        if (srcset) {
            // Extract the highest resolution image from srcset
            const srcsetEntries = srcset.split(',').map(entry => entry.trim());
            const highestResEntry = srcsetEntries[0]; // First entry is usually the highest resolution
            imgSrc = highestResEntry.split(' ')[0]; // Get just the URL part
        } else {
            imgSrc = imgElement.getAttribute('src');
        }

        // Preload the image
        const img = new Image();
        img.onload = function () {
            // Update popup content
            popupImage.setAttribute('src', imgSrc);
            imageTitle.textContent = titleElement.textContent;
            imageDescription.textContent = descriptionElement.textContent;
            categoryDot.setAttribute('style', categoryDotStyle);
            categoryName.textContent = categoryElement.textContent;

            // Show the image again
            popupImage.style.opacity = '1';
        };

        // Start loading the image
        img.src = imgSrc;

        // If image takes too long to load, update the content anyway after a timeout
        setTimeout(() => {
            if (popupImage.style.opacity === '0') {
                popupImage.setAttribute('src', imgSrc);
                imageTitle.textContent = titleElement.textContent;
                imageDescription.textContent = descriptionElement.textContent;
                categoryDot.setAttribute('style', categoryDotStyle);
                categoryName.textContent = categoryElement.textContent;
                popupImage.style.opacity = '1';
            }
        }, 300);
    }
});
