// scripts.js

//$(document).ready(function() {
//    $('[data-toggle="tooltip"]').tooltip();
//});

let map;
let marker;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 38.9071, lng: -77.0368 },
        zoom: 8
    });

    marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map,
        draggable: true
    });

    google.maps.event.addListener(map, 'click', function(event) {
        placeMarker(event.latLng);
    });

    google.maps.event.addListener(marker, 'dragend', function(event) {
        document.getElementById('latitude').value = event.latLng.lat();
        document.getElementById('longitude').value = event.latLng.lng();
    });

    placeMarker(map.getCenter());
}

function placeMarker(location) {
    marker.setPosition(location);
    map.panTo(location);
    document.getElementById('latitude').value = location.lat();
    document.getElementById('longitude').value = location.lng();
}

function performMapLookup() {
    const address = document.getElementById('mapLookupInput').value;
    if (address) {
        const geocoder = new google.maps.Geocoder();
        geocoder.geocode({ address: address }, function(results, status) {
            if (status === 'OK') {
                map.setCenter(results[0].geometry.location);
                placeMarker(results[0].geometry.location);
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
}


// Handle Enter key for map lookup
document.getElementById('mapLookupInput').addEventListener('keypress', function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        performMapLookup();
    }
});


document.getElementById('lookupIcon').addEventListener('click', performMapLookup);

document.getElementById('mapForm').addEventListener('submit', function(event) {
    event.preventDefault();
    performMapLookup();
});

document.getElementById('populateButton').addEventListener('click', function() {
    console.log("populateButton Clicked")
    const latitude = document.getElementById('latitude').value;
    const longitude = document.getElementById('longitude').value;
    const miles = document.getElementById('milesInput').value;
    //const searchInput = document.getElementById('searchInput').value;

    // Fetch all checked checkboxes
    const searchInput = Array.from(document.querySelectorAll('input.form-check-input:checked')).map(checkbox => checkbox.value);

    console.log("Selected POIs:", searchInput);
    console.log("Latitude:", latitude);
    console.log("Longitude:", longitude);
    console.log("Miles:", miles);



    if (latitude && longitude && miles && searchInput) {
        document.getElementById('overlay').style.display = 'block';
        document.getElementById('loader').style.display = 'block';

        $.ajax({
            url: '/populate_data', // Replace with your backend endpoint
            type: 'POST',
            contentType: 'application/json',
            timeout: 600000, 
            data: JSON.stringify({
                latitude: latitude,
                longitude: longitude,
                miles: miles,
                searchInput: searchInput
            }),
            success: function(response) {
                document.getElementById('overlay').style.display = 'none';
                document.getElementById('loader').style.display = 'none';
                displayResults(response);
                scrollToResults();
            },
            error: function(error) {
                document.getElementById('overlay').style.display = 'none';
                document.getElementById('loader').style.display = 'none';
                alert('Error populating data');
                console.error(error);
            }
        });
    } else {
        alert('Please fill in all fields.');
    }
});









function scrollToResults() {
    const resultsSection = document.getElementById('dataDisplay');
    resultsSection.scrollIntoView({ behavior: 'smooth' });
}


// Validate Input
function validateInput() {
    var input = document.getElementById("milesInput");
    var value = input.value.trim();

    if (value === "" || isNaN(value)) {
        alert("Please enter a valid number.");
        input.value = "";
        return false;
    }
    return true;
}

document.getElementById('milesForm').addEventListener('submit', function(event) {
    if (!validateInput()) {
        event.preventDefault();  // Prevent form submission if the input is invalid
    }
});






document.getElementById('clearButton').addEventListener('click', function() {
    document.getElementById('searchInput').value = '';
    document.getElementById('mapLookupInput').value = '';
    document.getElementById('latitude').value = '';
    document.getElementById('longitude').value = '';
    document.getElementById('milesInput').value = '';

    document.getElementById('dataDisplay').style.display = 'none';
    document.getElementById('overlay').style.display = 'none';
    document.getElementById('loader').style.display = 'none';

    const mapCenter = new google.maps.LatLng(38.9071, -77.0368);
    map.setCenter(mapCenter);
    placeMarker(mapCenter);
});




