/*start nav*/
jQuery('.sub-list').slideUp();
jQuery('.mobile-nav-list .link > i').on('click',function () {
    if (jQuery(this).hasClass('open')) {
        jQuery(this).siblings('.sub-list').slideUp();
        jQuery(this).removeClass('open');
    } else {
        jQuery(this).parents(".sub-link").siblings(".sub-link").find(".sub-list").slideUp();
        jQuery(this).parents(".sub-link").siblings(".sub-link").find("i").removeClass("open");
        jQuery(this).parent().siblings(".link").find(".sub-list").slideUp();
        jQuery(this).parent().siblings(".link").find("i").removeClass("open");
        jQuery(this).siblings('.sub-list').slideDown();
        jQuery(this).addClass('open')
    }
});


jQuery('.nav-btn').on('click',function () {
    jQuery('.mobile-nav-list, .nav-overlay').addClass('trans-none');
    jQuery('body').addClass('over-hidden')
});
jQuery('.nav-overlay').on('click',function () {
    jQuery('.mobile-nav-list, .nav-overlay').removeClass('trans-none');
    jQuery('body').removeClass('over-hidden')
});
/*end nav*/

$(document).ready(function() {
    // Initialize AOS (Animate On Scroll)
    AOS.init({
        duration: 1000,
        easing: 'ease-in-out',
        once: true,
        mirror: false
    });
    var $clone = $('#mainNav').clone(true, true);
    $('#sec_menu').empty().append($clone);


    // Navbar scroll effect
    $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
            $('#sec_menu').addClass('scrolled');
        } else {
            $('#sec_menu').removeClass('scrolled');
        }
    });

    // Smooth scrolling for navigation links
    $('a[href^="#"]').on('click', function(event) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            event.preventDefault();
            $('html, body').stop().animate({
                scrollTop: target.offset().top - 80
            }, 1000);
        }
    });

    // Counter animation for stats
    function animateCounters() {
        $('.stat-number').each(function() {
            var $this = $(this);
            var target = parseInt($this.data('target'));
            var current = 0;
            var increment = target / 100;
            var timer = setInterval(function() {
                current += increment;
                if (current >= target) {
                    current = target;
                    clearInterval(timer);
                }
                $this.text(Math.floor(current));
            }, 20);
        });
    }

    // Trigger counter animation when stats section is visible
    var statsTriggered = false;
    $(window).scroll(function() {
        var statsSection = $('#stats');

        // تحقق من وجود العنصر
        if (statsSection.length === 0) {
            return; // لو العنصر مش موجود، اخرج من الـ scroll function
        }

        var scrollTop = $(window).scrollTop();
        var elementTop = statsSection.offset().top;
        var elementHeight = statsSection.height();
        var windowHeight = $(window).height();

        if (!statsTriggered && scrollTop > elementTop - windowHeight + elementHeight / 2) {
            animateCounters();
            statsTriggered = true;
        }
    });


    // Initialize Charts
    initializeCharts();

    // Parallax effect for hero section
    $(window).scroll(function() {
        var scrolled = $(window).scrollTop();
        var parallax = $('.hero-background');
        var speed = scrolled * 0.5;
        parallax.css('transform', 'translateY(' + speed + 'px)');
    });

    // Add hover effects to cards
    $('.feature-card, .service-card, .testimonial-card, .chart-card').hover(
        function() {
            $(this).addClass('shadow-lg');
            $(this).find('.feature-icon, .service-icon').addClass('animate__animated animate__pulse');
        },
        function() {
            $(this).removeClass('shadow-lg');
            $(this).find('.feature-icon, .service-icon').removeClass('animate__animated animate__pulse');
        }
    );

    // Interactive statistics with hover effects
    $('.stat-card').hover(
        function() {
            $(this).find('.stat-number').addClass('text-warning');
            $(this).find('.stat-suffix').addClass('text-warning');
            $(this).find('.stat-icon').addClass('animate__animated animate__bounceIn');
        },
        function() {
            $(this).find('.stat-number').removeClass('text-warning');
            $(this).find('.stat-suffix').removeClass('text-warning');
            $(this).find('.stat-icon').removeClass('animate__animated animate__bounceIn');
        }
    );

    // Testimonial carousel effect
    let currentTestimonial = 0;
    const testimonials = $('.testimonial-card');

    function rotateTestimonials() {
        testimonials.removeClass('active-testimonial');
        testimonials.eq(currentTestimonial).addClass('active-testimonial');
        currentTestimonial = (currentTestimonial + 1) % testimonials.length;
    }

    // Auto-rotate testimonials every 5 seconds
    setInterval(rotateTestimonials, 5000);

    // Initialize first testimonial
    rotateTestimonials();

    // Mobile menu close on link click
    $('.navbar-nav .nav-link').on('click', function() {
        if ($(window).width() < 992) {
            $('.navbar-collapse').collapse('hide');
        }
    });

    // Loading animation for buttons
    $('.btn').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.html();

        if (!$btn.hasClass('loaading')) {
            $btn.addClass('loaading');
            $btn.html('<span class="loading"></span> جاري التحميل...');

            setTimeout(function() {
                $btn.removeClass('loaading');
                $btn.html(originalText);
            }, 2000);
        }
    });
    Fancybox.bind("[data-fancybox]", {});
});



// Intersection Observer for animations
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver(function(entries) {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('visible');
        }
    });
}, observerOptions);

// Observe elements for animation
document.addEventListener('DOMContentLoaded', function() {
    const animatedElements = document.querySelectorAll('.fade-in, .slide-in-left, .slide-in-right, .zoom-in');
    animatedElements.forEach(el => observer.observe(el));
});

// Utility functions
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

// Optimized scroll handler
const optimizedScroll = debounce(function() {
    // Add any scroll-based functionality here
}, 10);

window.addEventListener('scroll', optimizedScroll);

// Form validation and submission
function validateForm(form) {
    let isValid = true;
    const inputs = form.querySelectorAll('input[required], textarea[required]');

    inputs.forEach(input => {
        if (!input.value.trim()) {
            input.classList.add('is-invalid');
            isValid = false;
        } else {
            input.classList.remove('is-invalid');
        }
    });

    return isValid;
}

// Email validation
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

// Phone validation (Saudi format)
function validatePhone(phone) {
    const re = /^(05|5)[0-9]{8}$/;
    return re.test(phone.replace(/\s/g, ''));
}

// Lazy loading for images
function lazyLoadImages() {
    const images = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });

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

// Initialize lazy loading
document.addEventListener('DOMContentLoaded', lazyLoadImages);

// Performance monitoring
function measurePerformance() {
    if ('performance' in window) {
        window.addEventListener('load', function() {
            setTimeout(function() {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('Page Load Time:', perfData.loadEventEnd - perfData.fetchStart, 'ms');
            }, 0);
        });
    }
}

measurePerformance();

// Error handling
window.addEventListener('error', function(e) {
    console.error('JavaScript Error:', e.error);
    // You can send error reports to your analytics service here
});

// Service Worker registration (for PWA capabilities)
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js')
            .then(function(registration) {
                console.log('ServiceWorker registration successful');
            })
            .catch(function(err) {
                console.log('ServiceWorker registration failed');
            });
    });
}

