/**
 * Palace Properties — Gallery & Lightbox
 * Vanilla JS, no dependencies.
 */
(function () {
    'use strict';

    var mainImg, thumbs, images, current, lightboxEl, lightboxImg, lightboxCounter;

    function init() {
        // Find the main gallery image (works with palace-property template)
        mainImg = document.getElementById('ipp-gallery-main-img');
        if (!mainImg) return;

        // Find all thumbnail buttons
        thumbs = document.querySelectorAll('.ipp-gallery__thumb');
        if (!thumbs.length) return;

        // Build images array from thumb data attributes
        images = [];
        thumbs.forEach(function (btn) {
            images.push({
                full: btn.getAttribute('data-full') || '',
                url: btn.getAttribute('data-url') || btn.getAttribute('data-full') || '',
                alt: btn.getAttribute('data-alt') || ''
            });
        });

        current = 0;

        // Thumb click — change main image
        thumbs.forEach(function (btn, i) {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                goTo(i);
            });
        });

        // Main image click — open lightbox
        mainImg.addEventListener('click', function () {
            openLightbox(current);
        });
        mainImg.style.cursor = 'pointer';

        // Touch swipe on main image
        initSwipe(mainImg.parentElement || mainImg);
    }

    function goTo(index) {
        if (index < 0) index = images.length - 1;
        if (index >= images.length) index = 0;
        current = index;

        // Update main image
        mainImg.src = images[current].url || images[current].full;
        mainImg.setAttribute('data-full', images[current].full);
        if (images[current].alt) mainImg.alt = images[current].alt;

        // Update active thumb
        thumbs.forEach(function (t) { t.classList.remove('is-active'); });
        thumbs[current].classList.add('is-active');
        thumbs[current].scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
    }

    // ─── Lightbox ────────────────────────────────────────────────

    function buildLightbox() {
        if (lightboxEl) return;

        lightboxEl = document.createElement('div');
        lightboxEl.id = 'ipp-lightbox';
        lightboxEl.innerHTML =
            '<div style="position:fixed;inset:0;z-index:999999;background:rgba(0,0,0,.92);display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity .25s ease;pointer-events:none;" id="ipp-lb-backdrop">' +
                '<button id="ipp-lb-close" style="position:absolute;top:16px;right:20px;background:none;border:none;color:#fff;font-size:36px;cursor:pointer;z-index:10;padding:8px;line-height:1;" aria-label="Close">&times;</button>' +
                '<button id="ipp-lb-prev" style="position:absolute;left:16px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.15);border:none;color:#fff;width:48px;height:48px;border-radius:50%;cursor:pointer;font-size:24px;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);z-index:10;" aria-label="Previous">' +
                    '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="15 18 9 12 15 6"/></svg>' +
                '</button>' +
                '<img id="ipp-lb-img" style="max-width:90vw;max-height:85vh;object-fit:contain;border-radius:8px;transition:opacity .2s ease;" src="" alt="" />' +
                '<button id="ipp-lb-next" style="position:absolute;right:16px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.15);border:none;color:#fff;width:48px;height:48px;border-radius:50%;cursor:pointer;font-size:24px;display:flex;align-items:center;justify-content:center;backdrop-filter:blur(4px);z-index:10;" aria-label="Next">' +
                    '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>' +
                '</button>' +
                '<span id="ipp-lb-counter" style="position:absolute;bottom:20px;left:50%;transform:translateX(-50%);color:rgba(255,255,255,.7);font-size:14px;font-weight:500;"></span>' +
            '</div>';

        document.body.appendChild(lightboxEl);

        var backdrop = document.getElementById('ipp-lb-backdrop');
        lightboxImg = document.getElementById('ipp-lb-img');
        lightboxCounter = document.getElementById('ipp-lb-counter');

        document.getElementById('ipp-lb-close').addEventListener('click', closeLightbox);
        document.getElementById('ipp-lb-prev').addEventListener('click', function (e) { e.stopPropagation(); lbGo(current - 1); });
        document.getElementById('ipp-lb-next').addEventListener('click', function (e) { e.stopPropagation(); lbGo(current + 1); });
        backdrop.addEventListener('click', function (e) { if (e.target === backdrop) closeLightbox(); });

        // Touch swipe in lightbox
        initSwipe(backdrop, true);
    }

    function openLightbox(index) {
        buildLightbox();
        current = index;
        lbGo(current);
        var backdrop = document.getElementById('ipp-lb-backdrop');
        backdrop.style.opacity = '1';
        backdrop.style.pointerEvents = 'auto';
        document.body.style.overflow = 'hidden';
    }

    function closeLightbox() {
        var backdrop = document.getElementById('ipp-lb-backdrop');
        if (backdrop) {
            backdrop.style.opacity = '0';
            backdrop.style.pointerEvents = 'none';
        }
        document.body.style.overflow = '';
    }

    function lbGo(index) {
        if (!images || !images.length) return;
        if (index < 0) index = images.length - 1;
        if (index >= images.length) index = 0;
        current = index;
        lightboxImg.style.opacity = '0';
        setTimeout(function () {
            lightboxImg.src = images[current].full;
            lightboxImg.alt = images[current].alt;
            lightboxImg.style.opacity = '1';
        }, 150);
        lightboxCounter.textContent = (current + 1) + ' / ' + images.length;

        // Also update the inline gallery
        goTo(current);
    }

    // ─── Keyboard ────────────────────────────────────────────────

    document.addEventListener('keydown', function (e) {
        var backdrop = document.getElementById('ipp-lb-backdrop');
        if (!backdrop || backdrop.style.pointerEvents !== 'auto') return;
        if (e.key === 'ArrowLeft') { e.preventDefault(); lbGo(current - 1); }
        if (e.key === 'ArrowRight') { e.preventDefault(); lbGo(current + 1); }
        if (e.key === 'Escape') { e.preventDefault(); closeLightbox(); }
    });

    // ─── Touch Swipe ─────────────────────────────────────────────

    function initSwipe(el, isLightbox) {
        var startX = 0, distX = 0, distY = 0;
        el.addEventListener('touchstart', function (e) {
            if (e.touches.length !== 1) return;
            startX = e.touches[0].clientX;
            distX = 0; distY = 0;
        }, { passive: true });
        el.addEventListener('touchmove', function (e) {
            if (e.touches.length !== 1) return;
            distX = e.touches[0].clientX - startX;
            distY = e.touches[0].clientY - (e.touches[0].clientY - distY); // approximate
        }, { passive: true });
        el.addEventListener('touchend', function () {
            if (Math.abs(distX) > 50) {
                if (isLightbox) {
                    lbGo(distX > 0 ? current - 1 : current + 1);
                } else {
                    goTo(distX > 0 ? current - 1 : current + 1);
                }
            }
        }, { passive: true });
    }

    // ─── Init ────────────────────────────────────────────────────

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    window.IPPGallery = { init: init, openLightbox: openLightbox, closeLightbox: closeLightbox };
})();
