/**
 * OKT Gallery Widget Handler
 * Handles: masonry layout via Packery, lightbox via GLightbox, load-more
 */
(function () {

    function initGallery( scope ) {
        var wrapper = scope.querySelector( '.okt-gallery-wrapper' );
        if ( ! wrapper ) return;

        var grid   = wrapper.querySelector( '.okt-gallery-grid' );
        if ( ! grid ) return;

        if ( grid.dataset.oktGalleryInit === '1' ) return;
        grid.dataset.oktGalleryInit = '1';

        var layout    = grid.dataset.layout || 'grid';
        var useLoadMore = grid.dataset.loadMore === 'yes';

        // ── Masonry / Packery ─────────────────────────────────────────────
        var packeryInstance = null;

        if ( layout === 'masonry' ) {
            imagesLoaded( grid, function () {
                packeryInstance = new Packery( grid, {
                    itemSelector : '.okt-gallery-item',
                    columnWidth  : '.okt-gallery-masonry-sizer',
                    gutter       : '.okt-gallery-masonry-gutter',
                    percentPosition: true,
                } );
            } );
        }

        // ── GLightbox ─────────────────────────────────────────────────────
        var lightboxLinks = wrapper.querySelectorAll( '[data-glightbox]' );
        if ( lightboxLinks.length && typeof GLightbox !== 'undefined' ) {
            // Extract gallery id from the first link to scope the instance
            var galleryAttr = lightboxLinks[0].getAttribute( 'data-glightbox' ) || '';
            var galleryMatch = galleryAttr.match( /gallery:\s*([^;]+)/ );
            var galleryName  = galleryMatch ? galleryMatch[1].trim() : 'okt-gallery';

            GLightbox( {
                selector : '[data-glightbox*="gallery: ' + galleryName + '"]',
                touchNavigation : true,
                loop            : true,
            } );
        }

        // ── Load More ─────────────────────────────────────────────────────
        if ( useLoadMore ) {
            var btn = wrapper.querySelector( '.okt-gallery-load-more' );
            if ( btn ) {
                var allHidden    = Array.prototype.slice.call( wrapper.querySelectorAll( '.okt-gallery-item--hidden' ) );
                var perClick     = parseInt( btn.dataset.perClick ) || 3;

                btn.addEventListener( 'click', function () {
                    var toShow = allHidden.splice( 0, perClick );

                    toShow.forEach( function ( item ) {
                        item.classList.remove( 'okt-gallery-item--hidden' );
                    } );

                    // Re-layout masonry after revealing items
                    if ( packeryInstance ) {
                        imagesLoaded( grid, function () {
                            packeryInstance.reloadItems();
                            packeryInstance.layout();
                        } );
                    }

                    // Hide button when all items are shown
                    if ( allHidden.length === 0 ) {
                        btn.parentElement.style.display = 'none';
                    }
                } );
            }
        }
    }

    // ── Elementor frontend hook ───────────────────────────────────────────
    ( function ( $ ) {
        $( window ).on( 'elementor/frontend/init', function () {
            elementorFrontend.hooks.addAction(
                'frontend/element_ready/okthemes-gallery.default',
                function ( $element ) {
                    initGallery( $element[0] );
                }
            );
        } );
    } )( jQuery );

    // ── Plain DOM fallback ────────────────────────────────────────────────
    document.addEventListener( 'DOMContentLoaded', function () {
        document.querySelectorAll( '.okt-gallery-wrapper' ).forEach( function ( wrapper ) {
            initGallery( wrapper.parentElement || wrapper );
        } );
    } );

} )();
