/**
 * SparkleWash Laundry - Frontend JavaScript
 */

// Initialize all components
function initializeComponents() {
    initThemeToggle();
    initHeader();
    initMobileMenu();
    initScrollAnimations();
    initFaqAccordion();
    initScrollToTop();
    initCounterAnimation();
    initTestimonialSlider();
    initSmoothScroll();
}

// Initial load
document.addEventListener('DOMContentLoaded', initializeComponents);

// Re-initialize after Livewire initializes
document.addEventListener('livewire:init', () => {
    // Wait a tick to ensure Livewire components are rendered
    setTimeout(initializeComponents, 0);
});

// Re-initialize on Livewire navigation (for wire:navigate)
document.addEventListener('livewire:navigated', initializeComponents);

/**
 * Progress Loading Bar for Livewire Navigation
 */
function initProgressBar() {
    const progressBar = document.getElementById('progress-bar');

    if (!progressBar) return;

    let progressInterval;

    // Show progress bar when navigation starts
    document.addEventListener('livewire:navigating', () => {
        progressBar.classList.add('active');
        progressBar.style.width = '0%';

        // Animate progress from 0% to 90%
        let progress = 0;
        progressInterval = setInterval(() => {
            if (progress < 90) {
                progress += Math.random() * 10;
                if (progress > 90) progress = 90;
                progressBar.style.width = progress + '%';
            }
        }, 200);
    });

    // Complete progress bar when navigation finishes
    document.addEventListener('livewire:navigated', () => {
        clearInterval(progressInterval);

        // Complete to 100%
        progressBar.style.width = '100%';

        // Hide after a short delay
        setTimeout(() => {
            progressBar.classList.remove('active');
            setTimeout(() => {
                progressBar.style.width = '0%';
            }, 300);
        }, 300);
    });
}

// Initialize progress bar
document.addEventListener('DOMContentLoaded', initProgressBar);

/**
 * Theme toggle (light/dark mode)
 * Theme is saved per website slug to allow independent theme preferences
 */
function initThemeToggle() {
    const themeToggle = document.getElementById('theme-toggle');
    const themeToggleMobile = document.getElementById('theme-toggle-mobile');
    const body = document.body;

    // Get website slug from meta tag or data attribute (set by backend)
    const websiteSlug = document.querySelector('meta[name="website-slug"]')?.content ||
                       body.dataset.websiteSlug ||
                       'default';

    // Build slug-based theme key (e.g., "theme_mywebsite" or "theme_default")
    const themeKey = `theme_${websiteSlug}`;

    // Helper function to set cookie
    function setCookie(name, value, days) {
        const expires = new Date();
        expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000);
        document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
    }

    // Helper function to get cookie value
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }

    function setTheme(theme) {
        // Add transition class for smooth change
        body.classList.add('theme-transition');

        if (theme === 'dark') {
            body.classList.add('dark');
            body.dataset.theme = 'dark';
        } else {
            body.classList.remove('dark');
            body.dataset.theme = 'light';
        }

        // Remove transition class after animation completes
        setTimeout(() => {
            body.classList.remove('theme-transition');
        }, 300);
    }

    function toggleTheme() {
        const currentTheme = body.classList.contains('dark') ? 'dark' : 'light';
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        setTheme(newTheme);
        // Save theme with slug-based key to localStorage
        localStorage.setItem(themeKey, newTheme);
        // Also save to cookie so backend can read it (expires in 1 year)
        setCookie(themeKey, newTheme, 365);
    }

    // Priority order for theme detection:
    // 1. Backend-set theme (from cookie, already applied to body)
    // 2. localStorage (slug-specific)
    // 3. Default to 'light'
    const initialTheme = body.dataset.theme || 'light';
    const cookieTheme = getCookie(themeKey);
    const localStorageTheme = localStorage.getItem(themeKey);

    // Determine which theme to use
    let themeToUse = initialTheme;

    // If cookie exists and matches initialTheme, trust the backend
    // If not, prefer localStorage (user might have changed it)
    if (localStorageTheme && localStorageTheme !== initialTheme) {
        themeToUse = localStorageTheme;
        // Sync to cookie
        setCookie(themeKey, localStorageTheme, 365);
    } else if (!cookieTheme && localStorageTheme) {
        // Cookie doesn't exist but localStorage does
        themeToUse = localStorageTheme;
        setCookie(themeKey, localStorageTheme, 365);
    } else if (!localStorageTheme) {
        // No localStorage, save current theme
        localStorage.setItem(themeKey, initialTheme);
    }

    // Apply the theme
    setTheme(themeToUse);

    // Toggle theme on click
    if (themeToggle) {
        themeToggle.addEventListener('click', toggleTheme);
    }

    if (themeToggleMobile) {
        themeToggleMobile.addEventListener('click', toggleTheme);
    }
}

/**
 * Header scroll effect
 */
function initHeader() {
    const header = document.getElementById('header');
    if (!header) return;

    let lastScroll = 0;

    window.addEventListener('scroll', () => {
        const currentScroll = window.pageYOffset;

        if (currentScroll > 50) {
            header.classList.add('header-scrolled');
        } else {
            header.classList.remove('header-scrolled');
        }

        lastScroll = currentScroll;
    });
}

/**
 * Mobile menu toggle
 */
function initMobileMenu() {
    const menuBtn = document.getElementById('mobile-menu-btn');
    const closeBtn = document.getElementById('mobile-menu-close');
    const mobileMenu = document.getElementById('mobile-menu');
    const menuLinks = document.querySelectorAll('.mobile-menu-link');

    if (!menuBtn || !mobileMenu) return;

    menuBtn.addEventListener('click', () => {
        mobileMenu.classList.add('active');
        document.body.style.overflow = 'hidden';
    });

    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            mobileMenu.classList.remove('active');
            document.body.style.overflow = '';
        });
    }

    menuLinks.forEach(link => {
        link.addEventListener('click', () => {
            mobileMenu.classList.remove('active');
            document.body.style.overflow = '';
        });
    });
}

/**
 * Scroll animations using Intersection Observer
 */
function initScrollAnimations() {
    const elements = document.querySelectorAll('.scroll-animate');

    if (!elements.length) return;

    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                // Add staggered delay based on element index within its parent
                const siblings = entry.target.parentElement.querySelectorAll('.scroll-animate');
                const siblingIndex = Array.from(siblings).indexOf(entry.target);

                setTimeout(() => {
                    entry.target.classList.add('animate');
                }, siblingIndex * 100);

                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    elements.forEach(el => observer.observe(el));
}

/**
 * FAQ Accordion
 */
function initFaqAccordion() {
    const faqItems = document.querySelectorAll('.faq-item');

    faqItems.forEach(item => {
        const question = item.querySelector('.faq-question');

        if (!question) return;

        question.addEventListener('click', () => {
            const isActive = item.classList.contains('active');

            // Close all other items
            faqItems.forEach(otherItem => {
                if (otherItem !== item) {
                    otherItem.classList.remove('active');
                }
            });

            // Toggle current item
            item.classList.toggle('active', !isActive);
        });
    });
}

/**
 * Scroll to top button
 */
function initScrollToTop() {
    const scrollTopBtn = document.getElementById('scroll-top');

    if (!scrollTopBtn) return;

    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 500) {
            scrollTopBtn.classList.add('visible');
        } else {
            scrollTopBtn.classList.remove('visible');
        }
    });

    scrollTopBtn.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

/**
 * Counter animation for stats
 */
function initCounterAnimation() {
    const counters = document.querySelectorAll('[data-counter]');

    if (!counters.length) return;

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                animateCounter(entry.target);
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.5 });

    counters.forEach(counter => observer.observe(counter));
}

function animateCounter(element) {
    const target = element.getAttribute('data-counter');
    const suffix = element.getAttribute('data-suffix') || '';
    const duration = 2000;
    const steps = 60;
    const stepDuration = duration / steps;

    // Parse the target value
    let targetValue = parseFloat(target.replace(/[^0-9.]/g, ''));
    let prefix = target.match(/^[^0-9]*/)[0] || '';

    let current = 0;
    let step = 0;

    const timer = setInterval(() => {
        step++;
        const progress = step / steps;
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        current = Math.floor(targetValue * easeOutQuart);

        if (targetValue >= 1000) {
            element.textContent = prefix + (current / 1000).toFixed(current >= 10000 ? 0 : 1) + 'K' + suffix;
        } else {
            element.textContent = prefix + current + suffix;
        }

        if (step >= steps) {
            element.textContent = target + suffix;
            clearInterval(timer);
        }
    }, stepDuration);
}

/**
 * Testimonial slider
 */
function initTestimonialSlider() {
    const slider = document.getElementById('testimonial-slider');
    const prevBtn = document.getElementById('testimonial-prev');
    const nextBtn = document.getElementById('testimonial-next');
    const dots = document.querySelectorAll('.testimonial-dot');

    if (!slider) return;

    let currentSlide = 0;
    const slides = slider.querySelectorAll('.testimonial-slide');
    const totalSlides = slides.length;
    let autoplayInterval;

    function goToSlide(index) {
        if (index < 0) index = totalSlides - 1;
        if (index >= totalSlides) index = 0;

        currentSlide = index;
        slider.style.transform = `translateX(-${currentSlide * 100}%)`;

        // Update dots
        dots.forEach((dot, i) => {
            dot.classList.toggle('active', i === currentSlide);
        });
    }

    function startAutoplay() {
        autoplayInterval = setInterval(() => {
            goToSlide(currentSlide + 1);
        }, 5000);
    }

    function stopAutoplay() {
        clearInterval(autoplayInterval);
    }

    if (prevBtn) {
        prevBtn.addEventListener('click', () => {
            stopAutoplay();
            goToSlide(currentSlide - 1);
            startAutoplay();
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            stopAutoplay();
            goToSlide(currentSlide + 1);
            startAutoplay();
        });
    }

    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => {
            stopAutoplay();
            goToSlide(index);
            startAutoplay();
        });
    });

    // Touch/swipe support
    let touchStartX = 0;
    let touchEndX = 0;

    slider.addEventListener('touchstart', (e) => {
        touchStartX = e.changedTouches[0].screenX;
        stopAutoplay();
    }, { passive: true });

    slider.addEventListener('touchend', (e) => {
        touchEndX = e.changedTouches[0].screenX;
        handleSwipe();
        startAutoplay();
    }, { passive: true });

    function handleSwipe() {
        const swipeThreshold = 50;
        const diff = touchStartX - touchEndX;

        if (Math.abs(diff) > swipeThreshold) {
            if (diff > 0) {
                goToSlide(currentSlide + 1);
            } else {
                goToSlide(currentSlide - 1);
            }
        }
    }

    // Start autoplay
    startAutoplay();

    // Pause on hover
    slider.parentElement.addEventListener('mouseenter', stopAutoplay);
    slider.parentElement.addEventListener('mouseleave', startAutoplay);
}

/**
 * Smooth scroll for anchor links
 * Handles both same-page scrolling and cross-page navigation with hash
 */
function initSmoothScroll() {
    // Handle navigation links with data-section attribute
    document.querySelectorAll('a[data-section]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const href = this.getAttribute('href');
            const section = this.getAttribute('data-section');
            const targetId = '#' + section;
            const targetElement = document.querySelector(targetId);

            // Check if we're on the homepage (has the target section)
            if (targetElement) {
                // We're on the homepage, do smooth scroll
                e.preventDefault();

                const headerOffset = 80;
                const elementPosition = targetElement.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });

                // Close mobile menu if open
                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu) {
                    mobileMenu.classList.remove('active');
                    document.body.style.overflow = '';
                }
            }
            // If not on homepage, browser will navigate to the URL with hash normally
        });
    });

    // Handle regular anchor links on the same page
    document.querySelectorAll('a[href^="#"]:not([data-section])').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const targetId = this.getAttribute('href');

            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);

            if (targetElement) {
                e.preventDefault();

                const headerOffset = 80;
                const elementPosition = targetElement.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        });
    });

    // Handle hash in URL on page load (for cross-page navigation)
    if (window.location.hash) {
        setTimeout(() => {
            const targetElement = document.querySelector(window.location.hash);
            if (targetElement) {
                const headerOffset = 80;
                const elementPosition = targetElement.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        }, 100); // Small delay to ensure page is fully loaded
    }
}

/**
 * Contact form handling
 */
function initContactForm() {
    const form = document.getElementById('contact-form');

    if (!form) return;

    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        // Show loading state
        submitBtn.innerHTML = '<span class="spinner"></span> Sending...';
        submitBtn.disabled = true;

        // Simulate form submission
        await new Promise(resolve => setTimeout(resolve, 2000));

        // Show success message
        submitBtn.innerHTML = '<svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg> Message Sent!';
        submitBtn.classList.remove('btn-primary');
        submitBtn.classList.add('bg-green-500', 'text-white');

        // Reset after delay
        setTimeout(() => {
            form.reset();
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
            submitBtn.classList.add('btn-primary');
            submitBtn.classList.remove('bg-green-500', 'text-white');
        }, 3000);
    });
}

// Initialize contact form
document.addEventListener('DOMContentLoaded', initContactForm);
