/**
 * Gallery Frontend Scripts - Vanilla JavaScript
 */

(function () {
    'use strict';

    class VimeifyGallery {
        constructor(gallery) {
            this.gallery = gallery;
            this.galleryId = gallery.getAttribute('data-gallery-id');
            this.style = gallery.getAttribute('data-style');
            this.thumbnails = gallery.querySelector('.vimeify-gallery-thumbnails');
            this.playlistItems = gallery.querySelector('.vimeify-playlist-items');
            this.isLoading = false;
            this.hasMore = gallery.querySelectorAll('.vimeify-gallery-load-more, .vimeify-playlist-loading').length > 0;

            this.init();
        }

        init() {
            if (this.style === 'slider') {
                this.initSlider();
            } else if (this.style === 'playlist') {
                this.initPlaylist();
            }
        }

        /**
         * Initialize slider style
         */
        initSlider() {
            // Thumbnail click handler
            this.gallery.addEventListener('click', (e) => {
                const thumbnail = e.target.closest('.vimeify-gallery-thumbnail');
                if (thumbnail) {
                    this.switchVideo(thumbnail);
                }

                const loadMoreBtn = e.target.closest('.vimeify-gallery-load-more');
                if (loadMoreBtn) {
                    this.loadMoreVideos(loadMoreBtn);
                }
            });
        }

        /**
         * Initialize playlist style
         */
        initPlaylist() {
            // Playlist item click handler
            this.gallery.addEventListener('click', (e) => {
                const playlistItem = e.target.closest('.vimeify-playlist-item');
                if (playlistItem) {
                    this.switchVideo(playlistItem);
                }
            });

            // Infinite scroll handler
            if (this.hasMore && this.playlistItems) {
                this.playlistItems.addEventListener('scroll', () => {
                    this.handlePlaylistScroll();
                });
            }

            // Match playlist height to video player height
            this.matchPlaylistHeight();
            window.addEventListener('resize', () => this.matchPlaylistHeight());
        }

        /**
         * Match playlist sidebar height to video player
         */
        matchPlaylistHeight() {
            const playerWrapper = this.gallery.querySelector('.vimeify-gallery-player-wrapper');
            const playlistSidebar = this.gallery.querySelector('.vimeify-playlist-sidebar');

            if (playerWrapper && playlistSidebar) {
                const playerHeight = playerWrapper.offsetHeight;
                playlistSidebar.style.height = playerHeight + 'px';
            }
        }

        /**
         * Switch to a different video
         */
        switchVideo(item) {
            const embedUrl = item.getAttribute('data-embed-url');
            const title = item.getAttribute('data-title');
            const description = item.getAttribute('data-description');

            // Update active state
            this.gallery.querySelectorAll('.vimeify-gallery-thumbnail, .vimeify-playlist-item').forEach(el => {
                el.classList.remove('active');
            });
            item.classList.add('active');

            // Update main player
            const playerWrapper = this.gallery.querySelector('.vimeify-gallery-player-wrapper');
            if (playerWrapper) {
                playerWrapper.innerHTML =
                    '<iframe src="' + embedUrl + '" ' +
                    'frameborder="0" ' +
                    'allow="autoplay; fullscreen; picture-in-picture" ' +
                    'allowfullscreen ' +
                    'class="vimeify-gallery-iframe"></iframe>';
            }

            // Update video info
            if (title) {
                const titleElement = this.gallery.querySelector('.vimeify-gallery-video-title');
                if (titleElement) {
                    titleElement.textContent = title;
                }
            }
            if (description) {
                const descElement = this.gallery.querySelector('.vimeify-gallery-video-description');
                if (descElement) {
                    descElement.textContent = description;
                }
            }

            // Scroll to player for slider style
            if (this.style === 'slider') {
                const galleryTop = this.gallery.getBoundingClientRect().top + window.pageYOffset - 20;
                window.scrollTo({
                    top: galleryTop,
                    behavior: 'smooth'
                });
            }
        }

        /**
         * Load more videos (button-based)
         */
        loadMoreVideos(button) {
            if (this.isLoading) {
                return;
            }

            const wrapper = button.closest('.vimeify-gallery-load-more-wrapper');
            const loading = wrapper.querySelector('.vimeify-gallery-loading');
            const nextOffset = parseInt(button.getAttribute('data-next-offset'));

            this.isLoading = true;
            button.style.display = 'none';
            loading.style.display = 'block';

            this.fetchMoreVideos(nextOffset, (response) => {
                if (response.success && response.data.html) {
                    this.thumbnails.insertAdjacentHTML('beforeend', response.data.html);
                    this.thumbnails.setAttribute('data-current-offset', response.data.offset);

                    if (response.data.has_more) {
                        button.setAttribute('data-next-offset', response.data.next_offset);
                        button.style.display = 'block';
                    } else {
                        wrapper.remove();
                        this.hasMore = false;
                    }
                }
                loading.style.display = 'none';
                this.isLoading = false;
            });
        }

        /**
         * Handle playlist scroll for infinite loading
         */
        handlePlaylistScroll() {
            if (this.isLoading || !this.hasMore) {
                return;
            }

            const container = this.playlistItems;
            const scrollTop = container.scrollTop;
            const scrollHeight = container.scrollHeight;
            const containerHeight = container.clientHeight;

            // Check if near bottom (within 100px)
            if (scrollTop + containerHeight >= scrollHeight - 100) {
                const currentOffset = parseInt(container.getAttribute('data-current-offset'));
                const perPage = parseInt(container.getAttribute('data-per-page'));
                const nextOffset = currentOffset + perPage;

                this.isLoading = true;
                const loadingIndicator = this.gallery.querySelector('.vimeify-playlist-loading');
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'block';
                }

                this.fetchMoreVideos(nextOffset, (response) => {
                    if (response.success && response.data.html) {
                        // Insert before loading indicator
                        const loadingIndicator = this.gallery.querySelector('.vimeify-playlist-loading');
                        if (loadingIndicator) {
                            loadingIndicator.insertAdjacentHTML('beforebegin', response.data.html);
                        }
                        container.setAttribute('data-current-offset', response.data.offset);

                        if (!response.data.has_more) {
                            this.hasMore = false;
                            if (loadingIndicator) {
                                loadingIndicator.remove();
                            }
                        }
                    }
                    this.isLoading = false;
                    const loadingIndicator = this.gallery.querySelector('.vimeify-playlist-loading');
                    if (loadingIndicator) {
                        loadingIndicator.style.display = 'none';
                    }
                });
            }
        }

        /**
         * Fetch more videos via AJAX
         */
        fetchMoreVideos(offset, callback) {
            const formData = new FormData();
            formData.append('action', 'vimeify_load_more_gallery_videos');
            formData.append('nonce', vimeifyGallery.nonce);
            formData.append('gallery_id', this.galleryId);
            formData.append('offset', offset);

            fetch(vimeifyGallery.ajaxUrl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            })
                .then(response => response.json())
                .then(callback)
                .catch(() => {
                    this.isLoading = false;
                    const loadingElements = this.gallery.querySelectorAll('.vimeify-gallery-loading, .vimeify-playlist-loading');
                    loadingElements.forEach(el => el.style.display = 'none');
                    alert('Failed to load more videos. Please try again.');
                });
        }
    }

    // Initialize galleries on page load
    function initGalleries() {
        document.querySelectorAll('.vimeify-gallery[data-gallery-id]').forEach(gallery => {
            new VimeifyGallery(gallery);
        });
    }

    // Run when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initGalleries);
    } else {
        initGalleries();
    }

})();
