var $ = jQuery.noConflict();
class ClassWatcher {

    constructor(targetNode, classToWatch, classAddedCallback, classRemovedCallback) {
        this.targetNode = targetNode
        this.classToWatch = classToWatch
        this.classAddedCallback = classAddedCallback
        this.classRemovedCallback = classRemovedCallback
        this.observer = null
        this.lastClassState = targetNode.classList.contains(this.classToWatch)

        this.init()
    }

    init() {
        this.observer = new MutationObserver(this.mutationCallback)
        this.observe()
    }

    observe() {
        this.observer.observe(this.targetNode, { attributes: true })
    }

    disconnect() {
        this.observer.disconnect()
    }

    mutationCallback = mutationsList => {
        for(let mutation of mutationsList) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                let currentClassState = mutation.target.classList.contains(this.classToWatch)
                if(this.lastClassState !== currentClassState) {
                    this.lastClassState = currentClassState
                    if(currentClassState) {
                        this.classAddedCallback()
                    }
                    else {
                        this.classRemovedCallback()
                    }
                }
            }
        }
    }
}
var observeDOM = (function(){
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

    return function( obj, callback ){
        if( !obj || obj.nodeType !== 1 ) return;

        if( MutationObserver ){
            // define a new observer
            var mutationObserver = new MutationObserver(callback)

            // have the observer observe for changes in children
            mutationObserver.observe( obj, { childList:true, subtree:true })
            return mutationObserver
        }

        // browser support fallback
        else if( window.addEventListener ){
            obj.addEventListener('DOMNodeInserted', callback, false)
            obj.addEventListener('DOMNodeRemoved', callback, false)
        }
    }
})()
//on load
function calculateTimeLeft(convertedDatetime) {
    // Parse the converted datetime string
    var targetDate = new Date(convertedDatetime);

    // Get the current date and time
    var now = new Date();

    // Calculate the difference in milliseconds
    var difference = targetDate - now;

    if (difference < 0) {
        return "Time has already passed";
    }

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

    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    if (seconds < 10) {
        seconds = '0' + seconds;
    }

    // Format the remaining time
    var timeLeft = days + " dni, " + hours + ":" + minutes + ":" + seconds;

    return timeLeft;
}
function convertDatetime(preorderDatetime) {
    // Split the datetime string into date and time parts
    var parts = preorderDatetime.split(', ');
    var datePart = parts[0];
    var timePart = parts[1];

    // Split the date part into day, month, and year
    var dateParts = datePart.split('.');
    var day = dateParts[0];
    var month = dateParts[1];
    var year = dateParts[2];

    // Split the time part into hours and minutes
    var timeParts = timePart.split(':');
    var hours = timeParts[0];
    var minutes = timeParts[1];

    // Create a new Date object with the parsed values
    var dt = new Date(year, month - 1, day, hours, minutes);

    // Format the date object to the desired format
    var formattedDatetime = dt.toISOString();

    return formattedDatetime;
}
$(document).ready(function () {
    //if on the product page
    var priceChanged = false;
    if ($('body').hasClass('single-product')) {
        var quantityInput = $('input.input-text.qty');
        var addToCartButton = $('span.addToCartButton .buttonInner .priceCustom');
        var quantityCounter = $('.addToCartBox .quantityCounter');
        //create quantity minus and plus buttons and append and prepend them into .addToCartButton .buttonInner that will increment and decrement the quantity input starting at 1
        addToCartButton.before('<button type="button" class="minus-btn">-</button>');
        addToCartButton.after('<button type="button" class="plus-btn">+</button>');
        //wrap addToCartButton and minus and plus buttons in a div wrapper
        addToCartButton.add($('.minus-btn')).add($('.plus-btn')).wrapAll('<div class="quantity-wrapper"></div>');
        //on click of the minus button
        $('.minus-btn').click(function () {
            //if the quantity is greater than 1
            if (quantityInput.val() > 1) {
                //decrement the quantity
                quantityInput.val(parseInt(quantityInput.val()) - 1);
                quantityCounter.text(quantityInput.val());
            }
            multiplyThePrice();
        });
        //on click of the plus button
        $('.plus-btn').click(function () {
            //increment the quantity
            quantityInput.val(parseInt(quantityInput.val()) + 1);
            quantityCounter.text(quantityInput.val());
            multiplyThePrice();
        });
        function multiplyThePrice() {
            if (priceChanged === false) {
                //save the original price to localStorage as originalPrice + the index of the price
                $('.woocommerce-Price-amount').each(function () {
                    localStorage.setItem('originalPrice' + $('.woocommerce-Price-amount').index(this), $(this).text());
                });
                priceChanged = true;
            }
            $('.woocommerce-Price-amount').each(function () {
                //get the original price from localStorage if it exists and set it to the price variable
                if (localStorage.getItem('originalPrice' + $('.woocommerce-Price-amount').index(this))) {
                    var price = localStorage.getItem('originalPrice' + $('.woocommerce-Price-amount').index(this));
                } else {
                    var price = $(this).text();
                }
                var currencySymbol = $(this).find('.woocommerce-Price-currencySymbol').text();
                //get the price with regex to remove the currency symbol, take care to not remove the decimal point
                price = price.replace(currencySymbol, '');
                //convert the price to a number
                price = parseFloat(price.replace(',', '.'));

                //multiply the original price by the quantity, while respecting the price after decimal and add the currency symbol after
                $(this).html((price * quantityInput.val()).toFixed(2) + ' <span class="woocommerce-Price-currencySymbol">' + currencySymbol + '</span>');
            });
        }
        $('#pa_rozmiar').parent().addClass('select-wrapper');
        //add wrapper to select element inside select-wrapper
        $('#pa_rozmiar').wrap('<div class="select-outer"></div>');
        //get .label element that is a sibling of select-wrapper and add class to it
        $('.select-wrapper').parent().find('.label').addClass('select-label');
        $('.select-wrapper').parent().addClass('d-flex');
        //create element a with class sizesTable and text "Tabela rozmiarów" and append it after select-wrapper. Make it open an element #sizesTable on click in popup
        $('.select-wrapper').after('<a href="#" class="sizesTable">Tabela rozmiarów</a>');
        $('.sizesTable').click(function (e) {
            e.preventDefault();
            $('body').css('overflow', 'hidden');
            $('#sizesTablePopup').toggleClass('show');
        });
        $('#closePopup').click(function (e) {
            e.preventDefault();
            $('body').css('overflow', 'auto');
            $('#sizesTablePopup').removeClass('show');
        });
        //wrap .select-label and .select-wrapper in a div
        $('.select-label').add('.select-wrapper').wrapAll('<div class="d-flex"></div>');
        //cut .preorder-timer element and paste it to the woocommerce-product-gallery at the end
        setTimeout(function () {
            if ($('.preorder_timer_clock').attr('data-timer') === '' || $('.preorder_timer_clock').attr('data-timer') === undefined) {
                $('.preorder_timer').remove();
            } else {
                $('.preorder_timer').appendTo('.woocommerce-product-gallery');
                //if the preorder-timer element exists
                if ($('.preorder_timer').length) {
                    const preorderTimer = document.querySelectorAll('.preorder_timer_clock');
                    preorderTimer.forEach(timer => {
                        const preorderDatetime = timer.getAttribute('data-timer');
                        const convertedDatetime = convertDatetime(preorderDatetime);

                        // Display initial time left
                        timer.innerHTML = calculateTimeLeft(convertedDatetime);

                        // Update time left every minute
                        setInterval(function() {
                            const timeLeft = calculateTimeLeft(convertedDatetime);
                            timer.innerHTML = timeLeft;

                            if (timeLeft === "Time has already passed") {
                                clearInterval(updateInterval);
                            }
                        }, 1000); // Update every minute
                    });
                }
            }
        }, 1000);
    }
    function addFileInputListenerCheckout(productCount) {
        const fileInput = document.getElementById(`file${productCount}`);
        const fileButton = fileInput.nextElementSibling;

        fileInput.addEventListener('change', function(event) {
            const fileList = event.target.files;

            Array.from(fileList).forEach(file => {
                const p = document.createElement('p');
                p.textContent = file.name;
                p.style.marginBottom = '5px';
                fileButton.parentNode.insertBefore(p, fileButton.nextSibling);

                const removeButton = document.createElement('button');
                removeButton.classList.add('remove-button');
                removeButton.textContent = 'x';
                removeButton.addEventListener('click', function() {
                    fileInput.value = null;
                    p.parentNode.removeChild(p);
                    removeButton.parentNode.removeChild(removeButton);
                });

                p.appendChild(removeButton);
            });
            // Add save button if not already added
            if (!document.getElementById(`saveButton${productCount}`)) {
                const saveButton = document.createElement('button');
                saveButton.id = `saveButton${productCount}`;
                saveButton.classList.add('button', 'save-button');
                saveButton.style.padding = '10px';
                saveButton.style.marginLeft = '5px';
                saveButton.textContent = 'Zapisz';
                saveButton.addEventListener('click', function() {
                    uploadFilesCheckout(fileList);
                });
                fileButton.parentNode.insertBefore(saveButton, fileButton.nextSibling);
            }
        });
    }
    function uploadFilesCheckout(files) {
        const xhr = new XMLHttpRequest();
        const formData = new FormData();

        Array.from(files).forEach(file => {
            formData.append('files[]', file);
        });

        console.log('FormData:', formData); // Log FormData object for debugging

        xhr.open('POST', '/store/wp-json/api/v1/save_file');
        xhr.onload = function() {
            if (xhr.status === 200) {
                console.log('Files uploaded successfully.');
                // You can handle success response here
            } else {
                console.error('Upload failed. Status:', xhr.status);
                // You can handle failure response here
            }
        };
        xhr.onerror = function() {
            console.error('Error occurred during upload.');
            // You can handle upload error here
        };
        xhr.send(formData);
    }

    let uploadedInitiated = false;

    function woocommerceCheckoutFileUploader() {
        console.log('Ja sie uruchamiam');
        if (!uploadedInitiated && $('.wc-block-components-order-summary-item').length) {
            let productCount = 1;
            uploadedInitiated = true;
            $('.wc-block-components-order-summary-item').each(function () {
                var productName = $(this).find('.wc-block-components-product-name').text();
                $(this).after('<div class="file-input w-12/12"><input type="file" name="file' + productCount + '" id="file' + productCount + '"></div>');
                //make the input file multiple
                $('#file' + productCount).attr('multiple', 'multiple');
                //add styling to the file input
                $('#file' + productCount).css({
                    'display': 'none'
                });
                //create a button with the text "Wybierz plik" and append it after the input file
                $('#file' + productCount).after('<button type="button" class="file-button button" style="padding: 10px;">Dodaj pliki</button>');
                //on click of the button, click the input file
                $('.file-button').click(function () {
                    $(this).prev().click();
                });
                addFileInputListenerCheckout(productCount);

                productCount++;
            });
        }
    }

    function woocommerceCheckoutFileUploaderInit() {
        if ($('.wc-block-components-order-summary-item').length) {
            woocommerceCheckoutFileUploader();
        } else {
            const rootelem = document.getElementById('main');
            observeDOM( rootelem, function(m){
                woocommerceCheckoutFileUploader();
            });
        }
    }
    if ($('body').hasClass('woocommerce-checkout')) {
        //take every product in the cart and create an input type file with the label "Plik: " + the name of the product and append it to the #mainHeader .inner
        // woocommerceCheckoutFileUploaderInit();
    } else {
        function workOnBodyClassAddCheckout() {
            woocommerceCheckoutFileUploaderInit();
        }

        function workOnBodyClassRemovalCheckout() {}

        let targetNode = document.getElementsByTagName('body')[0];
        new ClassWatcher(targetNode, 'woocommerce-checkout', workOnBodyClassAddCheckout, workOnBodyClassRemovalCheckout);
    }
    //if on the checkout page or cart page
    /*setTimeout(function () {

    }, 1000);*/
});