/**
 * Advanced Court Creation JavaScript
 * Handles Google Places API, image cropping, and form validation
 */

let map;
let marker;
let autocomplete;
let cropper;
let currentImageIndex = 0;
let uploadedImages = [];

// Initialize Google Maps and Places
function initMap() {
    // Initialize map
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 40.7128, lng: -74.0060 }, // Default to NYC
        zoom: 13,
        styles: [
            {
                featureType: 'poi',
                elementType: 'labels',
                stylers: [{ visibility: 'off' }]
            }
        ]
    });

    // Initialize Places Autocomplete
    const locationInput = document.getElementById('location');
    autocomplete = new google.maps.places.Autocomplete(locationInput, {
        types: ['geocode'],
        componentRestrictions: { country: 'us' }
    });

    // Handle place selection
    autocomplete.addListener('place_changed', function () {
        const place = autocomplete.getPlace();

        if (!place.geometry || !place.geometry.location) {
            showError('Please select a valid address from the suggestions.');
            return;
        }

        // Update form fields
        updateLocationFields(place);

        // Update map
        updateMap(place);

        // Show success feedback
        showSuccess('Address selected successfully!');
    });

    // Get user's current location
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function (position) {
                const pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                map.setCenter(pos);
            },
            function () {
                console.log('Geolocation permission denied or failed');
            }
        );
    }
}

// Update location fields from place data
function updateLocationFields(place) {
    const components = place.address_components;
    let city = '', state = '', zip = '';

    // Extract address components
    components.forEach(component => {
        const types = component.types;
        if (types.includes('locality')) {
            city = component.long_name;
        } else if (types.includes('administrative_area_level_1')) {
            state = component.long_name;
        } else if (types.includes('postal_code')) {
            zip = component.long_name;
        }
    });

    // Update form fields
    document.getElementById('latitude').value = place.geometry.location.lat();
    document.getElementById('longitude').value = place.geometry.location.lng();
    document.getElementById('city').value = city;
    document.getElementById('state').value = state;
    document.getElementById('zip').value = zip;

    // Enable readonly fields briefly to show they're updated
    const fields = ['latitude', 'longitude', 'city', 'state', 'zip'];
    fields.forEach(field => {
        const element = document.getElementById(field);
        element.classList.add('is-valid');
        setTimeout(() => element.classList.remove('is-valid'), 2000);
    });
}

// Update map with selected place
function updateMap(place) {
    const location = place.geometry.location;

    map.setCenter(location);
    map.setZoom(15);

    // Remove existing marker
    if (marker) {
        marker.setMap(null);
    }

    // Add new marker
    marker = new google.maps.Marker({
        position: location,
        map: map,
        title: place.name || 'Selected Location',
        animation: google.maps.Animation.DROP
    });

    // Add info window
    const infoWindow = new google.maps.InfoWindow({
        content: `
            <div class="p-2">
                <h6 class="mb-1">${place.name || 'Selected Location'}</h6>
                <p class="mb-0 text-muted small">${place.formatted_address}</p>
            </div>
        `
    });

    marker.addListener('click', () => {
        infoWindow.open(map, marker);
    });
}

// Image upload handling
function initializeImageUpload() {
    document.getElementById('images').addEventListener('change', function (e) {
        const files = Array.from(e.target.files);

        if (files.length > 10) {
            showError('Maximum 10 images allowed');
            return;
        }

        // Clear previous previews
        document.getElementById('imagePreviewContainer').innerHTML = '';
        uploadedImages = [];

        files.forEach((file, index) => {
            if (file.size > 5 * 1024 * 1024) { // 5MB limit
                showError(`${file.name} is too large. Maximum size is 5MB.`);
                return;
            }

            if (!file.type.match('image.*')) {
                showError(`${file.name} is not a valid image file.`);
                return;
            }

            // Create preview
            const reader = new FileReader();
            reader.onload = function (e) {
                createImagePreview(e.target.result, index, file.name);
            };
            reader.readAsDataURL(file);

            uploadedImages.push(file);
        });
    });
}

// Create image preview with crop option
function createImagePreview(src, index, filename) {
    const container = document.getElementById('imagePreviewContainer');

    const previewDiv = document.createElement('div');
    previewDiv.className = 'col-6 mb-3';
    previewDiv.innerHTML = `
        <div class="card">
            <img src="${src}" class="card-img-top" style="height: 150px; object-fit: cover;" alt="Preview">
            <div class="card-body p-2">
                <h6 class="card-title small mb-1">${filename}</h6>
                <button type="button" class="btn btn-primary btn-sm me-1" onclick="cropImage(${index}, '${src}')">
                    <i class="bx bx-crop"></i> Crop
                </button>
                <button type="button" class="btn btn-danger btn-sm" onclick="removeImage(${index})">
                    <i class="bx bx-trash"></i>
                </button>
            </div>
        </div>
    `;

    container.appendChild(previewDiv);
}

// Crop image function
function cropImage(index, src) {
    currentImageIndex = index;
    document.getElementById('cropImage').src = src;

    const modal = new bootstrap.Modal(document.getElementById('cropModal'));
    modal.show();

    // Initialize cropper after modal is shown
    document.getElementById('cropModal').addEventListener('shown.bs.modal', function () {
        const image = document.getElementById('cropImage');
        cropper = new Cropper(image, {
            aspectRatio: 16 / 9,
            viewMode: 1,
            responsive: true,
            restore: true,
            guides: true,
            center: true,
            highlight: false,
            cropBoxMovable: true,
            cropBoxResizable: true,
            toggleDragModeOnDblclick: false,
        });
    }, { once: true });
}

// Handle crop and save
function initializeCropHandler() {
    document.getElementById('cropBtn').addEventListener('click', function () {
        if (cropper) {
            const canvas = cropper.getCroppedCanvas({
                width: 800,
                height: 450,
                imageSmoothingEnabled: true,
                imageSmoothingQuality: 'high',
            });

            // Convert to base64
            const croppedImage = canvas.toDataURL('image/jpeg', 0.9);

            // Store cropped image
            storeCroppedImage(currentImageIndex, croppedImage);

            // Update preview
            updateImagePreview(currentImageIndex, croppedImage);

            // Close modal
            bootstrap.Modal.getInstance(document.getElementById('cropModal')).hide();

            // Destroy cropper
            cropper.destroy();
            cropper = null;

            showSuccess('Image cropped successfully!');
        }
    });
}

// Store cropped image
function storeCroppedImage(index, croppedData) {
    const container = document.getElementById('croppedImagesContainer');

    // Remove existing input for this index
    const existingInput = container.querySelector(`input[data-index="${index}"]`);
    if (existingInput) {
        existingInput.remove();
    }

    // Add new hidden input
    const input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'cropped_images[]';
    input.value = croppedData;
    input.setAttribute('data-index', index);

    container.appendChild(input);
}

// Update image preview after cropping
function updateImagePreview(index, croppedSrc) {
    const previews = document.querySelectorAll('#imagePreviewContainer .card img');
    if (previews[index]) {
        previews[index].src = croppedSrc;
        previews[index].parentElement.classList.add('border-success');
    }
}

// Remove image
function removeImage(index) {
    // Remove from preview
    const previews = document.querySelectorAll('#imagePreviewContainer .col-6');
    if (previews[index]) {
        previews[index].remove();
    }

    // Remove cropped data
    const croppedInput = document.querySelector(`input[data-index="${index}"]`);
    if (croppedInput) {
        croppedInput.remove();
    }

    // Remove from uploadedImages array
    uploadedImages.splice(index, 1);

    showSuccess('Image removed successfully!');
}

// Utility functions
function showSuccess(message) {
    // Create and show success toast/alert
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bx bx-check-circle me-2"></i>${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertDiv);

    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 4000);
}

function showError(message) {
    // Create and show error toast/alert
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bx bx-error-circle me-2"></i>${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertDiv);

    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 6000);
}

// Form validation before submit
function initializeFormValidation() {
    document.getElementById('courtForm').addEventListener('submit', function (e) {
        const requiredFields = ['name', 'location', 'latitude', 'longitude', 'city', 'state', 'zip'];
        let isValid = true;

        requiredFields.forEach(field => {
            const element = document.getElementById(field);
            if (!element.value.trim()) {
                element.classList.add('is-invalid');
                isValid = false;
            } else {
                element.classList.remove('is-invalid');
            }
        });

        if (!isValid) {
            e.preventDefault();
            showError('Please fill in all required fields.');
            return false;
        }

        // Show loading state
        const submitBtn = document.getElementById('submitBtn');
        submitBtn.innerHTML = '<i class="bx bx-loader-alt bx-spin me-2"></i>Creating Court...';
        submitBtn.disabled = true;
    });
}

// Handle modal cleanup
function initializeModalCleanup() {
    document.getElementById('cropModal').addEventListener('hidden.bs.modal', function () {
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });
}

// Input validation and formatting
function initializeInputValidation() {
    // Phone number formatting
    const phoneInput = document.getElementById('phone');
    phoneInput.addEventListener('input', function (e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length >= 6) {
            value = value.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
        } else if (value.length >= 3) {
            value = value.replace(/(\d{3})(\d{1,3})/, '($1) $2');
        }
        e.target.value = value;
    });

    // Number inputs validation
    const numberInputs = document.querySelectorAll('input[type="number"]');
    numberInputs.forEach(input => {
        input.addEventListener('input', function (e) {
            if (e.target.value < 0) e.target.value = 0;
            if (e.target.value > 100) e.target.value = 100;
        });
    });
}

// Initialize all functionality when DOM is ready
document.addEventListener('DOMContentLoaded', function () {
    initializeImageUpload();
    initializeCropHandler();
    initializeFormValidation();
    initializeModalCleanup();
    initializeInputValidation();
});
