/**
 * Comment Image Boost JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    const config = window.ciboostCommentImages || {};

    function initLightbox() {
        if (config.lightboxEnabled === false) {
            return;
        }

        var links = Array.from(document.querySelectorAll('.ciboost-lightbox-trigger'));
        if (!links.length) {
            return;
        }

        var activeIndex = 0;
        var overlay = null;
        var image = null;
        var caption = null;

        function ensureOverlay() {
            if (overlay) {
                return;
            }
            overlay = document.createElement('div');
            overlay.className = 'ciboost-lightbox';
            overlay.innerHTML = '<button type="button" class="ciboost-lightbox-close" aria-label="Close">&times;</button>'
                + '<button type="button" class="ciboost-lightbox-prev" aria-label="Previous">&#8249;</button>'
                + '<figure class="ciboost-lightbox-figure"><img src="" alt=""><figcaption></figcaption></figure>'
                + '<button type="button" class="ciboost-lightbox-next" aria-label="Next">&#8250;</button>';
            document.body.appendChild(overlay);

            image = overlay.querySelector('img');
            caption = overlay.querySelector('figcaption');

            overlay.querySelector('.ciboost-lightbox-close').addEventListener('click', hide);
            overlay.querySelector('.ciboost-lightbox-prev').addEventListener('click', function() { show(activeIndex - 1); });
            overlay.querySelector('.ciboost-lightbox-next').addEventListener('click', function() { show(activeIndex + 1); });
            overlay.addEventListener('click', function(event) {
                if (event.target === overlay) {
                    hide();
                }
            });
            document.addEventListener('keydown', function(event) {
                if (!overlay || !overlay.classList.contains('is-open')) {
                    return;
                }
                if (event.key === 'Escape') {
                    hide();
                }
                if (event.key === 'ArrowLeft') {
                    show(activeIndex - 1);
                }
                if (event.key === 'ArrowRight') {
                    show(activeIndex + 1);
                }
            });
        }

        function show(index) {
            ensureOverlay();
            activeIndex = (index + links.length) % links.length;
            var link = links[activeIndex];
            var img = link.querySelector('img');
            image.src = link.href;
            image.alt = img ? img.alt : '';
            caption.textContent = link.getAttribute('data-ciboost-caption') || image.alt || '';
            caption.hidden = caption.textContent === '';
            overlay.classList.add('is-open');
            document.body.classList.add('ciboost-lightbox-open');
        }

        function hide() {
            if (!overlay) {
                return;
            }
            overlay.classList.remove('is-open');
            document.body.classList.remove('ciboost-lightbox-open');
            image.src = '';
        }

        links.forEach(function(link, index) {
            link.addEventListener('click', function(event) {
                event.preventDefault();
                show(index);
            });
        });
    }

    function initCommentForm() {
        const form = document.querySelector('#respond form');
        const imageArea = document.querySelector('.ciboost-comment-form-image');
        const imageInput = document.querySelector('.ciboost-comment-image-input');

        if (!form || !imageArea || !imageInput) {
            return;
        }

        form.setAttribute('enctype', 'multipart/form-data');
        imageArea.style.setProperty('--ciboost-preview-size', (config.previewSize || 120) + 'px');

        let dragCounter = 0;

        function getValidMimeTypes() {
            const formats = config.allowedFormats || ['jpg', 'jpeg', 'png'];
            const mimeMap = {
                jpg: 'image/jpeg',
                jpeg: 'image/jpeg',
                png: 'image/png',
                webp: 'image/webp',
                avif: 'image/avif'
            };

            return formats
                .map(function(format) { return mimeMap[format]; })
                .filter(function(type, index, list) { return type && list.indexOf(type) === index; });
        }

        function syncCaptionIndexes(container) {
            Array.from(container.querySelectorAll('.ciboost-image-preview')).forEach(function(preview, index) {
                preview.setAttribute('data-index', index);
                const input = preview.querySelector('.ciboost-preview-caption');
                if (input) {
                    input.name = 'ciboost_comment_image_caption[]';
                }
            });
        }

        function removeFileFromInput(index) {
            const dt = new DataTransfer();
            Array.from(imageInput.files).forEach(function(file, fileIndex) {
                if (fileIndex !== index) {
                    dt.items.add(file);
                }
            });
            imageInput.files = dt.files;
        }

        function showPreviews(files) {
            const existingContainer = imageArea.querySelector('.ciboost-previews-container');
            if (existingContainer) {
                existingContainer.remove();
            }

            const container = document.createElement('div');
            container.className = 'ciboost-previews-container';
            imageArea.appendChild(container);

            Array.from(files).forEach(function(file, index) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const preview = document.createElement('div');
                    preview.className = 'ciboost-image-preview';
                    preview.setAttribute('data-index', index);
                    preview.innerHTML = `
                        <img src="${event.target.result}" alt="Preview ${index + 1}">
                        <button type="button" class="ciboost-remove-image" title="Remove image">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M18 6L6 18M6 6l12 12"/>
                            </svg>
                        </button>
                    `;

                    if (config.captionsEnabled) {
                        const caption = document.createElement('input');
                        caption.type = 'text';
                        caption.name = 'ciboost_comment_image_caption[]';
                        caption.maxLength = 160;
                        caption.className = 'ciboost-preview-caption';
                        caption.placeholder = config.captionPlaceholder || 'Add a short caption';
                        preview.appendChild(caption);
                    }

                    container.appendChild(preview);

                    preview.querySelector('.ciboost-remove-image').addEventListener('click', function() {
                        const currentIndex = parseInt(preview.getAttribute('data-index'), 10);
                        removeFileFromInput(currentIndex);
                        preview.remove();
                        syncCaptionIndexes(container);

                        if (container.children.length === 0) {
                            container.remove();
                            imageInput.value = '';
                        }
                    });
                };
                reader.readAsDataURL(file);
            });
        }

        function handleDrop(event) {
            event.preventDefault();
            event.stopPropagation();

            const files = event.dataTransfer.files;
            if (files.length > 0) {
                const validTypes = getValidMimeTypes();
                const selectedFiles = config.allowMultiple ? Array.from(files) : [files[0]];
                const allValid = selectedFiles.every(function(file) {
                    return validTypes.includes(file.type);
                });

                if (allValid) {
                    const dt = new DataTransfer();
                    selectedFiles.forEach(function(file) { dt.items.add(file); });
                    imageInput.files = dt.files;
                    showPreviews(dt.files);
                } else {
                    alert(config.invalidFormatMsg || 'Invalid file format.');
                }
            }

            dragCounter = 0;
            imageArea.classList.remove('ciboost-dragenter');
        }

        imageInput.addEventListener('change', function() {
            if (this.files && this.files.length > 0) {
                showPreviews(this.files);
            }
        });

        imageArea.addEventListener('dragenter', function(event) {
            event.preventDefault();
            event.stopPropagation();
            dragCounter++;
            imageArea.classList.add('ciboost-dragenter');
        });
        imageArea.addEventListener('dragover', function(event) {
            event.preventDefault();
            event.stopPropagation();
        });
        imageArea.addEventListener('dragleave', function(event) {
            event.preventDefault();
            event.stopPropagation();
            dragCounter--;
            if (dragCounter === 0) {
                imageArea.classList.remove('ciboost-dragenter');
            }
        });
        imageArea.addEventListener('drop', handleDrop);
    }

    function initCarousels() {
        var wrappers = document.querySelectorAll('.ciboost-carousel-wrapper');
        wrappers.forEach(function(wrapper) {
            var gallery = wrapper.querySelector('.ciboost-gallery-layout-carousel');
            var prev = wrapper.querySelector('.ciboost-carousel-prev');
            var next = wrapper.querySelector('.ciboost-carousel-next');
            if (!gallery || !prev || !next) {
                return;
            }

            function getScrollAmount() {
                var item = gallery.querySelector('.ciboost-gallery-item');
                return item ? item.offsetWidth + 14 : 280;
            }

            function updateButtons() {
                prev.disabled = gallery.scrollLeft <= 0;
                next.disabled = gallery.scrollLeft + gallery.offsetWidth >= gallery.scrollWidth - 1;
            }

            prev.addEventListener('click', function() {
                gallery.scrollBy({ left: -getScrollAmount(), behavior: 'smooth' });
            });
            next.addEventListener('click', function() {
                gallery.scrollBy({ left: getScrollAmount(), behavior: 'smooth' });
            });
            gallery.addEventListener('scroll', updateButtons);
            updateButtons();
        });
    }

    initCommentForm();
    try { initLightbox(); } catch (e) { /* lightbox failed; form still works */ }
    try { initCarousels(); } catch (e) { /* carousel arrows failed */ }
});
