/**
 * Klippteam Näl - Main JavaScript
 * 
 * @package Klippteam_Nal
 */
(function () {
    'use strict';
    // DOM Elements
    const header = document.querySelector('.site-header');
    const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
    const mobileNav = document.querySelector('.mobile-nav');
    const mobileOverlay = document.querySelector('.mobile-overlay');
    const bookingForm = document.getElementById('booking-form');
    // Declare klippteamAjax variable
    const klippteamAjax = window.klippteamAjax || {
        ajaxurl: 'your_ajax_url_here',
        nonce: 'your_nonce_here'
    };
    /**
     * Header scroll effect
     */
    function handleHeaderScroll() {
        if (!header) return;
        const scrolled = window.scrollY > 30;
        header.classList.toggle('scrolled', scrolled);
    }
    /**
     * Mobile menu toggle
     */
    function toggleMobileMenu() {
        if (!mobileMenuToggle || !mobileNav || !mobileOverlay) return;
        const isOpen = mobileNav.classList.contains('active');
        mobileMenuToggle.classList.toggle('active', !isOpen);
        mobileNav.classList.toggle('active', !isOpen);
        mobileOverlay.classList.toggle('active', !isOpen);
        document.body.style.overflow = isOpen ? '' : 'hidden';
        // Update ARIA
        mobileMenuToggle.setAttribute('aria-expanded', !isOpen);
    }
    /**
     * Close mobile menu
     */
    function closeMobileMenu() {
        if (!mobileMenuToggle || !mobileNav || !mobileOverlay) return;
        mobileMenuToggle.classList.remove('active');
        mobileNav.classList.remove('active');
        mobileOverlay.classList.remove('active');
        document.body.style.overflow = '';
        mobileMenuToggle.setAttribute('aria-expanded', 'false');
    }
    /**
     * Smooth scroll for anchor links
     */
    function handleSmoothScroll(e) {
        const href = e.currentTarget.getAttribute('href');
        if (!href || !href.startsWith('#')) return;
        const target = document.querySelector(href);
        if (!target) return;
        e.preventDefault();
        closeMobileMenu();
        const headerHeight = header ? header.offsetHeight : 0;
        const targetPosition = target.getBoundingClientRect().top + window.scrollY - (window.innerWidth < 1024 ? 60 : 80);
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
        // Update URL without scrolling
        history.pushState(null, '', href);
    }
    /**
     * Reveal on Scroll using IntersectionObserver
     */
    function initScrollReveal() {
        const revealElements = document.querySelectorAll('.reveal');
        const revealObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('active');
                    revealObserver.unobserve(entry.target);
                }
            });
        }, {
            root: null,
            threshold: 0.15,
            rootMargin: '0px 0px -50px 0px'
        });
        revealElements.forEach(el => revealObserver.observe(el));
    }
    /**
     * Handle form submission
     */
    function handleFormSubmit(e) {
        e.preventDefault();
        const form = e.target;
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.textContent;
        // Disable button and show loading state
        submitBtn.disabled = true;
        submitBtn.textContent = 'Skickar...';
        // Gather form data
        const formData = new FormData(form);
        formData.append('action', 'klippteam_contact');
        formData.append('nonce', klippteamAjax.nonce);
        // Send AJAX request
        fetch(klippteamAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Show success message
                    showNotification(data.data.message, 'success');
                    form.reset();
                } else {
                    // Show error message
                    showNotification(data.data.message || 'Ett fel uppstod. Försök igen.', 'error');
                }
            })
            .catch(() => {
                showNotification('Ett fel uppstod. Försök igen.', 'error');
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
            });
    }
    /**
     * Show notification
     */
    function showNotification(message, type = 'success') {
        const existingNotification = document.querySelector('.notification');
        if (existingNotification) existingNotification.remove();
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <span>${message}</span>
            <button type="button" class="notification-close" aria-label="Stäng">&times;</button>
        `;
        Object.assign(notification.style, {
            position: 'fixed',
            bottom: '2rem',
            right: '2rem',
            padding: '1rem 1.5rem',
            borderRadius: '0.5rem',
            backgroundColor: type === 'success' ? '#10b981' : '#ef4444',
            color: '#fff',
            display: 'flex',
            alignItems: 'center',
            gap: '1rem',
            boxShadow: '0 10px 25px rgba(0, 0, 0, 0.3)',
            zIndex: '9999',
            animation: 'slideIn 0.3s ease'
        });
        const closeBtn = notification.querySelector('.notification-close');
        Object.assign(closeBtn.style, {
            background: 'none',
            border: 'none',
            color: '#fff',
            fontSize: '1.5rem',
            cursor: 'pointer',
            lineHeight: '1'
        });
        document.body.appendChild(notification);
        closeBtn.addEventListener('click', () => notification.remove());
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => notification.remove(), 300);
            }
        }, 5000);
    }
    /**
     * Initialize
     */
    function init() {
        // Add animation keyframes for notifications
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn { from { opacity: 0; transform: translateX(100%); } to { opacity: 1; transform: translateX(0); } }
            @keyframes slideOut { from { opacity: 1; transform: translateX(0); } to { opacity: 0; transform: translateX(100%); } }
        `;
        document.head.appendChild(style);
        // Events
        window.addEventListener('scroll', handleHeaderScroll, { passive: true });
        handleHeaderScroll();
        if (mobileMenuToggle) mobileMenuToggle.addEventListener('click', toggleMobileMenu);
        if (mobileOverlay) mobileOverlay.addEventListener('click', closeMobileMenu);
        document.querySelectorAll('a[href^="#"]').forEach(link => {
            link.addEventListener('click', handleSmoothScroll);
        });
        if (mobileNav) {
            mobileNav.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', closeMobileMenu);
            });
        }
        if (bookingForm) bookingForm.addEventListener('submit', handleFormSubmit);
        window.addEventListener('resize', () => {
            if (window.innerWidth >= 1024) closeMobileMenu();
        });
        // Initialize animations
        initScrollReveal();
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
