//JS for header media scroll down button

let scrollDownBtn = document.querySelector('.scroll-down')

if (scrollDownBtn !== null) {
    scrollDownBtn.addEventListener('click', function () {
        let sections = document.querySelectorAll('.wp-block-section')
        let firstSection = sections[1].offsetTop;
        window.scrollTo({
            top: firstSection,
            behavior: 'smooth'
        });
    })
}

// ADD CUSTOM CSS FOR SHOWING CURRENT_MENU_ITEM CLASS

document.body.querySelectorAll('.wp-block-navigation').forEach(function (navBlock) {
    if (navBlock !== null) {
        navBlock.querySelectorAll('[href="' + window.location.href + '"]').forEach(function (navActiveLink) {
            navActiveLink.parentNode.classList.add('current-nav-item');
        });
    }
});

// sticky playlist background changes on scroll
let stickyElement = document.querySelector('.sticky-playlist');
if (stickyElement !== null) {
    window.addEventListener('scroll', function () {
        if (window.scrollY > 0) {
            stickyElement.classList.add('scrolled');
        } else {
            stickyElement.classList.remove('scrolled');
        }
    });
}


// play icon text rotate
document.addEventListener('DOMContentLoaded', function () {
    // Find the rotating text element
    const rotatingText = document.querySelector('.wp-rotating-text');

    if (rotatingText) {
        // Get the text content and replace * with ★
        const text = rotatingText.textContent.replace(/\*/g, '★');

        // Create circular text container
        const circularContainer = document.createElement('div');
        circularContainer.className = 'circular-text-container';

        // Split text into characters
        const chars = text.split('');
        const angleStep = 360 / chars.length;

        // Create a span for each character
        chars.forEach((char, i) => {
            const span = document.createElement('span');
            span.className = 'letter';
            span.textContent = char;
            span.style.transform = `rotate(${i * angleStep}deg)`;
            circularContainer.appendChild(span);
        });

        // Insert the circular text after the play button
        const playButton = document.querySelector('.wp-play-button');
        if (playButton) {
            playButton.appendChild(circularContainer);
        }
    }
});



//  FOR HEADER PRODUCT SEARCH

const pfsearchInput = document.querySelector('.wp-header-right .search-product input[type="search"]');
const pfmobileIcon = document.querySelector('.wp-mobile-icon-menu');
const pfsearchCont = document.querySelectorAll('.wp-header-right');
const pfsearchDummy = document.querySelector('.dummy-icon .wp-block-search__button');
const pfsearchWrap = document.querySelector('.wp-header-right .search-product');
const pfShowHandler = (e) => {
    e.preventDefault();
    let pfbody = document.body;
    pfbody.classList.toggle('search-toggle');
}
if (pfsearchCont !== null) {
    pfsearchCont.forEach((item) => {
        let pfsearchBtn = document.querySelectorAll('.dummy-icon .wp-block-search__button')
        pfsearchBtn.forEach((btn) => {
            btn.addEventListener('click', pfShowHandler)
        })
    })
    if (pfmobileIcon !== null && pfsearchCont !== null && pfsearchWrap !== null && pfsearchDummy !== null) {
        document.addEventListener('click', function (e) {
            if (!pfsearchWrap.contains(e.target) && !pfsearchDummy.contains(e.target) && !pfmobileIcon.contains(e.target)) {
                let pfbody = document.body;
                pfbody.classList.remove('search-toggle')
            }
        }
        )
    }
}

// Header Search Show/Hide js //

let searchContainer = document.querySelectorAll('.wp-primary-search');
searchContainer.forEach((searchForm) => {
    let body = document.body;
    if (searchForm !== null) {
        let toggleIcon = searchForm.querySelector('.wp-search-toggle-container')
        let searchInnerContainer = searchForm.querySelector('.wp-search-container')
        let searchInput = searchForm.querySelector('.wp-block-search__input')
        let fseSearch = document.querySelectorAll('.search-controller .svg, .social-controller .svg')
        let body = document.body;

        fseSearch.forEach((searchButton) => {
            searchButton.addEventListener('click', function () {
                console.log('clicked')
                body.classList.remove('show-search')
                searchForm.classList.remove('toggled-on')
            })
        })

        toggleIcon.addEventListener('click', function () {
            searchForm.classList.toggle('toggled-on')
            body.classList.toggle('show-search')
            searchInput.focus()
        })

        document.addEventListener('click', function (e) {
            if (!searchInput.contains(e.target) && !searchInnerContainer.contains(e.target) && !toggleIcon.contains(e.target) && searchForm.classList.contains('toggled-on')) {
                searchForm.classList.remove('toggled-on')
                body.classList.remove('show-search')
            }
        })
    }
})


// Before after image js
document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".wp-before-after-block").forEach(container => {
        const afterFigure = container.querySelector(".wp-after-image");
        const afterImage = afterFigure?.querySelector("img");

        // Create and inject slider if missing
        let slider = container.querySelector(".ba-slider");
        if (!slider) {
            slider = document.createElement("div");
            slider.className = "ba-slider";

            // Create single span inside slider
            const span = document.createElement("span");
            span.className = "ba-slider-handle"; // or whatever class you want

            slider.appendChild(span);
            container.appendChild(slider);
        }

        // Initialize clip path of after image
        if (afterImage) {
            afterImage.style.clipPath = "inset(0 50% 0 0)";
        }

        const onMove = (e) => {
            const rect = container.getBoundingClientRect();
            const x = ((e.touches ? e.touches[0].clientX : e.clientX) - rect.left) / rect.width;
            const percent = Math.max(0, Math.min(1, x));
            if (afterImage) {
                afterImage.style.clipPath = `inset(0 ${(1 - percent) * 100}% 0 0)`;
            }
            slider.style.left = `${percent * 100}%`;
        };

        const onDown = () => {
            window.addEventListener("mousemove", onMove);
            window.addEventListener("touchmove", onMove);
            window.addEventListener("mouseup", onUp);
            window.addEventListener("touchend", onUp);
        };

        const onUp = () => {
            window.removeEventListener("mousemove", onMove);
            window.removeEventListener("touchmove", onMove);
            window.removeEventListener("mouseup", onUp);
            window.removeEventListener("touchend", onUp);
        };

        slider.addEventListener("mousedown", onDown);
        slider.addEventListener("touchstart", onDown);
    });
});




// DUPLICATE ITEMS ON TEXT CAROUSEL

const photoFocusLoopScroll = () => {
    const loopWrapper = document.querySelector('.text-carousel-col');
    if (loopWrapper !== null) {
        const loopContent = document.querySelectorAll('.text-carousel-col .wp-block-column');
        const body = document.body;

        // Clone each image div and append with the "cloned" class
        loopContent.forEach((loopItem) => {
            const clone = loopItem.cloneNode(true);
            clone.classList.add('cloned');
            loopWrapper.appendChild(clone);
        });

        let isPaused = false;
        let firstCycleComplete = false;

        loopWrapper.addEventListener('mouseover', () => {
            isPaused = true;
        });

        loopWrapper.addEventListener('mouseout', () => {
            isPaused = false;
        });

        // Calculate the total width of all cloned items including flex gap
        const flexGap = getComputedStyle(loopWrapper).gap; // Get the flex gap
        const totalClonedWidth = Array.from(loopWrapper.querySelectorAll('.cloned')).reduce((acc, clonedItem, index) => {
            return acc + clonedItem.offsetWidth + parseFloat(flexGap);
        }, 0);

        function photoFocusScrollContent() {
            if (!isPaused) {
                const currentLeft = parseInt(loopWrapper.style.left) || 0;
                const totalWidth = totalClonedWidth + body.offsetWidth;

                loopWrapper.style.left = currentLeft - 1 + 'px';

                // Check if the first child of the cloned class div touches the starting position of the loopWrapper div
                if (currentLeft <= -totalClonedWidth && firstCycleComplete) {
                    loopWrapper.style.left = '0';
                }

                // Mark the first cycle as complete after one complete cycle of scrolling
                if (currentLeft <= -totalWidth + body.offsetWidth) {
                    firstCycleComplete = true;
                }
            }
        }

        setInterval(photoFocusScrollContent, 40);
    }
};


window.addEventListener('load', photoFocusLoopScroll())
window.addEventListener('resize', photoFocusLoopScroll())
