import jQuery from 'jquery';
import Swup from 'swup';
import SwupPreloadPlugin from '@swup/preload-plugin';
import SwupScrollPlugin from '@swup/scroll-plugin';
import Foundation from 'foundation-sites';


jQuery(($) => {

    const swup = new Swup({
        plugins: [
            new SwupScrollPlugin(
                {
                    animateScroll: false
                },
            ),
            new SwupPreloadPlugin()
        ],
        elements: ['#swup'],
        animationSelector: '.swupper-overlay-1',
        animateHistoryBrowsing: false,
    });
    $(document).foundation();
    $('.vertical.menu.accordion-menu').foundation('toggle', $('.current-menu-parent > ul'));

    $(document).on('resize scroll', (evt, elem) => {
        if (jQuery('.amds-block-facts .wp-block-column').isInViewport()) {
            setTimeout(() => {
                initAnimation()
            }, 100)
        }
    });

    // $(document).on('scroll', function () {
    //     if ($(window).scrollTop() > 100) {
    //         $('.scroll-top-wrapper').addClass('show');
    //     } else {
    //         $('.scroll-top-wrapper').removeClass('show');
    //     }
    // });

    // javaScript Recall after swup-Reload
    document.addEventListener('swup:pageView', function() {
        var acc = document.getElementsByClassName("meg-accordion");
        var i;

        for (i = 0; i < acc.length; i++) {
            acc[i].addEventListener("click", function() {
                /* Toggle between adding and removing the "active" class,
                to highlight the button that controls the panel */
                this.classList.toggle("active");

                /* Toggle between hiding and showing the active panel */
                var panel = this.nextElementSibling;
                if (panel.style.maxHeight) {
                    panel.style.maxHeight = null;
                } else {
                    panel.style.maxHeight = panel.scrollHeight + "px";
                }
            });
        }


        $('.meg-scrollpoint > figure').click(function(event){
            scrollDown();
            event.preventDefault();
        });

        $('.scroll-top-wrapper').on('click', () => {
                $('html, body').animate({scrollTop: 0}, 500, 'linear');
            }
        );

        // Select all links with hashes
        $('a[href*="#"]')
            // Remove links that don't actually link to anything
            .not('[href="#"]')
            .not('[href="#0"]')
            .click(function(event) {
                // On-page links
                if (
                    location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                    &&
                    location.hostname == this.hostname
                ) {
                    // Figure out element to scroll to
                    var target = $(this.hash);
                    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                    // Does a scroll target exist?
                    if (target.length) {
                        // Only prevent default if animation is actually gonna happen
                        event.preventDefault();
                        $('html, body').animate({
                            scrollTop: target.offset().top - 50
                        }, 1000, function() {
                            // Callback after animation
                            // Must change focus!
                            var $target = $(target);
                            $target.focus();
                            if ($target.is(":focus")) { // Checking if the target was focused
                                return false;
                            } else {
                                $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                                $target.focus(); // Set focus again
                            };
                        });
                    }
                }
            });
    });

    var acc = document.getElementsByClassName("meg-accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
        acc[i].addEventListener("click", function() {
            /* Toggle between adding and removing the "active" class,
            to highlight the button that controls the panel */
            this.classList.toggle("active");

            /* Toggle between hiding and showing the active panel */
            var panel = this.nextElementSibling;
            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        });
    }

    $(window).scroll(function(){
        if (window.innerHeight > 400) {
            $(".meg-scrollpoint").css("opacity", 1 - ($(window).scrollTop() - 200) / 640);
        }
    });

    $('.meg-scrollpoint > figure').click(function(event){
        scrollDown();
        event.preventDefault();
    });

    $('.scroll-top-wrapper').on('click', () => {
            $('html, body').animate({scrollTop: 0}, 500, 'linear');
        }
    );

    // Select all links with hashes
    $('a[href*="#"]')
        // Remove links that don't actually link to anything
        .not('[href="#"]')
        .not('[href="#0"]')
        .click(function(event) {
            // On-page links
            if (
                location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                &&
                location.hostname == this.hostname
            ) {
                // Figure out element to scroll to
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                // Does a scroll target exist?
                if (target.length) {
                    // Only prevent default if animation is actually gonna happen
                    event.preventDefault();
                    $('html, body').animate({
                        scrollTop: target.offset().top - 50
                    }, 1000, function() {
                        // Callback after animation
                        // Must change focus!
                        var $target = $(target);
                        $target.focus();
                        if ($target.is(":focus")) { // Checking if the target was focused
                            return false;
                        } else {
                            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                            $target.focus(); // Set focus again
                        };
                    });
                }
            }
        });
});

var animationLock = false;

jQuery.fn.isInViewport = function () {
    var elementTop = jQuery(this).offset().top;
    var elementBottom = elementTop + jQuery(this).outerHeight();
    var viewportTop = jQuery(window).scrollTop();
    var viewportBottom = viewportTop + jQuery(window).height();
    return elementBottom > viewportTop && elementTop < viewportBottom;
};

function initAnimation() {

    var elems = jQuery('.amds-block-facts strong');
    console.log(elems);

    if (!animationLock) {

        animationLock = true;
        elems.each(function (index) {
            animateNumber(jQuery(this), 1, 0, jQuery(this).html())
        });
    }
}

function animateNumber(elem, currentStep, currentValue, value) {
    // const stepCount = value * 0.66;
    const stepCount = 3000;
    const delay = 15;

    value = parseFloat(value);
    currentValue = parseFloat(currentValue);

    var increaseByValue = (value - currentValue) / stepCount;

    currentValue = currentValue + (increaseByValue * currentStep);
    elem.html(parseInt(currentValue));

    if (increaseByValue * currentStep < 1) {
        elem.html(parseInt(value));
        currentStep = 1
    }

    if (currentStep < stepCount) setTimeout(() => {
        animateNumber(elem, currentStep + 1, currentValue, value)
    }, parseInt(delay - ((delay / stepCount) * currentStep)));
}

function scrollDown() {
    var screenh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

    window.scrollTo({
        top: screenh, //1010
        left: 0,
        behavior: 'smooth'
    });
}