(function () {
    document.querySelectorAll('.game-slider').forEach(function (slider) {
        slider.addEventListener('wheel', function (event) {
            if (Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
                slider.scrollLeft += event.deltaY;
                event.preventDefault();
            }
        }, { passive: false });
    });

    var activeLightbox = null;

    function initGallery(gallery) {
        var items = Array.prototype.slice.call(gallery.querySelectorAll('[data-gallery-item]'));
        var thumbs = Array.prototype.slice.call(gallery.querySelectorAll('[data-gallery-thumb]'));
        var current = Math.max(0, items.findIndex(function (item) { return item.classList.contains('is-active'); }));
        var startX = 0;
        var startY = 0;

        function show(index) {
            if (!items.length) return;
            current = (index + items.length) % items.length;
            items.forEach(function (item, itemIndex) {
                item.classList.toggle('is-active', itemIndex === current);
            });
            thumbs.forEach(function (thumb, thumbIndex) {
                thumb.classList.toggle('is-active', thumbIndex === current);
            });
        }

        function move(direction) {
            show(current + direction);
        }

        gallery.querySelectorAll('[data-gallery-prev]').forEach(function (button) {
            button.addEventListener('click', function () { move(-1); });
        });

        gallery.querySelectorAll('[data-gallery-next]').forEach(function (button) {
            button.addEventListener('click', function () { move(1); });
        });

        thumbs.forEach(function (thumb) {
            thumb.addEventListener('click', function () {
                show(Number(thumb.dataset.index || 0));
            });
        });

        gallery.querySelectorAll('[data-gallery-open]').forEach(function (button) {
            button.addEventListener('click', function () {
                openLightbox(items, current, show);
            });
        });

        gallery.addEventListener('touchstart', function (event) {
            if (!event.touches.length) return;
            startX = event.touches[0].clientX;
            startY = event.touches[0].clientY;
        }, { passive: true });

        gallery.addEventListener('touchend', function (event) {
            if (!event.changedTouches.length) return;
            var dx = event.changedTouches[0].clientX - startX;
            var dy = event.changedTouches[0].clientY - startY;
            if (Math.abs(dx) > 42 && Math.abs(dx) > Math.abs(dy)) {
                move(dx > 0 ? -1 : 1);
            }
        }, { passive: true });

        gallery.addEventListener('keydown', function (event) {
            if (event.key === 'ArrowLeft') move(-1);
            if (event.key === 'ArrowRight') move(1);
        });

        if (gallery.tabIndex < 0) gallery.tabIndex = 0;
        show(current);
    }

    function ensureLightbox() {
        var existing = document.querySelector('[data-gallery-lightbox]');
        if (existing) return existing;

        var lightbox = document.createElement('div');
        lightbox.className = 'gallery-lightbox';
        lightbox.hidden = true;
        lightbox.dataset.galleryLightbox = 'true';
        lightbox.innerHTML = '<div class="gallery-lightbox-bar"><strong class="gallery-lightbox-title" data-lightbox-title></strong><span class="gallery-lightbox-counter" data-lightbox-counter></span><div class="gallery-lightbox-actions"><button class="pill" type="button" data-lightbox-zoom-out aria-label="Uzaklastir">-</button><button class="pill" type="button" data-lightbox-reset aria-label="Sifirla">0</button><button class="pill" type="button" data-lightbox-zoom-in aria-label="Yakinlastir">+</button><button class="gallery-lightbox-close" type="button" data-lightbox-close aria-label="Kapat">&times;</button></div></div><button class="gallery-lightbox-nav prev" type="button" data-lightbox-prev aria-label="Onceki">&lsaquo;</button><button class="gallery-lightbox-nav next" type="button" data-lightbox-next aria-label="Sonraki">&rsaquo;</button><div class="gallery-lightbox-stage" data-lightbox-stage></div><div class="gallery-lightbox-thumbs" data-lightbox-thumbs></div>';
        document.body.appendChild(lightbox);

        lightbox.querySelector('[data-lightbox-close]').addEventListener('click', closeLightbox);
        lightbox.addEventListener('click', function (event) {
            if (event.target === lightbox) closeLightbox();
        });
        lightbox.querySelector('[data-lightbox-prev]').addEventListener('click', function () { renderLightbox(activeLightbox.index - 1); });
        lightbox.querySelector('[data-lightbox-next]').addEventListener('click', function () { renderLightbox(activeLightbox.index + 1); });
        lightbox.querySelector('[data-lightbox-zoom-in]').addEventListener('click', function () { zoomLightbox(.25); });
        lightbox.querySelector('[data-lightbox-zoom-out]').addEventListener('click', function () { zoomLightbox(-.25); });
        lightbox.querySelector('[data-lightbox-reset]').addEventListener('click', resetZoom);

        return lightbox;
    }

    function openLightbox(items, index, sync) {
        var lightbox = ensureLightbox();
        activeLightbox = {
            items: items,
            index: index || 0,
            lightbox: lightbox,
            scale: 1,
            x: 0,
            y: 0,
            hoverX: 0,
            image: null,
            dragging: false,
            dragX: 0,
            dragY: 0,
            startX: 0,
            startY: 0,
            startPanX: 0,
            startPanY: 0,
            moved: false,
            sync: sync
        };

        lightbox.hidden = false;
        document.body.classList.add('gallery-lightbox-open');
        renderThumbs();
        renderLightbox(activeLightbox.index);
    }

    function closeLightbox() {
        if (!activeLightbox) return;
        activeLightbox.lightbox.hidden = true;
        activeLightbox = null;
        document.body.classList.remove('gallery-lightbox-open');
    }

    function renderLightbox(index) {
        if (!activeLightbox || !activeLightbox.items.length) return;

        activeLightbox.index = (index + activeLightbox.items.length) % activeLightbox.items.length;
        resetZoom(false);

        var item = activeLightbox.items[activeLightbox.index];
        var stage = activeLightbox.lightbox.querySelector('[data-lightbox-stage]');
        var title = activeLightbox.lightbox.querySelector('[data-lightbox-title]');
        var counter = activeLightbox.lightbox.querySelector('[data-lightbox-counter]');
        var type = item.dataset.type || 'image';
        var src = item.dataset.src || '';

        title.textContent = item.dataset.label || '';
        counter.textContent = (activeLightbox.index + 1) + ' / ' + activeLightbox.items.length;
        stage.innerHTML = '';
        stage.onwheel = stage.onmousemove = stage.onmouseleave = null;
        stage.onpointerdown = stage.onpointermove = stage.onpointerup = stage.onpointercancel = null;
        activeLightbox.image = null;
        if (typeof activeLightbox.sync === 'function') {
            activeLightbox.sync(activeLightbox.index);
        }
        updateThumbs();

        if (type === 'video') {
            var iframe = document.createElement('iframe');
            iframe.src = src;
            iframe.allow = 'accelerometer; autoplay; encrypted-media; picture-in-picture';
            iframe.allowFullscreen = true;
            stage.appendChild(iframe);
            return;
        }

        if (type === 'model') {
            var viewer = document.createElement('model-viewer');
            viewer.src = src;
            viewer.setAttribute('camera-controls', '');
            viewer.setAttribute('auto-rotate', '');
            viewer.setAttribute('interaction-prompt', 'none');
            viewer.alt = item.dataset.label || '3D model';
            viewer.innerHTML = '<div class="gallery-model-fallback"><strong>3D model onizleme desteklenmiyor.</strong><p>Dosyayi dogrudan acabilirsin.</p><a class="pill" href="' + src + '" target="_blank" rel="noopener">Goruntule / Indir</a></div>';
            stage.appendChild(viewer);
            return;
        }

        var image = document.createElement('img');
        image.src = src;
        image.alt = item.dataset.label || '';
        stage.appendChild(image);
        activeLightbox.image = image;

        image.addEventListener('dblclick', function () {
            activeLightbox.scale = activeLightbox.scale > 1 ? 1 : 2;
            activeLightbox.x = 0;
            activeLightbox.y = 0;
            applyTransform();
        });

        stage.onwheel = function (event) {
            event.preventDefault();
            zoomLightbox(event.deltaY < 0 ? .18 : -.18);
        };

        stage.onmousemove = function (event) {
            if (!activeLightbox || activeLightbox.scale > 1 || activeLightbox.dragging) return;
            var rect = stage.getBoundingClientRect();
            activeLightbox.hoverX = ((event.clientX - rect.left) / Math.max(rect.width, 1) - .5) * 10;
            applyTransform();
        };

        stage.onmouseleave = function () {
            if (!activeLightbox || activeLightbox.scale > 1) return;
            activeLightbox.hoverX = 0;
            applyTransform();
        };

        stage.onpointerdown = function (event) {
            if (!activeLightbox || type !== 'image') return;
            activeLightbox.dragging = true;
            activeLightbox.moved = false;
            activeLightbox.startX = event.clientX;
            activeLightbox.startY = event.clientY;
            activeLightbox.startPanX = activeLightbox.x;
            activeLightbox.startPanY = activeLightbox.y;
            image.classList.add('is-panning');
            if (stage.setPointerCapture) stage.setPointerCapture(event.pointerId);
        };

        stage.onpointermove = function (event) {
            if (!activeLightbox || !activeLightbox.dragging) return;
            var dx = event.clientX - activeLightbox.startX;
            var dy = event.clientY - activeLightbox.startY;
            activeLightbox.moved = activeLightbox.moved || Math.abs(dx) > 4 || Math.abs(dy) > 4;
            if (activeLightbox.scale > 1) {
                activeLightbox.x = activeLightbox.startPanX + dx;
                activeLightbox.y = activeLightbox.startPanY + dy;
            } else {
                activeLightbox.hoverX = dx * .08;
            }
            applyTransform();
        };

        stage.onpointerup = function (event) {
            if (!activeLightbox) return;
            var dx = event.clientX - activeLightbox.startX;
            var dy = event.clientY - activeLightbox.startY;
            activeLightbox.dragging = false;
            image.classList.remove('is-panning');
            if (activeLightbox.scale <= 1) {
                activeLightbox.hoverX = 0;
                applyTransform();
                if (Math.abs(dx) > 58 && Math.abs(dx) > Math.abs(dy)) {
                    renderLightbox(activeLightbox.index + (dx < 0 ? 1 : -1));
                }
            }
        };

        stage.onpointercancel = function () {
            if (!activeLightbox) return;
            activeLightbox.dragging = false;
            image.classList.remove('is-panning');
        };

        applyTransform();
    }

    function renderThumbs() {
        if (!activeLightbox) return;
        var thumbs = activeLightbox.lightbox.querySelector('[data-lightbox-thumbs]');
        if (!thumbs) return;
        thumbs.innerHTML = activeLightbox.items.map(function (item, index) {
            var type = item.dataset.type || 'image';
            var src = item.dataset.src || '';
            var label = item.dataset.label || '';
            if (type === 'image' && src) {
                return '<button type="button" data-lightbox-thumb="' + index + '" aria-label="Galeri oge ' + (index + 1) + '"><img src="' + src + '" alt=""></button>';
            }
            return '<button type="button" data-lightbox-thumb="' + index + '" aria-label="Galeri oge ' + (index + 1) + '">' + (type === 'model' ? '3D' : (type === 'video' ? 'Video' : label)) + '</button>';
        }).join('');
        thumbs.querySelectorAll('[data-lightbox-thumb]').forEach(function (button) {
            button.addEventListener('click', function () {
                renderLightbox(Number(button.dataset.lightboxThumb || 0));
            });
        });
        updateThumbs();
    }

    function updateThumbs() {
        if (!activeLightbox) return;
        activeLightbox.lightbox.querySelectorAll('[data-lightbox-thumb]').forEach(function (button) {
            button.classList.toggle('is-active', Number(button.dataset.lightboxThumb || 0) === activeLightbox.index);
        });
    }

    function applyTransform() {
        if (!activeLightbox || !activeLightbox.image) return;
        var displayX = activeLightbox.scale > 1 ? activeLightbox.x : activeLightbox.hoverX;
        activeLightbox.image.style.transform = 'translate(' + displayX + 'px, ' + activeLightbox.y + 'px) scale(' + activeLightbox.scale + ')';
        activeLightbox.image.classList.toggle('is-zoomed', activeLightbox.scale > 1);
    }

    function zoomLightbox(delta) {
        if (!activeLightbox || !activeLightbox.image) return;
        activeLightbox.scale = Math.min(4, Math.max(1, activeLightbox.scale + delta));
        if (activeLightbox.scale === 1) {
            activeLightbox.x = 0;
            activeLightbox.y = 0;
        }
        applyTransform();
    }

    function resetZoom(render) {
        if (!activeLightbox) return;
        activeLightbox.scale = 1;
        activeLightbox.x = 0;
        activeLightbox.y = 0;
        activeLightbox.hoverX = 0;
        if (render !== false) applyTransform();
    }

    document.addEventListener('keydown', function (event) {
        if (!activeLightbox) return;

        if (event.key === 'Escape') closeLightbox();
        if (event.key === 'ArrowLeft') renderLightbox(activeLightbox.index - 1);
        if (event.key === 'ArrowRight') renderLightbox(activeLightbox.index + 1);
        if (event.key === '+' || event.key === '=') zoomLightbox(.25);
        if (event.key === '-' || event.key === '_') zoomLightbox(-.25);
        if (event.key === '0') resetZoom();
    });

    document.querySelectorAll('[data-mod-gallery]').forEach(initGallery);
})();
