/**
 * ITSWEBER CMS – Modern Gallery Lightbox (v3.0.6)
 *
 * Shared lightbox component used across all themes.
 * Features:
 *   - Split-panel layout (image + info sidebar)
 *   - Album badge, title, description
 *   - Sharing: WhatsApp, TikTok, Pinterest, copy link
 *   - Prev/Next + keyboard + touch/swipe navigation
 *   - Fully accessible (ARIA, focus trap, screen reader)
 *   - Theme-adaptive via CSS custom properties
 *
 * © ITSWEBER – All rights reserved.
 */
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        var galleryGrid = document.querySelector('.gallery-images-grid');
        if (!galleryGrid) return;

        var items = Array.from(galleryGrid.querySelectorAll('.gallery-image-item'));
        if (items.length === 0) return;

        var currentIndex = 0;
        var touchStartX  = 0;
        var touchStartY  = 0;
        var openerItem   = null;

        // ─── Build modern lightbox DOM ──────────────────────────────────
        var lightbox = document.createElement('div');
        lightbox.className = 'glb';
        lightbox.setAttribute('role', 'dialog');
        lightbox.setAttribute('aria-modal', 'true');
        lightbox.setAttribute('aria-label', document.documentElement.lang === 'de' ? 'Bildansicht' : 'Image viewer');

        lightbox.innerHTML =
            '<div class="glb-backdrop"></div>' +
            '<div class="glb-container">' +
                // Close button
                '<button class="glb-close" aria-label="' + (document.documentElement.lang === 'de' ? 'Schließen (Esc)' : 'Close (Esc)') + '">' +
                    '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
                '</button>' +
                // Navigation
                '<button class="glb-nav glb-prev" aria-label="' + (document.documentElement.lang === 'de' ? 'Vorheriges Bild' : 'Previous image') + '">' +
                    '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>' +
                '</button>' +
                '<button class="glb-nav glb-next" aria-label="' + (document.documentElement.lang === 'de' ? 'Nächstes Bild' : 'Next image') + '">' +
                    '<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>' +
                '</button>' +
                // Main content area
                '<div class="glb-body">' +
                    // Image panel
                    '<div class="glb-image-panel">' +
                        '<img class="glb-img" src="" alt="" draggable="false">' +
                    '</div>' +
                    // Info sidebar
                    '<div class="glb-info-panel">' +
                        '<div class="glb-info-top">' +
                            '<span class="glb-badge"></span>' +
                            '<span class="glb-counter"></span>' +
                        '</div>' +
                        '<h3 class="glb-title"></h3>' +
                        '<p class="glb-description"></p>' +
                        '<div class="glb-share">' +
                            '<span class="glb-share-label">' + (document.documentElement.lang === 'de' ? 'Teilen' : 'Share') + '</span>' +
                            '<div class="glb-share-buttons">' +
                                '<button class="glb-share-btn" data-type="whatsapp" title="WhatsApp">' +
                                    '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>' +
                                '</button>' +
                                '<button class="glb-share-btn" data-type="tiktok" title="TikTok">' +
                                    '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M19.59 6.69a4.83 4.83 0 01-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 01-2.88 2.5 2.89 2.89 0 01-2.89-2.89 2.89 2.89 0 012.89-2.89c.28 0 .54.04.79.1v-3.5a6.37 6.37 0 00-.79-.05A6.34 6.34 0 003.15 15.2a6.34 6.34 0 0010.86-4.43V7.56a8.16 8.16 0 004.77 1.52v-3.4a4.85 4.85 0 01-.81.01h.62z"/></svg>' +
                                '</button>' +
                                '<button class="glb-share-btn" data-type="pinterest" title="Pinterest">' +
                                    '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0a12 12 0 00-4.37 23.17c-.1-.94-.2-2.4.04-3.44l1.4-5.96s-.36-.72-.36-1.78c0-1.66.97-2.9 2.17-2.9 1.02 0 1.52.77 1.52 1.69 0 1.03-.66 2.57-.99 3.99-.28 1.19.6 2.16 1.77 2.16 2.13 0 3.77-2.25 3.77-5.49 0-2.87-2.06-4.87-5.01-4.87-3.41 0-5.42 2.56-5.42 5.21 0 1.03.4 2.14.89 2.74a.36.36 0 01.08.34l-.33 1.36c-.05.22-.18.27-.41.16-1.55-.72-2.52-2.98-2.52-4.8 0-3.91 2.84-7.5 8.18-7.5 4.29 0 7.63 3.06 7.63 7.14 0 4.27-2.69 7.7-6.43 7.7-1.25 0-2.43-.65-2.84-1.42l-.77 2.94c-.28 1.08-1.04 2.43-1.55 3.26A12 12 0 1012 0z"/></svg>' +
                                '</button>' +
                                '<button class="glb-share-btn" data-type="copy" title="' + (document.documentElement.lang === 'de' ? 'Link kopieren' : 'Copy link') + '">' +
                                    '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>' +
                                '</button>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>' +
            '</div>';

        document.body.appendChild(lightbox);

        // ─── Cache DOM references ───────────────────────────────────────
        var dom = {
            backdrop:    lightbox.querySelector('.glb-backdrop'),
            container:   lightbox.querySelector('.glb-container'),
            close:       lightbox.querySelector('.glb-close'),
            prev:        lightbox.querySelector('.glb-prev'),
            next:        lightbox.querySelector('.glb-next'),
            img:         lightbox.querySelector('.glb-img'),
            badge:       lightbox.querySelector('.glb-badge'),
            counter:     lightbox.querySelector('.glb-counter'),
            title:       lightbox.querySelector('.glb-title'),
            description: lightbox.querySelector('.glb-description'),
            shareWrap:   lightbox.querySelector('.glb-share-buttons')
        };

        // ─── Update lightbox content ────────────────────────────────────
        function update() {
            var item   = items[currentIndex];
            var img    = item.querySelector('img');
            var imgAlt = img ? (img.getAttribute('alt') || '') : '';
            var caption = item.dataset.caption || imgAlt;
            var album   = item.dataset.album || '';
            var desc    = item.dataset.description || '';

            dom.img.src = item.dataset.src || (img ? img.src : '');
            dom.img.alt = imgAlt;

            // Badge (album name)
            if (album) {
                dom.badge.textContent = album;
                dom.badge.style.display = '';
            } else {
                dom.badge.style.display = 'none';
            }

            // Title
            dom.title.textContent = caption;
            dom.title.style.display = caption ? '' : 'none';

            // Description
            if (desc) {
                dom.description.textContent = desc;
                dom.description.style.display = '';
            } else {
                dom.description.style.display = 'none';
            }

            // Counter
            dom.counter.textContent = (currentIndex + 1) + ' / ' + items.length;

            // Nav state
            dom.prev.disabled = currentIndex === 0;
            dom.next.disabled = currentIndex === items.length - 1;
            dom.prev.style.opacity = currentIndex === 0 ? '0.3' : '';
            dom.next.style.opacity = currentIndex === items.length - 1 ? '0.3' : '';
        }

        // ─── Open / Close / Navigate ────────────────────────────────────
        function openAt(index) {
            openerItem = items[index];
            currentIndex = index;
            update();
            lightbox.classList.add('glb-open');
            document.body.style.overflow = 'hidden';
            dom.close.focus();
        }

        function close() {
            lightbox.classList.remove('glb-open');
            document.body.style.overflow = '';
            if (openerItem) openerItem.focus();
        }

        function prev() {
            if (currentIndex > 0) { currentIndex--; update(); }
        }

        function next() {
            if (currentIndex < items.length - 1) { currentIndex++; update(); }
        }

        // ─── Share handlers ─────────────────────────────────────────────
        dom.shareWrap.addEventListener('click', function (e) {
            var btn = e.target.closest('.glb-share-btn');
            if (!btn) return;

            var type    = btn.dataset.type;
            var url     = window.location.href;
            var caption = dom.title.textContent || document.title;
            var imgUrl  = dom.img.src || '';

            switch (type) {
                case 'whatsapp':
                    window.open(
                        'https://wa.me/?text=' + encodeURIComponent(caption + ' ' + url),
                        '_blank', 'noopener'
                    );
                    break;

                case 'tiktok':
                    // TikTok doesn't have a direct share-to URL; open profile or copy
                    window.open(
                        'https://www.tiktok.com/upload?url=' + encodeURIComponent(url),
                        '_blank', 'noopener'
                    );
                    break;

                case 'pinterest':
                    window.open(
                        'https://pinterest.com/pin/create/button/?url=' +
                            encodeURIComponent(url) +
                            '&media=' + encodeURIComponent(imgUrl) +
                            '&description=' + encodeURIComponent(caption),
                        '_blank', 'noopener'
                    );
                    break;

                case 'copy':
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(url).then(function () {
                            showCopyFeedback(btn);
                        });
                    } else {
                        var ta = document.createElement('textarea');
                        ta.value = url;
                        ta.style.cssText = 'position:fixed;opacity:0';
                        document.body.appendChild(ta);
                        ta.select();
                        document.execCommand('copy');
                        document.body.removeChild(ta);
                        showCopyFeedback(btn);
                    }
                    break;
            }
        });

        function showCopyFeedback(btn) {
            var orig = btn.innerHTML;
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
            btn.classList.add('glb-share-btn--copied');
            setTimeout(function () {
                btn.innerHTML = orig;
                btn.classList.remove('glb-share-btn--copied');
            }, 1800);
        }

        // ─── Attach events to thumbnails ────────────────────────────────
        items.forEach(function (item, idx) {
            item.style.cursor = 'pointer';
            item.addEventListener('click', function () { openAt(idx); });
            item.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    openAt(idx);
                }
            });
        });

        // ─── Lightbox controls ──────────────────────────────────────────
        dom.close.addEventListener('click', close);
        dom.prev.addEventListener('click', prev);
        dom.next.addEventListener('click', next);
        dom.backdrop.addEventListener('click', close);

        // Also close when clicking the container background (not children)
        dom.container.addEventListener('click', function (e) {
            if (e.target === dom.container) close();
        });

        // ─── Keyboard navigation ────────────────────────────────────────
        document.addEventListener('keydown', function (e) {
            if (!lightbox.classList.contains('glb-open')) return;
            switch (e.key) {
                case 'Escape':     close(); break;
                case 'ArrowLeft':  prev();  break;
                case 'ArrowRight': next();  break;
            }
        });

        // ─── Touch / swipe ──────────────────────────────────────────────
        lightbox.addEventListener('touchstart', function (e) {
            touchStartX = e.changedTouches[0].clientX;
            touchStartY = e.changedTouches[0].clientY;
        }, { passive: true });

        lightbox.addEventListener('touchend', function (e) {
            var dx = touchStartX - e.changedTouches[0].clientX;
            var dy = touchStartY - e.changedTouches[0].clientY;
            if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
                if (dx > 0) next(); else prev();
            }
        }, { passive: true });
    });
})();
