/**
 * Files to manage theme scripts.
 *
 * @package Purenote
 */

jQuery(document).ready(function($) {
    var headerSticky        = PN_JSObject.header_sticky,
        sidebarSticky       = PN_JSObject.sidebar_sticky,
        ajaxUrl             = PN_JSObject.ajaxUrl,
        _wpnonce            = PN_JSObject._wpnonce,
        KEYCODE_TAB         = 9,
        KEYCODE_ESC         = 27;

    var rtl = false;
    var dir = "left";
    if ($('body').hasClass("rtl")) {
        rtl = true;
        dir = "right";
    };

    /**
     * Preloader
     */
    if ($('#purenote-preloader').length > 0) {
        setTimeout(function() {
            $('#purenote-preloader').hide();
        }, 600);
    }
    
     // site mode switcher
    function siteModeToggle(siteModeVal) {
        $.removeCookie('purenote-site-mode-cookie', {
            path: '/'
        });
        if (siteModeVal === 'light-mode') {
            updateVal = 'dark-mode';
        } else {
            updateVal = 'light-mode';
        }
        $("#mode-switcher").removeClass(siteModeVal);
        $("#mode-switcher").addClass(updateVal);
        $('body').removeClass(siteModeVal);
        $('body').addClass(updateVal);
        var exDate = new Date();
        exDate.setTime(exDate.getTime() + (3600 * 1000)); 
        $.cookie('purenote-site-mode-cookie', updateVal, {
            expires: exDate,
            path: '/'
        });
    }

    $("#mode-switcher").click(function(event) {
        event.preventDefault();
        var siteModeClass = $(this).attr('class');
        siteModeAttr = $(this).data('site-mode');

        if ($(this).hasClass(siteModeAttr)) {
            siteModeToggle(siteModeAttr);
        } else {
            siteModeToggle(siteModeClass);
        }
    });

     // header news ticker
    $('.ticker-posts').marquee({
        duration: 50000,
        delayBeforeStart: 0,
        gap: 0,
        direction: dir,
        duplicated: true,
        startVisible: true,
        pauseOnHover: true,
    });

     //banner slider
    $(document).ready(function() {
        var mainSlider = $(".purenote-banner-wrapper");
        if (mainSlider.length) {
            var secSlider = mainSlider.find(".slider-wrapper");
            var slideAuto = secSlider.data("auto");
            var slideControl = secSlider.data("control");
            secSlider.lightSlider({
                item: 1,
                auto: slideAuto === true || slideAuto === "true",
                pager: false,
                loop: true,
                slideMargin: 0,
                speed: 1000,
                pause: 6000,
                enableTouch: true,
                rtl: rtl,
                enableDrag: true,
                pauseOnHover: true,
                prevHtml: '<i class="fas fa-chevron-left"></i>',
                nextHtml: '<i class="fas fa-chevron-right"></i>',
                onSliderLoad: function() {
                    $('.slider-wrapper').removeClass('cS-hidden');
                }
            });
        }
    });

    /**
     * Highlight slider
     */
    $('.highlight-slider-wrapper').each(function(){
        var wrapper = this;
        var slider = wrapper.querySelector('.swiper-wrapper');
        var slides = slider.children;
        var total = slides.length;
        var current = 0;

        function showSlide(index){
            if(index < 0) index = total - 1;
            if(index >= total) index = 0;
            current = index;
            var slideWidth = slides[0].offsetWidth + 15; // include margin
            slider.style.transform = 'translateX(' + (-current * slideWidth) + 'px)';
        }

        wrapper.querySelector('.custom-button-prev').addEventListener('click', function(){ showSlide(current - 1); });
        wrapper.querySelector('.custom-button-next').addEventListener('click', function(){ showSlide(current + 1); });

        // Optional auto-slide every 5 seconds
        setInterval(function(){ showSlide(current + 1); }, 5000);
    });

    /**
     * Settings of the header sticky menu
     */
    if ('true' === headerSticky) {
        var windowWidth = $(window).width();
        if (windowWidth > 600) {
            var wpAdminBar = $('#wpadminbar');
            if (wpAdminBar.length) {
                $("#header .site-logo-wrapper").sticky({
                    topSpacing: wpAdminBar.height()
                });
            } else {
                $("#header .site-logo-wrapper").sticky({
                    topSpacing: 0
                });
            }
        }
    }

    /**
     * theia sticky sidebar
     */
    if ('true' === sidebarSticky) {
        $('#primary, #secondary').theiaStickySidebar({
            additionalMarginTop: 30
        });

        $('#primary, #left-secondary').theiaStickySidebar({
            additionalMarginTop: 30
        });

        $('.primary-content-wrapper, .secondary-content-wrapper').theiaStickySidebar({
            additionalMarginTop: 30
        });
    }

    /**
     * Scroll To Top
     */
    $(window).scroll(function() {
        if ($(this).scrollTop() > 1000) {
            $('#purenote-scrollup').fadeIn('slow');
        } else {
            $('#purenote-scrollup').fadeOut('slow');
        }
    });
    $('#purenote-scrollup').click(function() {
        $("html, body").animate({
            scrollTop: 0
        }, 600);
        return false;
    });

    //Search toggle
    $('.header-search-wrapper .search-icon').click(function() {
        $('.search-form-wrap').toggleClass('active-search');
        $('.search-form-wrap .search-field').focus();
        var element = document.querySelector('.header-search-wrapper');
        if (element) {
            $(document).on('keydown', function(e) {
                if (element.querySelectorAll('.search-form-wrap.active-search').length === 1) {
                    var focusable = element.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
                    var firstFocusable = focusable[0];
                    var lastFocusable = focusable[focusable.length - 1];
                    purenote_focus_trap(firstFocusable, lastFocusable, e);
                }
            })
        }
    });

    $('.header-search-wrapper .search-icon-close').click(function() {
        $('.search-form-wrap').removeClass('active-search');
    });

    // Responsive main menu toggle
    $('#site-navigation .purenote-menu-toogle').on('click', function() {
        const $menuWrap = $(this).siblings('.primary-menu-wrap');
        $menuWrap.toggleClass('isActive').slideToggle('slow');

        const element = $menuWrap[0];
        if (element) {
            $(document).on('keydown.responsiveMenu', function(e) {
                if (element.classList.contains('isActive')) {
                    const focusable = element.querySelectorAll(
                        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                    );
                    const firstFocusable = document.querySelector('#site-navigation .purenote-menu-toogle');
                    const lastFocusable = focusable[focusable.length - 1];
                    focusTrap(firstFocusable, lastFocusable, e);
                }
            });
        }
    });

    // Sub-menu toggle
    $('<a class="purenote-sub-toggle" href="javascript:void(0);"><i class="fa fa-angle-right"></i></a>')
        .insertAfter('#site-navigation .menu-item-has-children > a, #site-navigation .page_item_has_children > a');

    $('#site-navigation .purenote-sub-toggle').on('click', function() {
        const $parentLi = $(this).parent();
        $parentLi.children('ul.sub-menu, ul.children').first().slideToggle(400);
        $(this).children('i.fa-angle-right').toggleClass('fa-angle-down');
    });
        
    // Focus trap for accessibility
    function focusTrap(firstFocusable, lastFocusable, e) {
        if (e.key === 'Tab' || e.keyCode === KEYCODE_TAB) {
            if (e.shiftKey) { // Shift + Tab
                if (document.activeElement === firstFocusable) {
                    lastFocusable.focus();
                    e.preventDefault();
                }
            } else { // Tab
                if (document.activeElement === lastFocusable) {
                    firstFocusable.focus();
                    e.preventDefault();
                }
            }
        }
    }

    // Close menu on ESC key
    $(document).on('keydown', function(event) {
        if (event.keyCode === KEYCODE_ESC) {
            $('#site-navigation.isActive').removeClass('isActive').slideUp('slow');
        }
    });
    // ==========================================
    // Web Stories
    // ==========================================

    const STORY_DURATION = 5000;
    let innerSwiper = null;
    let progressTimer = null;
    let isPaused = false;
    let storyCategories = [];
    let currentCategoryIndex = 0;

    const $innerModal   = $('.inner-stories-wrap');
    const $innerWrapper = $innerModal.find('.swiper-wrapper');

    /* ------------------------------------------
     Horizontal scroll for story previews
    -------------------------------------------*/
    $('.stories-wrap').on('wheel', function (e) {
        e.preventDefault();
        this.scrollLeft += e.originalEvent.deltaY;
    });

    /* ------------------------------------------
     Click left / right to scroll stories
    -------------------------------------------*/
    $('.stories-wrap').on('click', function (e) {

        if ($(e.target).closest('.story').length) return;

        const $wrap = $(this);
        const offsetX = e.pageX - $wrap.offset().left;
        const width = $wrap.outerWidth();
        const scrollAmount = width * 0.8;

        if (offsetX < width / 2) {
            $wrap.animate({
                scrollLeft: $wrap.scrollLeft() - scrollAmount
            }, 400);
        } else {
            $wrap.animate({
                scrollLeft: $wrap.scrollLeft() + scrollAmount
            }, 400);
        }
    });

    /* ------------------------------------------
     Open story modal
    -------------------------------------------*/
    $(document).on('click', '.story .preview', function (e) {

        if ($(e.target).closest('.story-count').length) return;

        storyCategories = $('.story').map(function () {
            return $(this).data('id');
        }).get();

        const clickedCatId = $(this).closest('.story').data('id');
        currentCategoryIndex = storyCategories.indexOf(clickedCatId);

        $innerModal.addClass('open is-loading cS-hidden');

        const slidesHTML = JSON.parse($(this).closest('.story').attr('data-slides'));
        $innerWrapper.html(slidesHTML);

        setupDots();
        initSwiper();
        showStories();
    });

    /* ------------------------------------------
     Progress dots
    -------------------------------------------*/
    function setupDots() {
        const slideCount = $innerWrapper.find('.swiper-slide').length;
        let dotsHtml = '<ul class="story-dots" role="tablist">';

        for (let i = 0; i < slideCount; i++) {
            dotsHtml += `
                <li role="presentation" class="${i === 0 ? 'active' : ''}">
                    <button role="tab">
                        <span class="progress-bar-inner"></span>
                    </button>
                </li>`;
        }

        dotsHtml += '</ul>';

        $innerModal.find('.story-dots').remove();
        $innerModal.find('.inner-stories').prepend(dotsHtml);
    }

    /* ------------------------------------------
     Show modal
    -------------------------------------------*/
    function showStories() {
        $innerModal.removeClass('cS-hidden is-loading').addClass('ready');
        isPaused = false;
        animateProgress();
    }

    /* ------------------------------------------
     Swiper init
    -------------------------------------------*/
    function initSwiper() {

        if (innerSwiper && !innerSwiper.destroyed) {
            innerSwiper.destroy(true, true);
        }

        innerSwiper = new Swiper('.inner-stories', {
            slidesPerView: 1,
            effect: 'fade',
            fadeEffect: { crossFade: true },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            watchOverflow: false,
            on: {
                slideChangeTransitionStart() {
                    clearTimeout(progressTimer);
                },
                slideChangeTransitionEnd() {
                    animateProgress();
                }
            }
        });
    }

    /* ------------------------------------------
     Progress animation
    -------------------------------------------*/
    function animateProgress() {

        if (isPaused || !innerSwiper) return;

        const activeIndex = innerSwiper.activeIndex;
        const $dots = $innerModal.find('.story-dots li');

        $dots.removeClass('active completed').each(function (index) {
            const $bar = $(this).find('.progress-bar-inner');

            if (index < activeIndex) {
                $(this).addClass('completed');
                $bar.css({ width: '100%', transition: 'none' });
            } else if (index > activeIndex) {
                $bar.css({ width: '0%', transition: 'none' });
            }
        });

        const $activeDot = $dots.eq(activeIndex).addClass('active');
        const $currentBar = $activeDot.find('.progress-bar-inner');

        $currentBar.css({ width: '0%', transition: 'none' });
        $currentBar[0].offsetHeight;
        $currentBar.css({
            width: '100%',
            transition: `width ${STORY_DURATION}ms linear`
        });

        progressTimer = setTimeout(function () {

            if (activeIndex >= innerSwiper.slides.length - 1) {
                goToNextCategory();
            } else {
                innerSwiper.slideNext();
            }

        }, STORY_DURATION);
    }

    /* ------------------------------------------
     Next category autoplay
    -------------------------------------------*/
    function goToNextCategory() {

        currentCategoryIndex++;

        if (currentCategoryIndex >= storyCategories.length) {
            closeStories();
            return;
        }

        const nextCat = $('.story').eq(currentCategoryIndex);
        const slidesHTML = JSON.parse(nextCat.attr('data-slides'));

        $innerWrapper.html(slidesHTML);

        setupDots();
        initSwiper();
        showStories();
    }

    /* ------------------------------------------
     Close modal
    -------------------------------------------*/
    function closeStories() {

        clearTimeout(progressTimer);

        if (innerSwiper && !innerSwiper.destroyed) {
            innerSwiper.destroy(true, true);
        }

        innerSwiper = null;
        $innerModal.removeClass('open ready is-loading');
    }

    $(document).on('click', '.action-btn.close', closeStories);

    /* ------------------------------------------
     Pause / Play
    -------------------------------------------*/
    $(document).on('click', '.action-btn.pause', function () {

        const $btn = $(this);
        isPaused = !$btn.hasClass('paused');

        if (isPaused) {
            clearTimeout(progressTimer);
            $btn.addClass('paused')
                .find('i')
                .attr('class', 'fa-solid fa-play');

            $innerModal.find('.progress-bar-inner').stop();

        } else {
            $btn.removeClass('paused')
                .find('i')
                .attr('class', 'fa-solid fa-pause');

            animateProgress();
        }
    });
});