import './bootstrap';
//import 'resources/js/app.js';
import '@fortawesome/fontawesome-free/css/all.min.css';



document.addEventListener('DOMContentLoaded', function () {

    imageLoading()
    scrollOpenCover();
    reset() // reset everrything to ensure smooth
    sessionStorage.setItem("initial-load", "true"); // will be used by click event

    let rsvpBtn = document.getElementById("rsvp-button");
    rsvpBtn.addEventListener('click', function(){
        this.classList.remove("animate__flash");
    })

    let scrollerInd = document.getElementById("scroller");

    setTimeout(()=>{
        window.addEventListener('scroll', function(){
            scrollerInd.remove();
        })
    },1000)
});


document.addEventListener('click', function () {

    let initLoad = sessionStorage.getItem("initial-load")

    let pointer = document.getElementById("pointer")
    if(pointer) pointer.remove()

    // parts is intro cover
    let parts = document.getElementsByClassName("part");
    for (let part of parts) {
        part.classList.add("shadow-lg")
    }

    // the intro - only done once and
    if (initLoad == "true") {
        playMusic();

        let leftCover = document.querySelector(".dummy-cover .left-dummy");
        let rightCover = document.querySelector(".dummy-cover .right-dummy");
        leftCover.classList.add("to-left-animation")
        rightCover.classList.add("to-right-animation")
        setTimeout(()=>{
            //dummy-cover
            let parts = document.querySelectorAll(".dummy-cover .part");
            for (let part of parts) {
                part.remove("hidden")
            }

            let body = document.querySelector("body");
            body.classList.remove("no-scroll");

        },2500)

        sessionStorage.removeItem("initial-load")
    }

    setTimeout(() => {
        eventCountdown();
        let petalOverlay = document.getElementById("petalOverlay");
        petalOverlay.classList.remove("hidden");
    }, 2000)

});

// to ensure all images is loaded before starting animation and gimmick
function imageLoading() {
    const images = document.querySelectorAll("img");
    let loadedCount = 0;
    const totalImages = images.length;

    images.forEach(image => {
        if (image.complete) {
            loadedCount++;
        } else {
            image.addEventListener("load", () => {
                loadedCount++;
                checkAllImagesLoaded();
            });
            image.addEventListener("error", () => {
                loadedCount++;
                checkAllImagesLoaded();
            });
        }
    });

    function checkAllImagesLoaded() {

        if (loadedCount === totalImages) {
            let loading = document.getElementById("loading");
            loading.remove();
            // parts is intro cover
            let parts = document.getElementsByClassName("part");
            for (let part of parts) {
                part.classList.remove("hidden")
            }

            let pointer = document.getElementById("pointer")
            setTimeout(() => {
                pointer.classList.remove("hidden")
            }, 1500);
        }
    }

    //somehow the server work so fast, script doesn't have much time to set the load eventlistener
    //thus we check here, to ensure checkAllImagesLoaded run
    checkAllImagesLoaded();
}

// enable open close cover
function scrollOpenCover() {
    var partLeftPos = 0;
    var partRightPos = 0;

    function updatePositions() {
        var distance = $(window).scrollTop() * 2;
        var left = partLeftPos - distance;
        var right = partRightPos - distance;

        $('.left').css('left', left + "px");
        $('.right').css('right', right + "px");

        //Calculate boundaries
        var leftPartRightEdge = $('.left').offset().left + $('.left').outerWidth();

        //Check if both parts are completely off-screen
        var isLeftOffScreen = leftPartRightEdge <= 0;

        //Toggle visibility and z-index
        if (isLeftOffScreen && left < 0) {
            $('.parent').removeClass('z-30');
        } else {
            $('.parent').addClass('z-30');
        }
    }

    //Initial positions update
    updatePositions();

    //Listen to scroll events using requestAnimationFrame for smooth animation
    var ticking = false;
    $(window).scroll(function () {
        if (!ticking) {
            window.requestAnimationFrame(function () {
                updatePositions();
                ticking = false;
            });
        }
        ticking = true;
    });
}

function reset() {

    // reset to top
    let body = document.querySelector("body");
    window.scrollTo(0, document.body.scrollHeight * 0.05);
    body.classList.add("no-scroll");

}

function playMusic() {
    var audioElement = document.getElementById('player');
    var hasPlayed = false;
    if (!hasPlayed) {
        console.log('play')
        var playPromise = audioElement.play();

        if (playPromise !== undefined) {
            playPromise.then(function () {
                // Automatic playback started!
                hasPlayed = true; // Prevent further attempts to play
            }).catch(function (error) {
                // Automatic playback failed.
                console.log('Autoplay failed: ' + error);
            });
        }
    }
}

function eventCountdown() {

    //Countdown date (adjust this date to your desired countdown target)
    const countdownDate = new Date('2024-08-17T11:00:00').getTime();

    //Update the countdown every second
    const countdownElement = document.getElementById('countdown');
    const countdownTimer = setInterval(() => {
        //Get the current date and time
        const now = new Date().getTime();

        //Calculate the time remaining
        const distance = countdownDate - now;

        //Calculate days, hours, minutes, and seconds
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        //Format the countdown into a string
        const countdownHTML = `
        <div class="flex flex-col">
            <div class="flex gap-8 justify-center">
                <div class="font-medium text-gray-500">${days}</div>
                <div class="font-medium text-gray-500">:</div>
                <div class="font-medium text-gray-500">${hours.toString().padStart(2, '0')}</div>
                <div class="font-medium text-gray-500">:</div>
                <div class="font-medium text-gray-500">${minutes.toString().padStart(2, '0')}</div>
                <div class="font-medium text-gray-500">:</div>
                <div class="font-medium text-gray-500">${seconds.toString().padStart(2, '0')}</div>
            </div>
            <div class="flex gap-14 justify-center">
                <div class="font-medium text-gray-600">Hari</div>
                <div class="font-medium text-gray-600">Jam</div>
                <div class="font-medium text-gray-600">Minit</div>
                <div class="font-medium text-gray-600">Saat</div>
            </div>
        </div>
    `;

        //Display the countdown in the element
        countdownElement.innerHTML = countdownHTML;

        //If the countdown is over, clear the timer and display a message
        if (distance < 0) {
            clearInterval(countdownTimer);
            countdownElement.innerHTML = 'Majlis berlangsung';
        }
    }, 1000); // Update every second (1000 milliseconds)
}


const observerOptions = {
    root: null,
    rootMargin: '0px',
    threshold: 0.1
};

const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('fade-in');
            observer.unobserve(entry.target);
        }
    });
}, observerOptions);

document.querySelectorAll('.fade-element').forEach(element => {
    observer.observe(element);
});
