/**
 * AutoCheck Pro - Main JavaScript
 * Handles interactivity for the car inspection website
 */

document.addEventListener('DOMContentLoaded', function() {
    // Mobile Menu Toggle
    initMobileMenu();

    // Photo Upload Handling
    initPhotoUpload();

    // Form Validation
    initFormValidation();

    // Smooth Scrolling
    initSmoothScroll();

    // Header Scroll Effect
    initHeaderScroll();
});

/**
 * Mobile Menu Toggle
 */
function initMobileMenu() {
    const mobileMenuBtn = document.querySelector('.mobile-menu');
    const navLinks = document.querySelector('.nav-links');

    if (mobileMenuBtn && navLinks) {
        mobileMenuBtn.addEventListener('click', function() {
            navLinks.classList.toggle('active');
            const icon = this.querySelector('i');
            if (icon) {
                icon.classList.toggle('fa-bars');
                icon.classList.toggle('fa-times');
            }
        });

        // Close menu when clicking on a link
        navLinks.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', function() {
                navLinks.classList.remove('active');
                const icon = mobileMenuBtn.querySelector('i');
                if (icon) {
                    icon.classList.add('fa-bars');
                    icon.classList.remove('fa-times');
                }
            });
        });
    }
}

/**
 * Photo Upload Handling
 */
function initPhotoUpload() {
    const uploadBoxes = document.querySelectorAll('.upload-box');

    uploadBoxes.forEach(box => {
        const input = box.querySelector('input[type="file"]');
        const removeBtn = box.querySelector('.remove-btn');
        const originalContent = {
            icon: box.querySelector('.upload-icon'),
            span: box.querySelector('span')
        };

        // Click to upload
        box.addEventListener('click', function(e) {
            if (e.target !== removeBtn && !removeBtn.contains(e.target)) {
                input.click();
            }
        });

        // Handle file selection
        input.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];

                // Validate file size (5MB max)
                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;
                }

                // Preview image
                const reader = new FileReader();
                reader.onload = function(e) {
                    // Remove existing preview if any
                    const existingImg = box.querySelector('img');
                    if (existingImg) {
                        existingImg.remove();
                    }

                    // Hide original content
                    if (originalContent.icon) originalContent.icon.style.display = 'none';
                    if (originalContent.span) originalContent.span.style.display = 'none';

                    // Create and add preview image
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.alt = 'Preview';
                    box.insertBefore(img, box.firstChild);
                    box.classList.add('has-image');
                };
                reader.readAsDataURL(file);
            }
        });

        // Remove image
        if (removeBtn) {
            removeBtn.addEventListener('click', function(e) {
                e.stopPropagation();

                // Remove preview image
                const img = box.querySelector('img');
                if (img) {
                    img.remove();
                }

                // Clear input
                input.value = '';

                // Show original content
                if (originalContent.icon) originalContent.icon.style.display = '';
                if (originalContent.span) originalContent.span.style.display = '';

                box.classList.remove('has-image');
            });
        }
    });

    // Drag and drop support
    uploadBoxes.forEach(box => {
        const input = box.querySelector('input[type="file"]');

        box.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = 'var(--primary)';
            this.style.background = 'rgba(16, 185, 129, 0.1)';
        });

        box.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.background = '';
        });

        box.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '';
            this.style.background = '';

            const files = e.dataTransfer.files;
            if (files.length > 0) {
                // Create a new DataTransfer to assign to input
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(files[0]);
                input.files = dataTransfer.files;

                // Trigger change event
                input.dispatchEvent(new Event('change'));
            }
        });
    });
}

/**
 * Form Validation
 */
function initFormValidation() {
    const form = document.getElementById('inspectionForm');

    if (form) {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            const requiredFields = form.querySelectorAll('[required]');

            // Clear previous errors
            form.querySelectorAll('.error-message').forEach(el => el.remove());
            form.querySelectorAll('.error').forEach(el => el.classList.remove('error'));

            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    isValid = false;
                    field.classList.add('error');
                    field.style.borderColor = '#ef4444';

                    // Add error message
                    const errorMsg = document.createElement('span');
                    errorMsg.className = 'error-message';
                    errorMsg.style.color = '#ef4444';
                    errorMsg.style.fontSize = '0.85rem';
                    errorMsg.style.marginTop = '5px';
                    errorMsg.style.display = 'block';
                    errorMsg.textContent = 'This field is required';
                    field.parentNode.appendChild(errorMsg);
                } else {
                    field.style.borderColor = '';
                }
            });

            // Validate year
            const yearField = form.querySelector('#vehicle_year');
            if (yearField && yearField.value) {
                const year = parseInt(yearField.value);
                const currentYear = new Date().getFullYear();
                if (year < 1900 || year > currentYear + 1) {
                    isValid = false;
                    yearField.style.borderColor = '#ef4444';
                    const errorMsg = document.createElement('span');
                    errorMsg.className = 'error-message';
                    errorMsg.style.color = '#ef4444';
                    errorMsg.style.fontSize = '0.85rem';
                    errorMsg.textContent = 'Please enter a valid year';
                    yearField.parentNode.appendChild(errorMsg);
                }
            }

            // Validate VIN (if provided)
            const vinField = form.querySelector('#vin_number');
            if (vinField && vinField.value && vinField.value.length !== 17) {
                isValid = false;
                vinField.style.borderColor = '#ef4444';
                const errorMsg = document.createElement('span');
                errorMsg.className = 'error-message';
                errorMsg.style.color = '#ef4444';
                errorMsg.style.fontSize = '0.85rem';
                errorMsg.textContent = 'VIN must be 17 characters';
                vinField.parentNode.appendChild(errorMsg);
            }

            if (!isValid) {
                e.preventDefault();

                // Scroll to first error
                const firstError = form.querySelector('.error, [style*="border-color: rgb(239, 68, 68)"]');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            } else {
                // Show loading state
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<span class="loading"></span> Generating Report...';
                }
            }
        });

        // Clear error on input
        form.querySelectorAll('input, select, textarea').forEach(field => {
            field.addEventListener('input', function() {
                this.style.borderColor = '';
                const errorMsg = this.parentNode.querySelector('.error-message');
                if (errorMsg) {
                    errorMsg.remove();
                }
            });
        });
    }
}

/**
 * Smooth Scrolling for Anchor Links
 */
function initSmoothScroll() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            const href = this.getAttribute('href');
            if (href !== '#') {
                e.preventDefault();
                const target = document.querySelector(href);
                if (target) {
                    const headerHeight = document.querySelector('header').offsetHeight;
                    const targetPosition = target.offsetTop - headerHeight - 20;
                    window.scrollTo({
                        top: targetPosition,
                        behavior: 'smooth'
                    });
                }
            }
        });
    });
}

/**
 * Header Scroll Effect
 */
function initHeaderScroll() {
    const header = document.querySelector('header');

    if (header) {
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                header.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.15)';
            } else {
                header.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
            }
        });
    }
}

/**
 * Utility: Format number with commas
 */
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

/**
 * Auto-format mileage input
 */
const mileageInput = document.getElementById('mileage');
if (mileageInput) {
    mileageInput.addEventListener('blur', function() {
        if (this.value) {
            // Store raw value for form submission
            this.dataset.rawValue = this.value;
        }
    });
}
