(function ($) {

    // Hamburger Menu Functionality
    document.addEventListener('DOMContentLoaded', function() {
        // Wait for everything to load
        setTimeout(function() {
            initMobileMenu();
        }, 200);
    });

    function initMobileMenu() {
        const hamburgerBtn = document.querySelector('.hamburger-menu-btn');
        const mobileMenuOverlay = document.querySelector('.mobile-menu-overlay');
        const mobileMenuClose = document.querySelector('[data-action="close-menu"]');
        const body = document.body;

        // Check if elements exist
        if (!hamburgerBtn || !mobileMenuOverlay) {
            console.error('Mobile menu elements not found');
            return;
        }

        console.log('Mobile menu initialized successfully');

        // Open mobile menu
        hamburgerBtn.addEventListener('click', function(e) {
            e.preventDefault();
            hamburgerBtn.classList.add('active');
            mobileMenuOverlay.classList.add('active');
            body.style.overflow = 'hidden';
            console.log('Mobile menu opened');
        });

        // Close mobile menu function
        function closeMobileMenu() {
            hamburgerBtn.classList.remove('active');
            mobileMenuOverlay.classList.remove('active');
            body.style.overflow = '';
            console.log('Mobile menu closed');
        }

        // Close button functionality using event delegation
        document.addEventListener('click', function(e) {
            if (e.target.closest('[data-action="close-menu"]')) {
                e.preventDefault();
                e.stopPropagation();
                console.log('Close button clicked');
                closeMobileMenu();
            }
        });

        // Also add touch event for mobile devices
        document.addEventListener('touchstart', function(e) {
            if (e.target.closest('[data-action="close-menu"]')) {
                e.preventDefault();
                e.stopPropagation();
                console.log('Close button touched');
                closeMobileMenu();
            }
        });

        // Close on overlay click
        mobileMenuOverlay.addEventListener('click', function(e) {
            if (e.target === mobileMenuOverlay) {
                closeMobileMenu();
            }
        });

        // Close on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && mobileMenuOverlay.classList.contains('active')) {
                closeMobileMenu();
            }
        });

        // Close on menu item click
        const mobileMenuLinks = document.querySelectorAll('.mobile-menu-list a');
        mobileMenuLinks.forEach(link => {
            link.addEventListener('click', function() {
                setTimeout(closeMobileMenu, 300);
            });
        });
    }

    // menu
    $(document).ready(function(){
        $('.menu-item').click(function() {
            var target = $(this).data('target');
            $('.content-section').removeClass('active');
            $('#' + target).addClass('active');
            $('.menu-item').removeClass('active');
            $(this).addClass('active');
        });
    });
    document.addEventListener('DOMContentLoaded', function() {
        // Create tooltip element
        const tooltip = document.createElement('div');
        tooltip.className = 'mouse-follow-tooltip';
        document.body.appendChild(tooltip);

        // Get all menu icon links
        const menuLinks = document.querySelectorAll('.menu-icon-link');

        // Check if device is mobile/touch
        let isMobile = window.innerWidth <= 768 || 'ontouchstart' in window;

        // Update mobile detection on window resize
        window.addEventListener('resize', function() {
            isMobile = window.innerWidth <= 768 || 'ontouchstart' in window;
        });

        // Add event listeners
        menuLinks.forEach(link => {
            link.addEventListener('mouseenter', function(e) {
                const title = this.getAttribute('data-title');
                tooltip.textContent = title;
                tooltip.classList.add('visible');

                // Small delay to ensure tooltip is rendered before positioning
                setTimeout(() => {
                    if (!isMobile) {
                        // Desktop: position next to the menu item
                        positionTooltipNextToElement(this, tooltip);
                    } else {
                        // Mobile: position in fixed location
                        positionTooltipFixed(tooltip);
                    }
                }, 10);
            });

            link.addEventListener('mouseleave', function() {
                tooltip.classList.remove('visible');
            });

            // Touch devices: show tooltip on touch
            if (isMobile) {
                link.addEventListener('touchstart', function(e) {
                    const title = this.getAttribute('data-title');
                    tooltip.textContent = title;
                    tooltip.classList.add('visible');
                    
                    // Hide tooltip after 2 seconds on touch devices
                    setTimeout(() => {
                        tooltip.classList.remove('visible');
                    }, 2000);
                });
            }
        });

        // Function to position tooltip next to a specific element
        function positionTooltipNextToElement(element, tooltip) {
            const elementRect = element.getBoundingClientRect();
            const tooltipRect = tooltip.getBoundingClientRect();
            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;
            
            // Get menu position
            const menu = document.querySelector('.menu');
            const menuRect = menu ? menu.getBoundingClientRect() : null;
            const menuRight = menuRect ? menuRect.right : 0;
            
            // Calculate position to the right of the menu
            let left = menuRight + 15;
            let top = elementRect.top + (elementRect.height / 2) - (tooltipRect.height / 2);
            
            // Check if tooltip goes off the right edge
            if (left + tooltipRect.width > windowWidth - 20) {
                // Position to the left of the menu
                left = menuRect ? menuRect.left - tooltipRect.width - 15 : 20;
            }
            
            // Check if tooltip goes off the top
            if (top < 20) {
                top = 20;
            }
            
            // Check if tooltip goes off the bottom
            if (top + tooltipRect.height > windowHeight - 20) {
                top = windowHeight - tooltipRect.height - 20;
            }
            
            // Ensure tooltip doesn't go off the left
            left = Math.max(20, left);
            
            tooltip.style.left = left + 'px';
            tooltip.style.top = top + 'px';
        }

        // Function to position tooltip in a fixed, non-overlapping location
        function positionTooltipFixed(tooltip) {
            const windowWidth = window.innerWidth;
            const windowHeight = window.innerHeight;
            
            if (windowWidth <= 768) {
                // Mobile: center bottom
                const tooltipWidth = Math.min(200, windowWidth * 0.9);
                const left = (windowWidth - tooltipWidth) / 2;
                const top = windowHeight - 80;
                
                tooltip.style.left = left + 'px';
                tooltip.style.top = top + 'px';
                tooltip.style.right = 'auto';
                tooltip.style.bottom = 'auto';
            } else {
                // Desktop: right bottom corner
                tooltip.style.left = 'auto';
                tooltip.style.top = 'auto';
                tooltip.style.right = '20px';
                tooltip.style.bottom = '20px';
            }
        }
    });
    // end menu

    // skill comment
    var swiper = new Swiper(".mySwiper", {
        loop: true,
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
        autoplay: {
            delay: 3000,
            disableOnInteraction: false,
        },
    });
    // end skill comment

    // items project
    document.addEventListener('DOMContentLoaded', function() {

        function initGallery() {
            const filterButtons = document.querySelectorAll('.buttons a');
            const galleryItems = document.querySelectorAll('.gallery .image');

            filterButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();

                    filterButtons.forEach(btn => btn.classList.remove('active'));

                    this.classList.add('active');

                    const filterValue = this.textContent.trim();

                    galleryItems.forEach(item => {
                        const tags = item.dataset.tags.split(',').map(tag => tag.trim());

                        if (filterValue === 'همه' || tags.includes(filterValue)) {
                            item.classList.remove('hidden');
                        } else {
                            item.classList.add('hidden');
                        }
                    });
                });
            });
        }

        initGallery();

        if (window.elementorFrontend) {
            window.elementorFrontend.hooks.addAction('frontend/element_ready/widget', function($scope) {
                if ($scope.find('.elementor-widget-custom_gallery').length) {
                    initGallery();
                }
            });
        }
    });
    // end items project

    // Skill Post Rating AJAX
    function setSkillRatingCookie(postId) {
        var d = new Date();
        d.setTime(d.getTime() + (365*24*60*60*1000)); // 1 year
        document.cookie = "skill_rated_" + postId + "=1;expires=" + d.toUTCString() + ";path=/";
    }
    function hasSkillRatingCookie(postId) {
        return document.cookie.indexOf("skill_rated_" + postId + "=1") !== -1;
    }
    jQuery(document).ready(function($){
            $('.skill-post-rating .star-btn').on('mouseenter', function(){
        var star = $(this).data('star');
        $(this).parent().children().each(function(){
            if($(this).data('star') <= star) {
                $(this).find('i').removeClass('far fa-star').addClass('fas fa-star');
            } else {
                $(this).find('i').removeClass('fas fa-star').addClass('far fa-star');
            }
        });
    }).on('mouseleave', function(){
        $(this).parent().children().find('i').removeClass('fas fa-star').addClass('far fa-star');
    });
        $('.skill-post-rating .star-btn').on('click', function(e){
            e.preventDefault();
            var $btn = $(this);
            var postId = $btn.parent().data('post');
            var rating = $btn.data('star');
            if(hasSkillRatingCookie(postId)) {
                $('.skill-post-rating .rating-message').text(skill_rating_data.already_rated).show();
                return;
            }
            $.post(skill_rating_data.ajaxurl, {
                action: 'skill_post_rating',
                post_id: postId,
                rating: rating,
                nonce: skill_rating_data.nonce
                         }, function(response){
                 if(response.success) {
                     setSkillRatingCookie(postId);
                     $('.skill-post-rating .rating-message').text(response.data.message).show();
                     $('.skill-post-rating .average-rating').text(response.data.average_text);
                     $('.skill-post-rating .rating-count').text(response.data.count_text);
                     
                     
                     var average = parseFloat(response.data.average);
                     $('.skill-post-rating .star-btn').each(function(){
                         var starValue = $(this).data('star');
                         if(starValue <= average) {
                             $(this).find('i').removeClass('far fa-star').addClass('fas fa-star');
                         } else {
                             $(this).find('i').removeClass('fas fa-star').addClass('far fa-star');
                         }
                     });
                 } else {
                     $('.skill-post-rating .rating-message').text(response.data.message).show();
                 }
             });
        });
    });

	// Blog view toggle (grid/list)
	document.addEventListener('DOMContentLoaded', function() {
		var containers = document.querySelectorAll('[data-view-container]');
		if (!containers.length) return;

		var gridBtns = document.querySelectorAll('.view-toggle [data-view="grid"]');
		var listBtns = document.querySelectorAll('.view-toggle [data-view="list"]');

		function setActive(view) {
			try { localStorage.setItem('blog_view', view); } catch (e) {}
			gridBtns.forEach(function(btn){ btn.classList.toggle('active', view === 'grid'); });
			listBtns.forEach(function(btn){ btn.classList.toggle('active', view === 'list'); });
			containers.forEach(function(c){
				if (view === 'list') { c.classList.add('list-view'); }
				else { c.classList.remove('list-view'); }
			});
		}

		var saved = null;
		try { saved = localStorage.getItem('blog_view'); } catch (e) {}
		setActive(saved === 'list' ? 'list' : 'grid');

		gridBtns.forEach(function(btn){
			btn.addEventListener('click', function(e){ e.preventDefault(); setActive('grid'); });
		});
		listBtns.forEach(function(btn){
			btn.addEventListener('click', function(e){ e.preventDefault(); setActive('list'); });
		});
	});


})(jQuery);