// -------------- Navbar /Start -----------------
jQuery(document).ready(function () {
    let toggleBtn = jQuery('.toggle-btn');
    let navMenu = jQuery('.header-menu');
    let menuItemSharp = jQuery('.header-menu .menu > .menu-item-has-children a[href="#"]');
    let megaMenuItemHasChild = jQuery('.mega-menu > .sub-menu > li > a');


    if (window.innerWidth < 1024) {
        menuItemSharp.on('click', function (e) {
            e.preventDefault();
        });
        toggleBtn.on('click', function () {
            navMenu.toggleClass('open');
            toggleBtn.toggleClass('open');
        });

        jQuery(document).mouseup(function (e) {
            if (navMenu.hasClass("open")) {
                if (!navMenu.is(e.target) && navMenu.has(e.target).length === 0 && !toggleBtn.is(e.target) && toggleBtn.has(e.target).length === 0) {
                    navMenu.removeClass("open");
                    toggleBtn.removeClass("open");
                }
            }
        });

        megaMenuItemHasChild.on('click', function () {
            jQuery(this).next().toggleClass('active');
        });
    }

});
// -------------- Navbar /End -----------------
// ----------- Plans Section/ Start ----------
jQuery(document).ready(function () {
    if (window.innerWidth <= 660) {
        jQuery('.plan-acc-body').slideUp();
        jQuery('.solutions-wrapper .plan-acc-head').on('click', function () {
            jQuery(this).siblings('.plan-acc-body').slideToggle();
            jQuery(this).toggleClass('active');
        });
    }
    jQuery(window).on("resize", function () {
        if (window.innerWidth <= 660) {
            jQuery('.plan-acc-body').slideUp();

            // Remove previously attached click event handlers
            jQuery('.solutions-wrapper .plan-acc-head').off('click');

            // Attach a new click event handler
            jQuery('.solutions-wrapper .plan-acc-head').on('click', function () {
                jQuery(this).siblings('.plan-acc-body').slideToggle();
                jQuery(this).toggleClass('active');
            });
        } else {
            jQuery('.plan-acc-body').slideDown();
            jQuery(this).removeClass('active');
            // Remove click event handlers when the window width is greater than 660
            jQuery('.solutions-wrapper .plan-acc-head').off('click');
        }
    });

});

// ----------- Plans Hero Section/ Start ----------
// -------------- Network service/Start -----------------
document.addEventListener('DOMContentLoaded', function () {
    const items = document.querySelectorAll('.service-item');
    const pictures = document.querySelectorAll('.service-picture');
    pictures[0]?.classList.add('active');
    items.forEach((item, index) => {
        item.addEventListener('mouseover', function () {
            showPicture(index);
        });
    });

    function showPicture(pictureNumber) {
        pictures.forEach(picture => {
            picture.classList.remove('active');
        });
        pictures[pictureNumber].classList.add('active');
    }

});

// -------------- Network service/ End -----------------
// -------------- Header/ Start -----------------
jQuery(document).ready(function () {
    jQuery(window).scroll(function () {
        if (jQuery(this).scrollTop() > 100) {
            jQuery('#main_header').addClass('active');
        } else {
            jQuery('#main_header').removeClass('active');
        }
    });
});

// Scroll down by 80vh with smooth behavior
let section_height = window.innerHeight;

function handleScroll() {
    console.log(108);
    if (window.scrollY <= window.innerHeight * 0.1) {
        window.scrollTo({
            top: window.scrollY + section_height, // Make sure to define section_height
            behavior: 'smooth'
        });
        window.removeEventListener('scroll', handleScroll);
    } else {
        window.removeEventListener('scroll', handleScroll);
    }
}

// Check if the current page is the homepage
if (window.location.pathname === '/' || window.location.pathname === '/index.php') {
    window.addEventListener('scroll', handleScroll);
}


let header_height = document.querySelector('#main_header').clientHeight;
document.addEventListener('DOMContentLoaded', function () {
    var scrollDownWrapper = document.querySelector('.scroll-down-wrapper');
    if (scrollDownWrapper) {
        scrollDownWrapper.addEventListener('click', function () {
            window.scrollTo({
                top: (window.innerHeight - header_height),
                behavior: 'smooth'
            });
        });
    }
});

// -------------- Header/ End -----------------
// -------------- Project Slider/ Start -----------------
document.addEventListener('DOMContentLoaded', function () {
    const slider = document.querySelector('.swiper-project.swiper-container');
    if (slider) {
        var mySwiper = new Swiper('.swiper-project.swiper-container', {
            slidesPerView: 1,
            spaceBetween: 10,
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
                dynamicBullets: false
            },
            navigation: {
                nextEl: '.custom-swiper-navigation .swiper-button-next',
                prevEl: '.custom-swiper-navigation .swiper-button-prev',
            },
            effect: 'fade', // Set fade effect
            fadeEffect: {
                crossFade: true,
            },
            on: {
                slideChange: function () {
                    var currentSlide = mySwiper.activeIndex + 1;
                    document.querySelector('.swiper-slide-number .current').textContent = currentSlide;
                },
            },
        });

        document.querySelector('.swiper-slide-number .total').textContent = mySwiper.slides.length;
    }
});
// -------------- Project Slider/ End -----------------
// ----------- Hinza Hero Section/ Start ----------
const canvas = document.querySelector("canvas");
if (canvas) {
    class Symbol {
        constructor(x, y, fontSize, canvasHeight) {
            this.chracters = "01 001 110 10 111 110 010 011 110 000";
            this.x = x;
            this.y = y;
            this.fontSize = fontSize;
            this.canvasHeight = canvasHeight;
            this.text = "";
        }

        draw(context) {
            // generating a random symbol from characters string
            this.text = this.chracters.charAt(
                Math.floor(Math.random() * this.chracters.length)
            );
            //drawing text
            context.textAlign = "center";
            context.font = this.fontSize + "px monospace";
            context.fillText(this.text, this.x * this.fontSize, this.y * this.fontSize);
        }

        // resetting y-axis to 0 if it crosses the height of the window
        // otherwise incerementing y-axis value by 1
        update() {
            if (this.y * this.fontSize > this.canvasHeight && Math.random() > 0.98) {
                this.y = 0;
            } else {
                this.y += 1;
            }
        }
    }

    class Effect {
        constructor(canvasWidth, canvasHeight) {
            this.canvasWidth = canvasWidth;
            this.canvasHeight = canvasHeight;
            this.fontSize = 17;
            this.columns = canvasWidth / this.fontSize;
            this.symbols = [];
            this.#initialize();
        }

        #initialize() {
            // initializing symbols array with Symbol objects
            for (let i = 0; i < this.columns; i++) {
                this.symbols[i] = new Symbol(i, 0, this.fontSize, this.canvasHeight);
            }
        }

        //function will be called when window resize event occurs
        resize(width, height) {
            this.canvasWidth = width;
            this.canvasHeight = height;
            this.columns = this.canvasWidth / this.fontSize;
            this.symbols = [];
            this.#initialize();
        }
    }


    const ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

//single color
    const singleColor = "#888888";

//gradient color
    let gradientColor = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
    gradientColor.addColorStop(0, "red");
    gradientColor.addColorStop(0.2, "yellow");
    gradientColor.addColorStop(0.4, "green");
    gradientColor.addColorStop(0.6, "cyan");
    gradientColor.addColorStop(0.8, "blue");
    gradientColor.addColorStop(0, "magenta");

// default color
    let defaultColor = singleColor;

// creating effect object which initializes symbols array with Symbol objects
    const effect = new Effect(canvas.width, canvas.height);

    const fps = 50;
    const nextframe = 1000 / fps; //for fps = 50, nextFrame = 20
    let timer = 0;

    function animate(timeStamp) {
        let lastTime = 0;
        // checking paint time difference
        const deltaTime = timeStamp - lastTime;
        //updating lastTime = current elapsed time to  paint the screen
        lastTime = timeStamp;
        // if time exceeds nextframe value then paint
        // and reset timer to zero else add delta time
        if (timer > nextframe) {
            // drawing transparent rectangle over text to hide previous text
            ctx.fillStyle = "rgba(0,0, 0, 0.05)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            // text color
            ctx.fillStyle = defaultColor;
            //drawing text column
            effect.symbols.forEach((symbol) => {
                symbol.draw(ctx);
                symbol.update();
            });
            timer = 0;
        } else {
            timer += deltaTime;
        }

        requestAnimationFrame(animate);
    }

    animate(0);

// resize event to handle columns adjustment on window resize
    window.addEventListener("resize", () => {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        effect.resize(canvas.width, canvas.height);
        gradientColor = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
        gradientColor.addColorStop(0, "red");
        gradientColor.addColorStop(0.2, "yellow");
        gradientColor.addColorStop(0.4, "green");
        gradientColor.addColorStop(0.6, "cyan");
        gradientColor.addColorStop(0.8, "blue");
        gradientColor.addColorStop(0, "magenta");
    });

//double mouse click event
    window.addEventListener("dblclick", () => {
        defaultColor === singleColor
            ? (defaultColor = gradientColor)
            : (defaultColor = singleColor);
    });

//double touch event on touch screen devices
    var lastTouchEnd = 0;
    window.addEventListener("touchend", () => {
        var now = new Date().getTime();
        if (now - lastTouchEnd <= 300) {
            // Code to be executed when a double-tap is detected
            defaultColor === singleColor
                ? (defaultColor = gradientColor)
                : (defaultColor = singleColor);
        }
        lastTouchEnd = now;
    });
}
// -------------- Hinza Hero Section/ End -----------------
// -------------- Back to top / Start -----------------
jQuery(document).ready(function ($) {

    jQuery(window).scroll(function () {
        if (jQuery(window).scrollTop() >= 400) {
            jQuery('#backtotop').fadeIn();
        } else {
            jQuery('#backtotop').fadeOut();
        }

    });
    jQuery('#backtotop').on('click', function (e) {
        e.preventDefault();

        jQuery("html, body").animate({scrollTop: 0}, 1000);
        return false;
    });

});

// -------------- Back to top / End -----------------
// -------------- Smooth scrolling to section / Start -----------------
/*jQuery(window).on("load", function () {
    // Smooth scrolling when clicking on links
    jQuery('a[href^="#"]:not(.backtotop)').on('click', function (e) {
        e.preventDefault();
        const scrollTopValue = jQuery(jQuery(this).attr('href')).offset().top;
        console.log("line 332");
        console.log(jQuery(this).attr('href'));
        console.log(scrollTopValue);

        jQuery('html, body').animate(
            {
                scrollTop: scrollTopValue
            },
            4000, // Adjust the speed (milliseconds)
            'swing'
        );
    });
});*/

/*jQuery(document).ready(function($) {
    // Smooth scrolling when clicking on links
    jQuery('a[href^="#"]:not(.backtotop)').on('click', function (e) {
        e.preventDefault();
        const scrollTopValue = jQuery(jQuery(this).attr('href')).offset().top;
        jQuery('html, body').stop().animate(
            {
                scrollTop: scrollTopValue - 120
            },6000,'linear');
    });
});*/

// -------------- Smooth scrolling to section / End -----------------
// -------------- Network Support plan click / Start -----------------
let hourly = jQuery('.landing-solution #hourly-support'),
    halftime = jQuery('.landing-solution #halftime-support'),
    fulltime = jQuery('.landing-solution #fulltime-support'),
    freeconsultNetwork = jQuery('.section-support-network #free-consult'),
    form = jQuery('.contact-section form'),
    typeSelect = form.find('select[name="support-type"]');

if(hourly || halftime || fulltime || freeconsultNetwork && typeSelect){
    freeconsultNetwork.on('click',function (){
        typeSelect.val('آنالیز رایگان شبکه');
    });
    hourly.on('click',function (){
        typeSelect.val('پشتیبانی ساعتی');
    });
    halftime.on('click',function (){
        typeSelect.val('پشتیبانی هفتگی');
    });
    fulltime.on('click',function (){
        typeSelect.val('پشتیبانی ماهانه');
    });
}
// -------------- Network Support plan click / End -----------------
// -------------- Ecommerce plan click / Start -----------------
let basePlan = jQuery('.ecommerce-suggestion #e-base-plan'),
    proPlan = jQuery('.ecommerce-suggestion #e-pro-plan'),
    freeconsultEcommerce = jQuery('.section-support-network.ecommerce #free-consult'),
    typeSelecte = form.find('select[name="ecommerce-type"]');

if(basePlan || proPlan || freeconsultEcommerce && typeSelecte){
    freeconsultEcommerce.on('click',function (){
        typeSelecte.val('درخواست مشاوره');
    });
    basePlan.on('click',function (){
        typeSelecte.val('بسته پایه');
    });
    proPlan.on('click',function (){
        typeSelecte.val('بسته حرفه‌ای');
    });
}
// -------------- Ecommerce plan click / End -----------------

document.addEventListener("DOMContentLoaded", () => {
    const section = document.querySelector('.nav-integrated .sub-menu');
    const menuItems = section.querySelectorAll('.menu-item a');

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                section.classList.add('active');

                // محاسبه مدت کل انیمیشن آخرین آیتم
                const lastDelay = 0.6; // آخرین delay بر حسب ثانیه
                const animationDuration = 1.3; // طول انیمیشن بر حسب ثانیه
                const totalTime = (lastDelay + animationDuration) * 1000;

                setTimeout(() => {
                    section.classList.remove('active');
                    // وقتی کلاس active رفت، کلاس finished به همه اضافه کن
                    menuItems.forEach(item => item.classList.add('finished'));
                }, totalTime);
            }
        });
    }, { threshold: 0.4 });

    observer.observe(section);
});
