/* Header Overlap Mode - Scroll Behavior */
/* Adds 'scrolled' class to navbar when page is scrolled */
(function() {
    'use strict';
    
    function pawsAndCareHandleHeaderScroll() {
        // Only run if header-overlap mode is enabled
        if (!document.body.classList.contains('header-overlap')) {
            return;
        }
        
        const navbar = document.querySelector('.navbar');
        if (!navbar) return;
        
        const scrollThreshold = 50; // Pixels to scroll before header becomes solid
        
        function updateNavbar() {
            if (window.scrollY > scrollThreshold) {
                navbar.classList.add('scrolled');
            } else {
                navbar.classList.remove('scrolled');
            }
        }
        
        // Listen for scroll events with passive flag for performance
        window.addEventListener('scroll', updateNavbar, { passive: true });
        
        // Check initial state
        updateNavbar();
    }
    
    // Run when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', pawsAndCareHandleHeaderScroll);
    } else {
        pawsAndCareHandleHeaderScroll();
    }
})();

/* Slider JS - Reads settings from data attributes set by customizer */
document.addEventListener('DOMContentLoaded', function() {
    const sliderCarousel = document.querySelector('#carouselSlider');
    if (sliderCarousel && typeof bootstrap !== 'undefined') {
        // Get settings from data attributes (set by PHP from customizer)
        const interval = sliderCarousel.getAttribute('data-bs-interval');
        const ride = sliderCarousel.getAttribute('data-bs-ride');
        const touch = sliderCarousel.getAttribute('data-bs-touch');
        const mouseDrag = sliderCarousel.getAttribute('data-mouse-drag');
        const touchEnabled = touch === 'true';
        const mouseDragEnabled = mouseDrag === 'true';

        // Dispose any existing carousel instance first
        const existingCarousel = bootstrap.Carousel.getInstance(sliderCarousel);
        if (existingCarousel) {
            existingCarousel.dispose();
        }

        // Initialize carousel with customizer settings
        const carousel = new bootstrap.Carousel(sliderCarousel, {
            interval: (ride === 'false' || interval === 'false') ? false : (parseInt(interval) || 5000),
            ride: ride === 'false' ? false : 'carousel',
            touch: touchEnabled
        });

        // Add mouse drag support for desktop (if mouse drag is enabled)
        if (mouseDragEnabled) {
            let isDragging = false;
            let startX = 0;
            const threshold = 50; // Minimum drag distance to trigger slide

            // Mouse down - start tracking
            sliderCarousel.addEventListener('mousedown', function(e) {
                // Ignore clicks on controls and buttons
                if (e.target.closest('.carousel-control-prev, .carousel-control-next, .carousel-indicators, .btn, a')) {
                    return;
                }
                isDragging = true;
                startX = e.clientX;
                sliderCarousel.style.cursor = 'grabbing';
                e.preventDefault(); // Prevent text selection

                // Pause carousel while dragging
                carousel.pause();
            });

            // Mouse move - track position (on document to catch all movements)
            document.addEventListener('mousemove', function(e) {
                if (!isDragging) return;
                e.preventDefault();
            });

            // Mouse up - determine slide direction (on document to catch release anywhere)
            document.addEventListener('mouseup', function(e) {
                if (!isDragging) return;

                const endX = e.clientX;
                const diffX = startX - endX;

                isDragging = false;
                sliderCarousel.style.cursor = 'grab';

                if (Math.abs(diffX) > threshold) {
                    if (diffX > 0) {
                        // Dragged left - go to next slide
                        carousel.next();
                    } else {
                        // Dragged right - go to previous slide
                        carousel.prev();
                    }
                }

                // Resume carousel if autoplay is enabled
                if (ride !== 'false') {
                    carousel.cycle();
                }
            });

            // Set initial cursor style
            sliderCarousel.style.cursor = 'grab';

            // Prevent default drag behavior on images
            sliderCarousel.querySelectorAll('img').forEach(function(img) {
                img.addEventListener('dragstart', function(e) {
                    e.preventDefault();
                });
            });
        }
    }
});


document.addEventListener('DOMContentLoaded', function() {

    // Scroll to Top Implementation (Vanilla JS)
    let scrollButton = document.getElementById('scrollToTop');

    // If the button is missing in the HTML, create it dynamically
    if (!scrollButton) {
        scrollButton = document.createElement('button');
        scrollButton.id = 'scrollToTop';
        scrollButton.className = 'scroll-to-top';
        scrollButton.setAttribute('aria-label', 'Scroll to top');
        scrollButton.innerHTML = '<i class="fa-solid fa-arrow-up"></i>';
        document.body.appendChild(scrollButton);
    }

    // Show/hide button on scroll and on initial load
    function pawsAndCareToggleScrollButton() {
        if (window.pageYOffset > 100) {
            scrollButton.classList.add('show');
        } else {
            scrollButton.classList.remove('show');
        }
    }

    window.addEventListener('scroll', pawsAndCareToggleScrollButton, { passive: true });
    pawsAndCareToggleScrollButton(); // initial state

    // Smooth scroll to top on click with custom easing
    scrollButton.addEventListener('click', function(e) {
        e.preventDefault();

        // Custom smooth scroll with easing
        const startPosition = window.pageYOffset;
        const startTime = performance.now();
        const duration = 1200; // 1.2 seconds for smooth scroll

        function easeInOutCubic(t) {
            return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
        }

        function scrollAnimation(currentTime) {
            const timeElapsed = currentTime - startTime;
            const progress = Math.min(timeElapsed / duration, 1);
            const ease = easeInOutCubic(progress);

            window.scrollTo(0, startPosition * (1 - ease));

            if (progress < 1) {
                requestAnimationFrame(scrollAnimation);
            }
        }

        requestAnimationFrame(scrollAnimation);
    });

    // Enhanced form validation
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const requiredFields = form.querySelectorAll('[required]');
            let isValid = true;

            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('is-invalid');

                    // Remove invalid class after user starts typing
                    field.addEventListener('input', function() {
                        this.classList.remove('is-invalid');
                    }, { once: true });
                }
            });

            if (!isValid) {
                e.preventDefault();
                // Show error message
                const errorMsg = document.createElement('div');
                errorMsg.className = 'alert alert-danger mt-3';
                errorMsg.textContent = 'Please fill in all required fields.';

                // Remove existing error messages
                const existingError = form.querySelector('.alert-danger');
                if (existingError) {
                    existingError.remove();
                }

                form.appendChild(errorMsg);

                // Remove error message after 5 seconds
                setTimeout(() => {
                    errorMsg.remove();
                }, 5000);
            }
        });
    });

    // Smooth scrolling for anchor links
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    anchorLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href !== '#' && href !== '#!') {
                const target = document.querySelector(href);
                if (target) {
                    e.preventDefault();
                    target.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            }
        });
    });

    // Add loading state to submit buttons (exclude search forms – they navigate away)
    const submitButtons = document.querySelectorAll('button[type="submit"]');
    submitButtons.forEach(button => {
        // Skip buttons inside search forms – they trigger page navigation
        if (button.closest('.search-form, form[role="search"]')) {
            return;
        }

        button.addEventListener('click', function() {
            const btn = this;
            const originalText = btn.innerHTML;

            // Delay disabling so the form submit event fires first
            setTimeout(function() {
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Loading...';
                btn.disabled = true;
            }, 0);

            // Re-enable after 3 seconds (fallback)
            setTimeout(function() {
                btn.innerHTML = originalText;
                btn.disabled = false;
            }, 3000);
        });
    });

    // Mobile menu improvements
    const navbarCollapse = document.querySelector('.navbar-collapse');
    if (navbarCollapse) {

        // Close mobile menu when clicking on a link (but not dropdown toggles or items)
        navbarCollapse.addEventListener('click', (e) => {
            // Only close menu for regular nav-links, not dropdown toggles or dropdown items
            if (e.target.classList.contains('nav-link') &&
                !e.target.classList.contains('dropdown-toggle') &&
                !e.target.classList.contains('dropdown-item') &&
                window.innerWidth < 992) {
                const bsCollapse = bootstrap.Collapse.getInstance(navbarCollapse);
                if (bsCollapse) {
                    bsCollapse.hide();
                }
            }

            // Close menu when clicking on dropdown items (actual navigation)
            if (e.target.classList.contains('dropdown-item') && window.innerWidth < 992) {
                const bsCollapse = bootstrap.Collapse.getInstance(navbarCollapse);
                if (bsCollapse) {
                    bsCollapse.hide();
                }
            }
        });

        // Handle dropdown toggle icon behavior (inside the nav-link)
        const dropdownToggleIcons = navbarCollapse.querySelectorAll('.navbar-nav > .nav-item > .nav-link .dropdown-toggle-icon');
        dropdownToggleIcons.forEach(toggleIcon => {
            // Handle click on the dropdown toggle icon
            toggleIcon.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                // Find the dropdown menu (sibling of the parent <a> tag)
                const navLink = toggleIcon.closest('.nav-link');
                const dropdownMenu = navLink ? navLink.nextElementSibling : null;
                if (!dropdownMenu || !dropdownMenu.classList.contains('dropdown-menu')) return;
                
                const isOpen = dropdownMenu.classList.contains('show');

                // Close all other dropdowns first
                navbarCollapse.querySelectorAll('.dropdown-menu.show').forEach(menu => {
                    if (menu !== dropdownMenu) {
                        menu.classList.remove('show');
                        const menuLink = menu.previousElementSibling;
                        const icon = menuLink ? menuLink.querySelector('.dropdown-toggle-icon') : null;
                        if (icon) {
                            icon.setAttribute('aria-expanded', 'false');
                        }
                    }
                });

                // Toggle current dropdown
                if (isOpen) {
                    dropdownMenu.classList.remove('show');
                    toggleIcon.setAttribute('aria-expanded', 'false');
                } else {
                    dropdownMenu.classList.add('show');
                    toggleIcon.setAttribute('aria-expanded', 'true');
                }
            });

            // Handle keyboard navigation (Enter and Space toggle dropdown)
            toggleIcon.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleIcon.click();
                }
            });
        });

        // Close dropdown when focus leaves the entire dropdown area (accessibility)
        const dropdownNavItems = navbarCollapse.querySelectorAll('.navbar-nav > .nav-item.dropdown');
        dropdownNavItems.forEach(navItem => {
            navItem.addEventListener('focusout', (e) => {
                // Use setTimeout to check if focus moved outside after the focusout event
                setTimeout(() => {
                    // Check if focus is still within this nav-item
                    if (!navItem.contains(document.activeElement)) {
                        // Focus has left the dropdown area, close it
                        const dropdownMenu = navItem.querySelector('.dropdown-menu');
                        const toggleIcon = navItem.querySelector('.dropdown-toggle-icon');
                        if (dropdownMenu && dropdownMenu.classList.contains('show')) {
                            dropdownMenu.classList.remove('show');
                            if (toggleIcon) {
                                toggleIcon.setAttribute('aria-expanded', 'false');
                            }
                        }
                    }
                }, 0);
            });
        });
    }

    // Touch device detection
    if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
        document.body.classList.add('touch-device');
    }

    // Set active class for current page in navigation
    function pawsAndCareSetActiveNavigation() {
        const currentPage = window.location.pathname.split('/').pop() || 'index.html';

        // Set active class for main nav links
        const navLinks = document.querySelectorAll('.navbar-nav .nav-link:not(.dropdown-toggle)');
        navLinks.forEach(link => {
            const href = link.getAttribute('href');
            if (href === currentPage || (currentPage === '' && href === 'index.html')) {
                link.classList.add('active');
            }
        });

        // Set active class for dropdown items
        const dropdownItems = document.querySelectorAll('.dropdown-item');
        dropdownItems.forEach(item => {
            const href = item.getAttribute('href');
            if (href === currentPage) {
                item.classList.add('active');
                // Also highlight the parent dropdown toggle
                const parentDropdown = item.closest('.dropdown');
                if (parentDropdown) {
                    const dropdownToggle = parentDropdown.querySelector('.dropdown-toggle');
                    if (dropdownToggle) {
                        dropdownToggle.classList.add('active');
                    }
                }
            }
        });
    }

    // Initialize active navigation
    pawsAndCareSetActiveNavigation();


    // Enhanced FAQ Accordion Animation
    const accordionButtons = document.querySelectorAll('.accordion-button');
    accordionButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Add smooth animation class
            const target = document.querySelector(this.getAttribute('data-bs-target'));
            if (target) {
                target.style.transition = 'all 0.4s ease-in-out';
            }
        });
    });
});

/* Smart Menu Positioning & Nested Keyboard Interaction */
document.addEventListener('DOMContentLoaded', function() {
    
    // Helper: Adjust position if off-screen (Desktop Only)
    function pawsAndCareAdjustSubmenuPosition(submenu) {
        if (window.innerWidth < 992 || !submenu) return;
        
        submenu.classList.remove('submenu-reverse');
        const rect = submenu.getBoundingClientRect();
        const viewportWidth = window.innerWidth || document.documentElement.clientWidth;

        if (rect.right > viewportWidth - 10) {
            submenu.classList.add('submenu-reverse');
        }
    }

    // Mouse Interaction (Desktop Hover)
    if (window.innerWidth >= 992) {
        const nestedDropdowns = document.querySelectorAll('.dropdown-menu .dropend');
        nestedDropdowns.forEach(function(dropend) {
            dropend.addEventListener('mouseenter', function() {
                pawsAndCareAdjustSubmenuPosition(this.querySelector('.dropdown-menu'));
            });
        });
    }

    // Fix Nested Dropdown Keyboard/Click Interaction
    const nestedToggles = document.querySelectorAll('.dropdown-menu .dropdown-toggle-icon');
    
    nestedToggles.forEach(function(toggleIcon) {
        toggleIcon.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Find the dropdown menu (sibling of the parent link)
            const dropdownItem = this.closest('.dropdown-item');
            const submenu = dropdownItem ? dropdownItem.nextElementSibling : null;
            if (submenu && submenu.classList.contains('dropdown-menu')) {
                // Close only sibling submenus (not ancestors)
                const parentLi = this.closest('li');
                const parentMenu = parentLi ? parentLi.parentElement : null;
                if (parentMenu && parentMenu.classList.contains('dropdown-menu')) {
                    // Find sibling <li> elements and close their submenus
                    parentMenu.querySelectorAll(':scope > li > .dropdown-menu.show').forEach(el => {
                        if (el !== submenu) {
                            el.classList.remove('show');
                            // Also remove expanded state from the toggle icon
                            const siblingLink = el.previousElementSibling;
                            const siblingIcon = siblingLink ? siblingLink.querySelector('.dropdown-toggle-icon') : null;
                            if (siblingIcon) {
                                siblingIcon.setAttribute('aria-expanded', 'false');
                            }
                        }
                    });
                }

                // Toggle current
                const isOpen = submenu.classList.contains('show');
                if (isOpen) {
                    submenu.classList.remove('show');
                    this.setAttribute('aria-expanded', 'false');
                } else {
                    submenu.classList.add('show');
                    this.setAttribute('aria-expanded', 'true');
                    pawsAndCareAdjustSubmenuPosition(submenu);
                }
            }
        });

        // Handle keyboard navigation for nested dropdowns
        toggleIcon.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                e.stopPropagation();
                this.click();
            }
        });
    });
});

