/**
 * Calcutta Club Newsletter Frontend JavaScript
 * 
 * Copyright (c) 2025 Deep Basu
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 * Developed for Calcutta Club Ltd.
 * All rights reserved.
 */

(function($) {
    'use strict';
    
    // Wait for DOM to be ready
    $(document).ready(function() {
    
    // Past Events Image Gallery Functionality
    (function() {
        'use strict';
        
        var currentSliderImages = [];
        var currentSliderIndex = 0;
        var isZoomed = false;
        var touchStartX = 0;
        var touchEndX = 0;
        var minSwipeDistance = 50;
        
        // Initialize past events gallery on page load
        function initPastEventsGallery() {
            // Remove any existing handlers to prevent duplicates
            $(document).off('click', '.past-event-view-more-btn');
            
            // Attach click handler using event delegation
            $(document).on('click', '.past-event-view-more-btn', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                console.log('View More button clicked'); // Debug log
                
                var $btn = $(this);
                var eventId = $btn.attr('data-event-id') || $btn.data('event-id');
                
                console.log('Event ID:', eventId); // Debug log
                console.log('Button element:', $btn[0]); // Debug log
                
                if (!eventId) {
                    console.error('Event ID not found');
                    alert('Error: Event ID not found. Please check the console for details.');
                    return;
                }
                
                var $imagesData = $('.past-event-images-data[data-event-id="' + eventId + '"]');
                
                console.log('Images data element found:', $imagesData.length); // Debug log
                
                if ($imagesData.length === 0) {
                    console.error('Images data not found for event:', eventId);
                    console.log('Available image data elements:', $('.past-event-images-data').length);
                    alert('Error: Images data not found. Please check the console for details.');
                    return;
                }
            
            // Get images from data attribute
            var imagesJson = $imagesData.attr('data-images');
            var images = [];
            
            console.log('Images JSON:', imagesJson); // Debug log
            
            try {
                if (imagesJson) {
                    // Handle HTML entities - decode them
                    imagesJson = imagesJson.replace(/&quot;/g, '"')
                                       .replace(/&#039;/g, "'")
                                       .replace(/&amp;/g, '&')
                                       .replace(/&lt;/g, '<')
                                       .replace(/&gt;/g, '>');
                    // Remove whitespace/newlines that might break JSON parsing
                    imagesJson = imagesJson.replace(/\s+/g, ' ').trim();
                    images = JSON.parse(imagesJson);
                    console.log('Parsed images:', images); // Debug log
                } else {
                    // Try using jQuery data() method as fallback
                    images = $imagesData.data('images');
                    if (images && !Array.isArray(images)) {
                        images = [];
                    }
                }
            } catch (e) {
                console.error('Error parsing images JSON:', e, 'Raw JSON:', imagesJson);
                // Try alternative method
                try {
                    var dataImages = $imagesData.data('images');
                    if (Array.isArray(dataImages)) {
                        images = dataImages;
                    }
                } catch (e2) {
                    console.error('Alternative parsing also failed:', e2);
                    return;
                }
            }
            
            if (!Array.isArray(images) || images.length === 0) {
                console.error('No images found');
                return;
            }
            
            // Get event title - try multiple selectors
            var $eventItem = $imagesData.closest('.past-event-item');
            var eventTitle = 'Event Images';
            
            // Try different selectors to find the title
            var $titleElement = $eventItem.find('font[size="4"] b').first();
            if ($titleElement.length === 0) {
                $titleElement = $eventItem.find('font[size="4"]').first();
            }
            if ($titleElement.length === 0) {
                $titleElement = $eventItem.find('b').first();
            }
            if ($titleElement.length > 0) {
                eventTitle = $titleElement.text().trim() || eventTitle;
            }
            
            // Escape HTML in title
            eventTitle = $('<div>').text(eventTitle).html();
            
            // Create popup modal
            var popupModal = $('<div class="past-events-popup-modal"><div class="past-events-popup-content">' +
                '<div class="past-events-popup-header">' +
                '<div class="past-events-popup-title">' + eventTitle + '</div>' +
                '<button class="past-events-popup-close" type="button">&times;</button>' +
                '</div>' +
                '<div class="past-events-popup-grid"></div>' +
                '</div></div>');
            
            var grid = popupModal.find('.past-events-popup-grid');
            
            // Add all images to grid
            images.forEach(function(image, index) {
                if (!image || image.trim() === '') {
                    return;
                }
                // Escape image URL
                var imageUrl = $('<div>').text(image.trim()).html();
                var gridItem = $('<div class="past-events-popup-grid-item" data-image-index="' + index + '" data-event-id="' + eventId + '">' +
                    '<img src="' + imageUrl + '" alt="' + eventTitle + '" loading="lazy">' +
                    '</div>');
                grid.append(gridItem);
            });
            
            if (grid.children().length === 0) {
                console.error('No valid images to display');
                return;
            }
            
            $('body').append(popupModal);
            popupModal.addClass('active');
            $('body').css('overflow', 'hidden');
            
            // Close popup on close button click
            popupModal.find('.past-events-popup-close').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                closePopup();
            });
            
            // Close popup on background click
            popupModal.on('click', function(e) {
                if ($(e.target).hasClass('past-events-popup-modal')) {
                    closePopup();
                }
            });
            
            // Open slider when image is clicked in popup
            grid.find('.past-events-popup-grid-item').on('click', function() {
                var imageIndex = parseInt($(this).attr('data-image-index')) || parseInt($(this).data('image-index')) || 0;
                openSlider(images, imageIndex, eventId);
            });
            
            function closePopup() {
                popupModal.removeClass('active');
                setTimeout(function() {
                    popupModal.remove();
                    $('body').css('overflow', '');
                }, 300);
            }
            
            // Close on Escape key
            var escapeHandler = function(e) {
                if (e.key === 'Escape' || e.keyCode === 27) {
                    closePopup();
                    $(document).off('keydown.pastEventsPopup', escapeHandler);
                }
            };
            $(document).on('keydown.pastEventsPopup', escapeHandler);
            }); // End of click handler
        } // End of initPastEventsGallery function
        
        // Initialize on page load
        initPastEventsGallery();
        
        // Debug: Check if buttons exist
        setTimeout(function() {
            var buttons = $('.past-event-view-more-btn');
            console.log('Found View More buttons:', buttons.length);
            if (buttons.length > 0) {
                console.log('First button data-event-id:', buttons.first().attr('data-event-id'));
            }
        }, 100);
        
        // Also initialize after a short delay to handle dynamically loaded content
        setTimeout(function() {
            initPastEventsGallery();
        }, 500);
        
        // Open slider when collage image is clicked
        $(document).on('click', '.past-event-collage-img', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var eventId = $(this).data('event-id');
            var imageIndex = parseInt($(this).data('image-index'));
            var $imagesData = $('.past-event-images-data[data-event-id="' + eventId + '"]');
            
            if ($imagesData.length === 0) {
                return;
            }
            
            var imagesJson = $imagesData.attr('data-images');
            if (!imagesJson) {
                return;
            }
            
            try {
                imagesJson = imagesJson.replace(/&quot;/g, '"')
                                   .replace(/&#039;/g, "'")
                                   .replace(/&amp;/g, '&')
                                   .replace(/&lt;/g, '<')
                                   .replace(/&gt;/g, '>');
                imagesJson = imagesJson.replace(/\s+/g, ' ').trim();
                var images = JSON.parse(imagesJson);
                
                if (images && images.length > 0) {
                    openSlider(images, imageIndex, eventId);
                }
            } catch (e) {
                console.error('Error parsing images:', e);
            }
        });
        
        // Detect mobile device
        function isMobileDevice() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
                   (window.matchMedia && window.matchMedia('(max-width: 768px)').matches) ||
                   ('ontouchstart' in window);
        }
        
        // Open image slider
        function openSlider(images, startIndex, eventId) {
            if (images.length === 0) {
                return;
            }
            
            var isMobile = isMobileDevice();
            
            currentSliderImages = images;
            currentSliderIndex = startIndex || 0;
            isZoomed = false;
            
            // Hide popup if open (don't remove it, so we can restore it when closing slider)
            var popupModal = $('.past-events-popup-modal');
            if (popupModal.length) {
                popupModal.removeClass('active');
            }
            
            // Create slider
            var slider = $('<div class="past-events-image-slider">' +
                '<div class="slider-header">' +
                '<div class="slider-counter"><span class="current-slide">' + (currentSliderIndex + 1) + '</span> / <span class="total-slides">' + images.length + '</span></div>' +
                '<button class="slider-close">&times;</button>' +
                '</div>' +
                '<div class="slider-container">' +
                '<button class="slider-nav prev" aria-label="Previous">&#8249;</button>' +
                '<div class="slider-image-wrapper">' +
                '<img class="slider-image" src="" alt="Event Image">' +
                '</div>' +
                '<button class="slider-nav next" aria-label="Next">&#8250;</button>' +
                '</div>' +
                '<div class="slider-footer">' +
                '<button class="slider-zoom-btn" aria-label="Zoom">🔍 Zoom</button>' +
                '</div>' +
                '</div>');
            
            $('body').append(slider);
            slider.addClass('active');
            $('body').css('overflow', 'hidden');
            
            // Load initial image
            updateSliderImage();
            
            // Navigation buttons
            slider.find('.slider-nav.prev').on('click', function() {
                if (currentSliderIndex > 0) {
                    currentSliderIndex--;
                    isZoomed = false;
                    updateSliderImage();
                }
            });
            
            slider.find('.slider-nav.next').on('click', function() {
                if (currentSliderIndex < images.length - 1) {
                    currentSliderIndex++;
                    isZoomed = false;
                    updateSliderImage();
                }
            });
            
            // Zoom button
            slider.find('.slider-zoom-btn').on('click', function() {
                toggleZoom();
            });
            
            // Close button
            slider.find('.slider-close').on('click', function() {
                closeSlider();
            });
            
            // Close on background click (but not on image)
            slider.on('click', function(e) {
                if ($(e.target).hasClass('past-events-image-slider')) {
                    closeSlider();
                }
            });
            
            // Keyboard navigation (desktop only)
            if (!isMobile) {
                $(document).on('keydown.pastEventsSlider', function(e) {
                    if (e.key === 'Escape' || e.keyCode === 27) {
                        closeSlider();
                    } else if (e.key === 'ArrowLeft' || e.keyCode === 37) {
                        if (currentSliderIndex > 0) {
                            currentSliderIndex--;
                            isZoomed = false;
                            updateSliderImage();
                        }
                    } else if (e.key === 'ArrowRight' || e.keyCode === 39) {
                        if (currentSliderIndex < images.length - 1) {
                            currentSliderIndex++;
                            isZoomed = false;
                            updateSliderImage();
                        }
                    } else if (e.key === ' ' || e.keyCode === 32) {
                        e.preventDefault();
                        toggleZoom();
                    }
                });
            }
            
            // Update slider image (base function)
            function updateSliderImage() {
                var img = slider.find('.slider-image');
                var imgSrc = currentSliderImages[currentSliderIndex];
                
                img.attr('src', imgSrc);
                img.css('transform', 'translate(0px, 0px) scale(1)');
                isZoomed = false;
                
                // Update counter
                slider.find('.current-slide').text(currentSliderIndex + 1);
                
                // Update navigation buttons
                slider.find('.slider-nav.prev').prop('disabled', currentSliderIndex === 0);
                slider.find('.slider-nav.next').prop('disabled', currentSliderIndex === images.length - 1);
                
                // Update zoom button
                slider.find('.slider-zoom-btn').text('🔍 Zoom In');
            }
            
            // Toggle zoom (base function)
            function toggleZoom() {
                var img = slider.find('.slider-image');
                if (isZoomed) {
                    img.css('transform', 'translate(0px, 0px) scale(1)');
                    isZoomed = false;
                    slider.find('.slider-zoom-btn').text('🔍 Zoom In');
                } else {
                    img.css('transform', 'translate(0px, 0px) scale(2)');
                    isZoomed = true;
                    slider.find('.slider-zoom-btn').text('🔍 Zoom Out');
                }
            }
            
            // Close slider
            function closeSlider() {
                slider.removeClass('active');
                setTimeout(function() {
                    // Clean up event handlers
                    $(document).off('keydown.pastEventsSlider');
                    slider.remove();
                    
                    // Restore popup modal (Stage 2) if it exists
                    var popupModal = $('.past-events-popup-modal');
                    if (popupModal.length) {
                        popupModal.addClass('active');
                        $('body').css('overflow', 'hidden');
                    } else {
                        $('body').css('overflow', '');
                    }
                }, 300);
            }
            
            // Mobile swipe support
            if (isMobile) {
                var touchStartX = 0;
                var touchEndX = 0;
                
                slider.find('.slider-image').on('touchstart', function(e) {
                    if (!isZoomed) {
                        touchStartX = e.originalEvent.touches[0].clientX;
                    }
                });
                
                slider.find('.slider-image').on('touchend', function(e) {
                    if (!isZoomed) {
                        touchEndX = e.originalEvent.changedTouches[0].clientX;
                        var swipeDistance = touchStartX - touchEndX;
                        
                        if (Math.abs(swipeDistance) > minSwipeDistance) {
                            if (swipeDistance > 0 && currentSliderIndex < images.length - 1) {
                                currentSliderIndex++;
                                updateSliderImage();
                            } else if (swipeDistance < 0 && currentSliderIndex > 0) {
                                currentSliderIndex--;
                                updateSliderImage();
                            }
                        }
                    }
                });
            }
        }
    })();
    
    }); // End of document.ready
    
})(jQuery); // End of IIFE
