import GLightbox from 'glightbox';

const popupSelector = '.modal-trigger, .glightbox';

const initPopups = () => {
    galleries('.glightbox');
    modals('.modal-trigger');
};

function galleries (selector) {
    GLightbox({
        selector: selector,
        loop: true,
        zoomable: false,
        openEffect: 'fade',
        closeEffect: 'fade'
    });
}

function modals (triggerSelector) {
    const modal = GLightbox({
        selector: triggerSelector,
        openEffect: 'fade',
        closeEffect: 'fade',
        skin: 'clean glightbox-modal',
        height: 'auto',
        width: 'auto',
        closeButton: false
    });

    modal.on('slide_after_load', (event) => {
        const slide = event.slideNode;
        const closeBtn = slide.querySelector('.modal__close');
        const prevBtn = slide.querySelector('.modal__prev');
        const nextBtn = slide.querySelector('.modal__next');

        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                modal.close();
            });
        }
        if (prevBtn) {
            prevBtn.addEventListener('click', () => {
                modal.prevSlide();
            });
        }
        if (nextBtn) {
            nextBtn.addEventListener('click', () => {
                modal.nextSlide();
            });
        }
    });

    modal.on('open', () => {
        const container = document.querySelector('.glightbox-container');
        container.addEventListener('click', (e) => {
            const modalEl = container.querySelector('.current .modal');
            const targetClass = e.target.classList;
            if (e.target !== modalEl && !modalEl.contains(e.target) && !(targetClass.contains('modal__btn-icon') || targetClass.contains('modal__btn'))) {
                modal.close();
            }
        });
    });
}

export { popupSelector, initPopups };
