/**
 * Main JavaScript - Amir Ahmed Theme
 *
 * @package Amir_Ahmed
 */

(function($) {
    'use strict';

    // DOM Ready
    $(document).ready(function() {
        initMobileMenu();
        initStickyHeader();
        initScrollAnimations();
        initBackToTop();
        initScrollProgress();
        initPortfolioFilter();
        initSmoothScroll();
    });

    // Window Load
    $(window).on('load', function() {
        hidePageLoader();
    });

    /**
     * Mobile Menu Toggle
     */
    function initMobileMenu() {
        const $menuToggle = $('#menu-toggle');
        const $navigation = $('#site-navigation');

        $menuToggle.on('click', function() {
            $(this).toggleClass('active');
            $navigation.toggleClass('active');
            $('body').toggleClass('menu-open');
        });

        // Close menu on link click
        $navigation.find('a').on('click', function() {
            $menuToggle.removeClass('active');
            $navigation.removeClass('active');
            $('body').removeClass('menu-open');
        });

        // Close menu on outside click
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.main-navigation, .menu-toggle').length) {
                $menuToggle.removeClass('active');
                $navigation.removeClass('active');
                $('body').removeClass('menu-open');
            }
        });
    }

    /**
     * Sticky Header on Scroll
     */
    function initStickyHeader() {
        const $header = $('.site-header');
        const scrollThreshold = 100;

        $(window).on('scroll', function() {
            if ($(this).scrollTop() > scrollThreshold) {
                $header.addClass('scrolled');
            } else {
                if (!$('body').hasClass('single') && !$('body').hasClass('page')) {
                    $header.removeClass('scrolled');
                }
            }
        });

        // Initial check
        if ($(window).scrollTop() > scrollThreshold) {
            $header.addClass('scrolled');
        }
    }

    /**
     * Scroll Animations - Fade In Elements
     */
    function initScrollAnimations() {
        const $animateElements = $('.animate-fadeInUp, .animate-fadeIn');

        // Initially hide elements
        $animateElements.css({
            opacity: '0',
            transform: 'translateY(30px)'
        });

        // Intersection Observer for animations
        if ('IntersectionObserver' in window) {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const $el = $(entry.target);
                        const delay = $el.data('delay') || 0;

                        setTimeout(() => {
                            $el.css({
                                opacity: '1',
                                transform: 'translateY(0)',
                                transition: 'all 0.8s cubic-bezier(0.4, 0, 0.2, 1)'
                            });
                        }, delay);

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

            $animateElements.each(function() {
                observer.observe(this);
            });
        } else {
            // Fallback for older browsers
            $animateElements.css({
                opacity: '1',
                transform: 'translateY(0)'
            });
        }
    }

    /**
     * Back to Top Button
     */
    function initBackToTop() {
        // Create button if not exists
        if (!$('.back-to-top').length) {
            $('body').append('<button class="back-to-top" aria-label="Back to top"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="18 15 12 9 6 15"></polyline></svg></button>');
        }

        const $backToTop = $('.back-to-top');

        // Show/hide button based on scroll position
        $(window).on('scroll', function() {
            if ($(this).scrollTop() > 500) {
                $backToTop.addClass('visible');
            } else {
                $backToTop.removeClass('visible');
            }
        });

        // Scroll to top on click
        $backToTop.on('click', function() {
            $('html, body').animate({
                scrollTop: 0
            }, 800);
        });
    }

    /**
     * Scroll Progress Bar
     */
    function initScrollProgress() {
        // Create progress bar if not exists
        if (!$('.scroll-progress').length) {
            $('body').prepend('<div class="scroll-progress"></div>');
        }

        const $progressBar = $('.scroll-progress');

        $(window).on('scroll', function() {
            const scrollTop = $(this).scrollTop();
            const docHeight = $(document).height() - $(window).height();
            const scrollPercent = (scrollTop / docHeight) * 100;

            $progressBar.css('width', scrollPercent + '%');
        });
    }

    /**
     * Portfolio Filter
     */
    function initPortfolioFilter() {
        const $filterBtns = $('.filter-btn');
        const $portfolioItems = $('.portfolio-item');

        $filterBtns.on('click', function() {
            const filter = $(this).data('filter');

            // Update active button
            $filterBtns.removeClass('active');
            $(this).addClass('active');

            // Filter items
            if (filter === 'all') {
                $portfolioItems.fadeIn(300);
            } else {
                $portfolioItems.each(function() {
                    const category = $(this).data('category');
                    if (category && category.includes(filter)) {
                        $(this).fadeIn(300);
                    } else {
                        $(this).fadeOut(300);
                    }
                });
            }
        });
    }

    /**
     * Smooth Scroll for Anchor Links
     */
    function initSmoothScroll() {
        $('a[href^="#"]').on('click', function(e) {
            const target = $(this.getAttribute('href'));

            if (target.length) {
                e.preventDefault();
                const headerHeight = $('.site-header').outerHeight();

                $('html, body').animate({
                    scrollTop: target.offset().top - headerHeight - 20
                }, 800);
            }
        });
    }

    /**
     * Hide Page Loader
     */
    function hidePageLoader() {
        const $loader = $('.page-loader');
        if ($loader.length) {
            setTimeout(() => {
                $loader.addClass('loaded');
                setTimeout(() => {
                    $loader.remove();
                }, 500);
            }, 500);
        }
    }

    /**
     * Lazy Load Images
     */
    function initLazyLoad() {
        if ('IntersectionObserver' in window) {
            const lazyImages = document.querySelectorAll('img[data-src]');

            const imageObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        imageObserver.unobserve(img);
                    }
                });
            });

            lazyImages.forEach(img => imageObserver.observe(img));
        }
    }

    /**
     * Parallax Effect for Hero Section
     */
    function initParallax() {
        const $hero = $('.hero-section');

        if ($hero.length && $(window).width() > 768) {
            $(window).on('scroll', function() {
                const scrolled = $(this).scrollTop();
                const parallaxSpeed = 0.3;

                $hero.find('.hero-shapes').css({
                    transform: 'translateY(' + (scrolled * parallaxSpeed) + 'px)'
                });
            });
        }
    }

    /**
     * Counter Animation
     */
    function initCounterAnimation() {
        const $counters = $('.stat-item h3');

        if ('IntersectionObserver' in window) {
            const counterObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const $counter = $(entry.target);
                        const target = parseInt($counter.text());

                        if (!isNaN(target)) {
                            $({ count: 0 }).animate({ count: target }, {
                                duration: 2000,
                                easing: 'swing',
                                step: function() {
                                    $counter.text(Math.ceil(this.count) + '+');
                                },
                                complete: function() {
                                    $counter.text(target + '+');
                                }
                            });
                        }

                        counterObserver.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.5 });

            $counters.each(function() {
                counterObserver.observe(this);
            });
        }
    }

    /**
     * Form Validation Enhancement
     */
    function initFormValidation() {
        const $form = $('#contact-form');

        $form.find('input, textarea').on('blur', function() {
            const $field = $(this);
            const value = $field.val().trim();

            if ($field.prop('required') && !value) {
                $field.addClass('error');
            } else {
                $field.removeClass('error');
            }

            // Email validation
            if ($field.attr('type') === 'email' && value) {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(value)) {
                    $field.addClass('error');
                }
            }
        });
    }

    /**
     * Keyboard Navigation Support
     */
    function initKeyboardNav() {
        // Add focus styles
        $('a, button, input, textarea, select').on('focus', function() {
            $(this).addClass('keyboard-focus');
        }).on('blur', function() {
            $(this).removeClass('keyboard-focus');
        });

        // Escape key closes mobile menu
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('#menu-toggle').removeClass('active');
                $('#site-navigation').removeClass('active');
                $('body').removeClass('menu-open');
            }
        });
    }

    // Initialize additional features
    $(document).ready(function() {
        initLazyLoad();
        initParallax();
        initCounterAnimation();
        initFormValidation();
        initKeyboardNav();
    });

})(jQuery);
