/**
 * Main JavaScript for Develop Sri Lanka Theme
 */

(function($) {
    'use strict';

    /**
     * Normalize the story text before counting words so that unusual whitespace
     * characters are treated the same as normal spaces.
     */
    function normalizeStoryText(text) {
        if (!text) {
            return '';
        }

        return text
            .replace(/[\u00A0\u202F\u2007]/g, ' ')
            .replace(/[\u200B-\u200D\uFEFF]/g, '')
            .trim();
    }

    /**
     * Count words in a piece of text by splitting on whitespace after normalization.
     */
    function getStoryWordCount(text) {
        var normalizedStory = normalizeStoryText(text);
        if (!normalizedStory) {
            return 0;
        }

        return normalizedStory.split(/\s+/).filter(function(word) {
            return word.length > 0;
        }).length;
    }
    
    // Mobile Menu Toggle
    $('#mobile-menu-toggle').on('click', function() {
        $('#main-navigation').toggleClass('active');
    });
    
    // Close mobile menu when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.site-header').length) {
            $('#main-navigation').removeClass('active');
        }
    });
    
    // Experience Form Submission
    $('#experience-form').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var submitBtn = $('#submit-btn');
        var messageDiv = $('#form-message');
        
        // Validate story word count (minimum 1 word)
        var storyValue = $('#experience-story').val() || '';
        var wordCount = getStoryWordCount(storyValue);
        
        if (wordCount < 1) {
            messageDiv.html('<div style="background: #ff4444; color: white; padding: 15px; border-radius: 5px;">Please write at least 1 word for your story. Current: ' + wordCount + ' words.</div>');
            return;
        }
        
        // Validate image count (maximum 4 images)
        if (uploadedImages.length > 4) {
            messageDiv.html('<div style="background: #ff4444; color: white; padding: 15px; border-radius: 5px;">You can upload a maximum of 4 images. You have ' + uploadedImages.length + ' images.</div>');
            return;
        }
        
        // Check consent
        if (!$('#consent').is(':checked')) {
            messageDiv.html('<div style="background: #ff4444; color: white; padding: 15px; border-radius: 5px;">Please agree to the terms before submitting.</div>');
            return;
        }
        
        // Disable submit button
        submitBtn.prop('disabled', true).text('Submitting...');
        messageDiv.html('');
        
        // Prepare form data
        var formData = new FormData();
        formData.append('action', 'submit_experience');
        formData.append('nonce', srilankaAjax.nonce);
        formData.append('name', $('#contributor-name').val());
        formData.append('email', $('#contributor-email').val());
        formData.append('phone', $('#contributor-phone').val());
        formData.append('company', $('#contributor-company').val());
        formData.append('country', $('#contributor-country').val());
        formData.append('title', $('#experience-title').val());
        formData.append('story', storyValue.trim());
        formData.append('consent', $('#consent').is(':checked') ? '1' : '0');
        
        // Handle multiple images - append each file from uploadedImages array
        if (uploadedImages.length > 0) {
            // Limit to 4 images
            var maxFiles = Math.min(uploadedImages.length, 4);
            for (var i = 0; i < maxFiles; i++) {
                formData.append('images[]', uploadedImages[i]);
            }
        }
        
        // Submit via AJAX
        $.ajax({
            url: srilankaAjax.ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    messageDiv.html('<div style="background: #4CAF50; color: white; padding: 20px; border-radius: 5px; margin-bottom: 20px;"><strong>Success!</strong> ' + response.data.message + '</div>');
                    form[0].reset();
                    
                    // Clear uploaded images and previews
                    uploadedImages = [];
                    $('#image-previews').empty();
                    updateImageCounter();
                    
                    // Scroll to message
                    $('html, body').animate({
                        scrollTop: messageDiv.offset().top - 100
                    }, 500);
                } else {
                    messageDiv.html('<div style="background: #ff4444; color: white; padding: 15px; border-radius: 5px;">' + response.data.message + '</div>');
                }
                
                submitBtn.prop('disabled', false).text('Submit Your Experience');
            },
            error: function() {
                messageDiv.html('<div style="background: #ff4444; color: white; padding: 15px; border-radius: 5px;">An error occurred. Please try again.</div>');
                submitBtn.prop('disabled', false).text('Submit Your Experience');
            }
        });
    });
    
    // Smooth Scroll for Anchor Links
    $('a[href^="#"]').on('click', function(e) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            e.preventDefault();
            $('html, body').stop().animate({
                scrollTop: target.offset().top - 80
            }, 1000);
        }
    });
    
    // Add animation on scroll
    function animateOnScroll() {
        $('.destination-card, .experience-card').each(function() {
            var elementTop = $(this).offset().top;
            var viewportBottom = $(window).scrollTop() + $(window).height();
            
            if (elementTop < viewportBottom - 100) {
                $(this).css({
                    'opacity': '1',
                    'transform': 'translateY(0)'
                });
            }
        });
    }
    
    // Initial setup for cards
    $('.destination-card, .experience-card').css({
        'opacity': '0',
        'transform': 'translateY(30px)',
        'transition': 'all 0.6s ease'
    });
    
    // Trigger animation on scroll
    $(window).on('scroll', animateOnScroll);
    animateOnScroll(); // Initial check
    
    // Multiple image upload handler (one at a time)
    var uploadedImages = []; // Store image data
    var maxImages = 4;
    
    // Add Image button click
    $('#add-image-btn').on('click', function() {
        if (uploadedImages.length >= maxImages) {
            $('#image-counter').html('<span style="color: red;">Maximum ' + maxImages + ' images allowed!</span>');
            return;
        }
        $('#experience-images').click();
    });
    
    // Handle image selection
    $('#experience-images').on('change', function() {
        var file = this.files[0];
        
        if (!file) return;
        
        // Check if already at max
        if (uploadedImages.length >= maxImages) {
            $('#image-counter').html('<span style="color: red;">Maximum ' + maxImages + ' images allowed!</span>');
            this.value = ''; // Reset input
            return;
        }
        
        // Validate file size (5MB)
        if (file.size > 5 * 1024 * 1024) {
            alert('File size must be less than 5MB');
            this.value = '';
            return;
        }
        
        // Validate file type
        if (!file.type.startsWith('image/')) {
            alert('Please select an image file');
            this.value = '';
            return;
        }
        
        // Add to uploaded images array
        uploadedImages.push(file);
        
        // Create preview
        var reader = new FileReader();
        reader.onload = function(e) {
            var previewHtml = '<div class="image-preview-item" data-index="' + (uploadedImages.length - 1) + '">' +
                '<img src="' + e.target.result + '" alt="Preview">' +
                '<button type="button" class="remove-image-btn" data-index="' + (uploadedImages.length - 1) + '">&times;</button>' +
                '</div>';
            $('#image-previews').append(previewHtml);
            updateImageCounter();
        };
        reader.readAsDataURL(file);
        
        // Reset input
        this.value = '';
    });
    
    // Remove image
    $(document).on('click', '.remove-image-btn', function() {
        var index = $(this).data('index');
        
        // Remove from array
        uploadedImages.splice(index, 1);
        
        // Remove preview and re-index
        $('#image-previews').empty();
        uploadedImages.forEach(function(file, i) {
            var reader = new FileReader();
            reader.onload = function(e) {
                var previewHtml = '<div class="image-preview-item" data-index="' + i + '">' +
                    '<img src="' + e.target.result + '" alt="Preview">' +
                    '<button type="button" class="remove-image-btn" data-index="' + i + '">&times;</button>' +
                    '</div>';
                $('#image-previews').append(previewHtml);
            };
            reader.readAsDataURL(file);
        });
        
        updateImageCounter();
    });
    
    // Update image counter
    function updateImageCounter() {
        var remaining = maxImages - uploadedImages.length;
        if (uploadedImages.length === 0) {
            $('#image-counter').html('You can upload up to ' + maxImages + ' images (max 5MB each)');
        } else if (uploadedImages.length >= maxImages) {
            $('#image-counter').html('<span style="color: orange;">' + uploadedImages.length + ' images added (maximum reached)</span>');
            $('#add-image-btn').prop('disabled', true).addClass('disabled');
        } else {
            $('#image-counter').html(uploadedImages.length + ' image(s) added. You can add ' + remaining + ' more.');
            $('#add-image-btn').prop('disabled', false).removeClass('disabled');
        }
    }
    
    // Prevent form resubmission on page reload
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }
    
    // Hero Slider
    var heroSlider = {
        currentSlide: 0,
        slides: $('.hero-slide'),
        totalSlides: $('.hero-slide').length,
        autoplayInterval: null,
        autoplayDelay: 5000,
        
        init: function() {
            if (this.totalSlides <= 1) {
                // Hide controls if only one slide
                $('.slider-prev, .slider-next, .slider-dots').hide();
                $('.hero-slide').addClass('active');
                return;
            }
            
            // Show first slide
            this.slides.eq(0).addClass('active');
            
            // Create dots
            this.createDots();
            
            // Bind events
            $('.slider-prev').on('click', $.proxy(this.prevSlide, this));
            $('.slider-next').on('click', $.proxy(this.nextSlide, this));
            
            // Start autoplay
            this.startAutoplay();
            
            // Pause on hover
            $('.hero-section').hover(
                $.proxy(this.stopAutoplay, this),
                $.proxy(this.startAutoplay, this)
            );
        },
        
        createDots: function() {
            var dotsHtml = '';
            for (var i = 0; i < this.totalSlides; i++) {
                dotsHtml += '<span class="slider-dot' + (i === 0 ? ' active' : '') + '" data-slide="' + i + '"></span>';
            }
            $('.slider-dots').html(dotsHtml);
            
            // Bind dot clicks
            $('.slider-dot').on('click', $.proxy(function(e) {
                var slideIndex = $(e.target).data('slide');
                this.goToSlide(slideIndex);
            }, this));
        },
        
        goToSlide: function(index) {
            this.slides.removeClass('active');
            this.slides.eq(index).addClass('active');
            
            $('.slider-dot').removeClass('active');
            $('.slider-dot').eq(index).addClass('active');
            
            this.currentSlide = index;
        },
        
        nextSlide: function() {
            var next = (this.currentSlide + 1) % this.totalSlides;
            this.goToSlide(next);
        },
        
        prevSlide: function() {
            var prev = (this.currentSlide - 1 + this.totalSlides) % this.totalSlides;
            this.goToSlide(prev);
        },
        
        startAutoplay: function() {
            this.stopAutoplay();
            this.autoplayInterval = setInterval($.proxy(this.nextSlide, this), this.autoplayDelay);
        },
        
        stopAutoplay: function() {
            if (this.autoplayInterval) {
                clearInterval(this.autoplayInterval);
            }
        }
    };
    
    // Initialize slider when DOM is ready
    $(document).ready(function() {
        heroSlider.init();
    });
    
})(jQuery);