$(document).ready(function() {
    $(window).on('ajaxInvalidField', function(event, field, fieldName, fieldMessages, isFirst) {

        var $form = $(field).closest('form');

        if (isFirst) {
            $('.invalid-feedback:not([data-validate-for])').remove();
            $form.find('[data-validate-for]').html('');
            $form.find('.is-invalid').removeClass('is-invalid');
        }

        $(field).addClass('is-invalid');

        var $validationContainer = $form.find('[data-validate-for="' + fieldName + '"]');

        if ($validationContainer.length === 0) {
            $('<div class="invalid-feedback">' + fieldMessages[0] + '</div>').insertAfter($(field));

            return;
        }

        $validationContainer.addClass('invalid-feedback').html(fieldMessages[0]);
    });

    $(document).on('ajaxPromise', '[data-request]', function() {
        var $form = $(this).closest('form');
        $form.find('.is-invalid').removeClass('is-invalid');
        $form.find('.invalid-feedback:not([data-validate-for])').remove();
        $form.find('[data-validate-for]').html('');
    });
});

/**
 * This function will be called when a new DOM element is created on the page, either at page load
 * or when the AJAX framework adds something to the page.
 */
function initNewElementComponents($updatedElement) {
    function initComponents(selector, callback) {
        $updatedElement
            .find(selector)
            .filter(function () {
                return !$(this).closest('[data-no-init]').length;
            })
            .each(callback);
    }

    // Tooltips
    initComponents('[data-bs-toggle="tooltip"]', function() {
       new bootstrap.Tooltip(this);
    });

    /*
     * Simple wysiwyg editor
     * usage: <textarea name="content" data-editor></textarea>
     */
    //initComponents('[data-editor]', function() {
    //    $(this).summernote({
    //        disableDragAndDrop: true,
    //        minHeight: 150,
    //        cleaner: {enabled: true},
    //        toolbar: [
    //            ['style', ['bold', 'italic', 'underline', 'clear']],
    //            ['font', ['strikethrough', 'superscript', 'subscript']],
    //            ['link', ['link']],
    //            ['para', ['ul', 'ol']],
    //            ['undo', ['undo', 'redo']]
    //        ],
    //    });
    //});
}

$(function () {
    /**
     * Initialize custom elements
     */
    initNewElementComponents($(document));

    /**
     * Reinitialize elements that have been updated by an ajax partial refresh
     */
    $(document).on('ajaxUpdate', function (event, context, data, status, xhr) {
        initNewElementComponents($(event.target));
    });

    // Menu
    $('[data-mobile-menu-toggle]').on('click', function (e) {
        $('body').toggleClass('menu-open');
        e.stopPropagation();
        e.preventDefault();
    });
    $(document).on('click', function (e) {
        if ($(e.target).closest('[data-mobile-menu-container]').length === 0) {
            $('body').removeClass('menu-open');
        }
    });
    $('.drop-menu ').on('mouseleave', function (e) {
        if ($(document.activeElement).closest('.drop-menu').length > 0) {
            document.activeElement.blur();
        }
    });

    // Open/close sub-menu entries in mobile version
    (function () {
        var $mobileMenu = $('.mobile-menu');

        function toggleElement(element) {
            $mobileMenu.find('.menu-link').each(function (i, item) {
                var collapseElement = $(item).siblings('.collapse').get(0);

                if (collapseElement && !$.contains(item.parentElement, element)) {
                    bootstrap.Collapse.getOrCreateInstance(collapseElement, { toggle: false }).hide();
                }
            });

            var collapseElement = $(element).siblings('.collapse').get(0);

            if (collapseElement) {
                bootstrap.Collapse.getOrCreateInstance(collapseElement, { toggle: false }).toggle();
            }
        }

        $mobileMenu.find('.menu-link')
            .on('click', function () {
                toggleElement(this);
            })
            .on('keydown', function (e) {
                if (e.key === 'Space') {
                    e.preventDefault();
                    toggleElement(this);
                }
            });

        $mobileMenu.find('.collapse')
            .on('hide.bs.collapse', function () {
                $(this).closest('.drop-menu').removeClass('open');
            })
            .on('show.bs.collapse', function () {
                $(this).closest('.drop-menu').addClass('open');
            });
    })();

    $('.image-link').magnificPopup({type:'image'});
    $('.carousel-inner').each(function() {
        $(this).magnificPopup({
            delegate: '.carousel-item',
            type: 'image',
            gallery: {
                enabled:true
            },
            callbacks: {
                elementParse: function (item) {
                    item.src = item.el[0].children[0].src;
                }
            }
        });
    });

    $('#select-category.form-select').on('change', function () {
        let url = window.location.href;
        let parts = url.split('/');

        if (parts.length >= 5) {
            parts[parts.length - 1] = `${this.value}#filtre-categories`;
        }

        let newUrl = parts.join('/');

        if (newUrl !== window.location.href) {
            window.location.href = newUrl;
        }
    });

    function initializeCarousel(carouselInnerId, block) {
        const container = document.getElementById(carouselInnerId);
        const buttons = document.querySelectorAll(`[data-carousel-id="${carouselInnerId}"]`);
        let targetLeft;

        if (!container || buttons.length === 0) {
            console.warn("Carousel initialization skipped: missing elements.");
            return;
        }

        buttons.forEach((button, index) => {
            button.addEventListener("click", function(e) {
                e.preventDefault();

                buttons.forEach(btn => btn.classList.remove("active"));
                button.classList.add("active");

                if (block == 'carousel') {
                    targetLeft = calculateCarouselOffsetLeft(index, container);
                } else {
                    targetLeft = getNavigationOffsetLeft(index);
                }

                container.scrollTo({
                    left: targetLeft,
                    behavior: "smooth"
                });
            });
        });
    }

    /**
     * Calculate 3 images width depending on parity of first image
     */
    function calculateCarouselOffsetLeft(index, container) {
        const items = container.querySelectorAll(".carousel-item");
        const groupWidthOdd = 1052;
        const groupWidthEven = 1126;

        let targetIndex = index * 3;

        if (targetIndex >= items.length) {
            targetIndex = items.length - 1;
        }

        const targetGroup = Math.floor(targetIndex / 3);

        let offsetLeft = 0;
        for (let i = 0; i < targetGroup; i++) {
            offsetLeft += i % 2 === 0 ? groupWidthOdd : groupWidthEven;
        }

        return targetIndex === 0 ? 0 : offsetLeft;
    }

    function getNavigationOffsetLeft(index) {
        switch (index) {
            case 0:
                return 100;
            
            case 1:
                return 530;
            
            case 2:
                return 620;
        }
    }

    $(".carousel-inner").each(function (_, carousel) {
        initializeCarousel(carousel.id, 'carousel');
    });
    
    $(".navigation-line").each(function (_, navigation) {
        initializeCarousel(navigation.id, 'navigation');
    });

    $(window).on('scroll', function () {       
        $('.showscroll').each(function () {
            let $this = $(this);
            var bottom_of_object = $(this).offset().top + 80;
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            if(bottom_of_window > bottom_of_object){
                $this.animate({
                    'opacity':'1',
                    'top':'0'
                }, 600);
            }
        }); 
    });

    $(window).trigger('scroll');

    $('.btn-share').each(function () {
        $(this).on('click', function () {
            const storage = document.createElement('textarea');

            storage.value = window.location.href;
            document.body.appendChild(storage);

            storage.select();
            storage.setSelectionRange(0, 99999);
            document.execCommand('copy');
            document.body.removeChild(storage);

            $(this).tooltip();
            $(this)
                .tooltip('dispose')
                .attr('data-bs-title', 'Copié!')
                .tooltip('toggle');

            setTimeout(() => {
                $(this)
                    .tooltip('dispose')
                    .attr('data-bs-title', 'Cliquer pour copier l\'URL')
                    .tooltip('hide');
            }, 2000);
        });
    });
});
