// DOM Ready and Initialization
$(document).ready(function() {
    initSmoothScrolling();
    initHeaderScroll();
    initMobileMenu();
    initContainerVideo();
    initGallery();
    initQuoteForm();
    initScrollAnimations();
    initSEOOptimizations();
});

// Smooth Scrolling Navigation
function initSmoothScrolling() {
    $('a[href^="#"]').on('click', function(e) {
        e.preventDefault();
        
        const target = $(this.getAttribute('href'));
        if (target.length) {
            const headerHeight = $('#header').outerHeight();
            const targetPosition = target.offset().top - headerHeight - 20;
            
            $('html, body').animate({
                scrollTop: targetPosition
            }, 800);
        }
    });
}

// Header Scroll Effects
function initHeaderScroll() {
    const header = $('#header');
    
    $(window).on('scroll', function() {
        if ($(window).scrollTop() > 100) {
            header.addClass('scrolled');
        } else {
            header.removeClass('scrolled');
        }
    });
}

// Mobile Menu Toggle
function initMobileMenu() {
    const mobileToggle = $('.mobile-menu-toggle');
    const navMenu = $('.nav-menu');
    
    mobileToggle.on('click', function() {
        navMenu.toggleClass('mobile-active');
        $(this).find('i').toggleClass('fa-bars fa-times');
    });
    
    $('.nav-menu a').on('click', function() {
        navMenu.removeClass('mobile-active');
        mobileToggle.find('i').removeClass('fa-times').addClass('fa-bars');
    });
    
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.navigation').length) {
            navMenu.removeClass('mobile-active');
            mobileToggle.find('i').removeClass('fa-times').addClass('fa-bars');
        }
    });
}

// Portrait Video Display for Reefer Container
function initContainerVideo() {
    const container = document.getElementById('video-container');
    if (!container) return;

    try {
        // Create video element
        const video = document.createElement('video');
        video.setAttribute('autoplay', '');
        video.setAttribute('muted', '');
        video.setAttribute('loop', '');
        video.setAttribute('playsinline', '');
        video.muted = true;      // Ensure muted property is set
        video.autoplay = true;   // Ensure autoplay property is set
        video.style.width = '100%';
        video.style.height = '100%';
        video.style.objectFit = 'cover';
        video.style.borderRadius = '20px';
        
        // Add video source
        video.src = 'attached_assets/biforstcon.mp4';
        
        // Add poster image as fallback
        video.poster = 'https://via.placeholder.com/450x600/1e40af/ffffff?text=BIFORST+Reefer+Container+Video';
        
        // Clear container and add video
        container.innerHTML = '';
        container.appendChild(video);

        // Handle video load errors
        video.addEventListener('error', () => {
            console.log('Video failed to load, showing poster image');
            const img = document.createElement('img');
            img.src = video.poster;
            img.alt = 'BIFORST 20ft Reefer Container Malaysia Temperature-Controlled Shipping';
            img.style.width = '100%';
            img.style.height = '100%';
            img.style.objectFit = 'cover';
            img.style.borderRadius = '20px';
            container.innerHTML = '';
            container.appendChild(img);
        });

        // Video play controls
        video.addEventListener('loadeddata', () => {
            video.play().catch(e => console.log('Autoplay prevented:', e));
        });

    } catch (error) {
        console.error('Video initialization failed:', error);
        // Show placeholder message for video upload
        container.innerHTML = `
            <div class="video-placeholder" style="
                width: 100%; 
                height: 100%; 
                background: linear-gradient(135deg, #1e40af 0%, #1d4ed8 100%);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: white;
                text-align: center;
                border-radius: 20px;
                padding: 2rem;
            ">
                <i class="fas fa-video" style="font-size: 3rem; margin-bottom: 1rem; color: #f59e0b;"></i>
                <h3 style="margin-bottom: 1rem;">Upload Your Reefer Container Video</h3>
                <p style="color: #e0e7ff;">Add a portrait video showcasing your BIFORST reefer containers</p>
            </div>
        `;
    }
}

// Gallery Modal Functionality
function initGallery() {
    const modal = $('#galleryModal');
    const modalImg = $('#modalImage');
    const closeBtn = $('.modal-close');
    
    $('.gallery-item').on('click', function() {
        const imageSrc = $(this).data('image');
        const imageAlt = $(this).find('img').attr('alt');
        
        modalImg.attr('src', imageSrc);
        modalImg.attr('alt', imageAlt);
        modal.fadeIn(300);
        $('body').css('overflow', 'hidden');
    });
    
    closeBtn.on('click', closeModal);
    modal.on('click', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });
    
    $(document).on('keyup', function(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
    
    function closeModal() {
        modal.fadeOut(300);
        $('body').css('overflow', 'auto');
    }
}

// Quote Form Handling
function initQuoteForm() {
    const form = $('#quoteForm');
    
    form.on('submit', function(e) {
        e.preventDefault();
        
        const formData = {
            name: $('#name').val().trim(),
            email: $('#email').val().trim(),
            phone: $('#phone').val().trim(),
            company: $('#company').val().trim(),
            containerType: $('#containerType').val(),
            duration: $('#duration').val(),
            temperature: $('#temperature').val(),
            location: $('#location').val().trim(),
            message: $('#message').val().trim()
        };
        
        const errors = validateQuoteForm(formData);
        
        if (errors.length > 0) {
            showFormMessage(errors.join('<br>'), 'error');
            return;
        }
        
        const submitBtn = form.find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Sending...').prop('disabled', true);
        
        setTimeout(() => {
            showFormMessage('Thank you for your reefer container quote request! Our specialists will contact you within 24 hours with competitive pricing for your temperature-controlled shipping needs.', 'success');
            form[0].reset();
            submitBtn.html(originalText).prop('disabled', false);
        }, 2000);
    });
}

// Form Validation
function validateQuoteForm(data) {
    const errors = [];
    
    if (!data.name) errors.push('Full name is required');
    if (!data.email) errors.push('Email address is required');
    if (!data.phone) errors.push('Phone number is required');
    if (!data.containerType) errors.push('Container type selection is required');
    
    if (data.email && !isValidEmail(data.email)) {
        errors.push('Please enter a valid email address');
    }
    
    if (data.phone && !isValidMalaysianPhone(data.phone)) {
        errors.push('Please enter a valid Malaysian phone number');
    }
    
    return errors;
}

function isValidEmail(email) {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
}

function isValidMalaysianPhone(phone) {
    const cleanPhone = phone.replace(/[^\d+]/g, '');
    const patterns = [
        /^\+60[1-9]\d{7,9}$/,
        /^60[1-9]\d{7,9}$/,
        /^0[1-9]\d{7,9}$/
    ];
    return patterns.some(pattern => pattern.test(cleanPhone));
}

// Form Message Display
function showFormMessage(message, type) {
    $('.form-message').remove();
    
    const messageClass = type === 'success' ? 'success' : 'error';
    const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle';
    const bgColor = type === 'success' ? '#dcfce7' : '#fee2e2';
    const textColor = type === 'success' ? '#166534' : '#991b1b';
    const borderColor = type === 'success' ? '#bbf7d0' : '#fca5a5';
    
    const messageHtml = `
        <div class="form-message ${messageClass}" style="
            background: ${bgColor};
            color: ${textColor};
            border: 1px solid ${borderColor};
            padding: 1rem 1.5rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-weight: 500;
        ">
            <i class="fas ${iconClass}"></i>
            <div>${message}</div>
        </div>
    `;
    
    $('#quoteForm').prepend(messageHtml);
    $('.form-message')[0].scrollIntoView({ behavior: 'smooth', block: 'center' });
    
    if (type === 'success') {
        setTimeout(() => {
            $('.form-message').fadeOut(500, function() {
                $(this).remove();
            });
        }, 5000);
    }
}

// Scroll Animations
function initScrollAnimations() {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('visible');
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });

    // Add animation classes to elements
    $('.feature-item, .spec-card, .application-card, .gallery-item').addClass('fade-in');
    
    // Observe elements
    $('.fade-in').each(function() {
        observer.observe(this);
    });
}

// SEO and Performance Optimizations
function initSEOOptimizations() {
    // Lazy load images
    $('img').each(function() {
        const img = $(this);
        const src = img.attr('src');
        
        if (src) {
            img.on('load', function() {
                img.removeClass('loading');
            }).addClass('loading');
        }
    });
    
    // Preload critical resources
    const criticalImages = [
        'https://images.unsplash.com/photo-1566576721346-d4a3b4eaeb55',
        'https://images.unsplash.com/photo-1578662996442-48f60103fc96'
    ];
    
    criticalImages.forEach(src => {
        const link = document.createElement('link');
        link.rel = 'preload';
        link.as = 'image';
        link.href = src;
        document.head.appendChild(link);
    });
    
    // Add structured data for better SEO
    updateStructuredData();
}

function updateStructuredData() {
    // Update structured data with current page interactions
    const structuredData = {
        "@context": "https://schema.org",
        "@type": "WebPage",
        "name": "BIFORST Reefer Container Rental Malaysia",
        "description": "Premium reefer container rental services with 3D container visualization",
        "url": window.location.href,
        "mainEntity": {
            "@type": "Service",
            "name": "Reefer Container Rental",
            "provider": {
                "@type": "LocalBusiness",
                "name": "BIFORST Malaysia"
            }
        }
    };
    
    // Add to page if not exists
    if (!$('script[type="application/ld+json"]:contains("WebPage")').length) {
        $('<script type="application/ld+json">')
            .text(JSON.stringify(structuredData))
            .appendTo('head');
    }
}

// Performance monitoring
function trackPagePerformance() {
    if ('performance' in window) {
        window.addEventListener('load', () => {
            setTimeout(() => {
                const perfData = performance.getEntriesByType('navigation')[0];
                console.log('Page Load Time:', perfData.loadEventEnd - perfData.loadEventStart, 'ms');
            }, 0);
        });
    }
}

// Initialize performance tracking
trackPagePerformance();

// Error handling for 3D container
window.addEventListener('error', function(e) {
    if (e.message.includes('THREE') || e.message.includes('WebGL')) {
        console.warn('3D container error, falling back to static image');
        const container = document.getElementById('threejs-container');
        if (container) {
            const fallback = container.querySelector('.container-fallback');
            if (fallback) {
                fallback.style.display = 'block';
            }
        }
    }
});

// Toggle mute/unmute on video and change icon
$(document).on('click', '#unmute-video-btn', function() {
    const video = document.querySelector('#video-container video');
    const icon = this.querySelector('i');
    if (video) {
        if (video.muted) {
            video.muted = false;
            video.volume = 1.0;
            icon.classList.remove('fa-volume-up');
            icon.classList.add('fa-volume-mute');
            this.innerHTML = '<i class="fas fa-volume-mute"></i> Mute Video';
        } else {
            video.muted = true;
            icon.classList.remove('fa-volume-mute');
            icon.classList.add('fa-volume-up');
            this.innerHTML = '<i class="fas fa-volume-up"></i> Unmute Video';
        }
        video.play();
    }
});
