
function initializeAutocomplete(inputSelector, zipInputSelector, submitSelector) {
    var $input = jQuery(inputSelector);
    if (!$input.length) return;

    var autocomplete = new google.maps.places.Autocomplete(
        $input[0],
        { types: ['geocode'] }
    );

    autocomplete.addListener('place_changed', function () {
        var $zipInput = jQuery(zipInputSelector);
        if ($zipInput.length) {
            fillInZipCode(autocomplete, $zipInput);
        }
        // checkZipCodes();
    });

    if (submitSelector) {
        jQuery(submitSelector).on("click", function () {
            storeMapData(autocomplete);
        });
    }
}

function initAutocompleteDeliveryInputField() {
    initializeAutocomplete('#rental_address', '#rental_zip', '#submit_date');
    initializeAutocomplete('#rental_address_min', '#rental_min_zip_input', '#rental_min_date_form_submit');

    // Initialize other specific autocompletes
    initAutocompleteCheckoutPage();
    // checkZipCodes();
}


function initializeCheckoutAutocomplete(inputSelector, type) {
    var $input = jQuery(inputSelector);
    if (!$input.length) return;

    var autocomplete = new google.maps.places.Autocomplete(
        $input[0],
        { types: ['geocode'] }
    );

    autocomplete.addListener('place_changed', function () {
        autocompleteCheckoutAddress(autocomplete, type);
        // checkZipCodes();
    });
}

function initAutocompleteCheckoutPage() {
    initializeCheckoutAutocomplete('#billing_address_1', 'billing');
    initializeCheckoutAutocomplete('#shipping_address_1', 'shipping');
    initializeCheckoutAutocomplete('#rental_pick_up_address_1', 'pickup');
    // checkZipCodes();

    initializeCheckoutAutocomplete('#rntp-wish-location', 'wish')
    // initAutocompleteWishlistForm()
}

// function initAutocompleteWishlistForm() {
//     initializeCheckoutAutocomplete('#rntp-wish-location', 'wish');
// }

function setAddressField(fieldSelector, value) {
    if (jQuery(fieldSelector).length) {
        jQuery(fieldSelector).val(value).trigger('change');
    }
}

function extractAddressComponent(components, type) {
    for (let i = 0; i < components.length; i++) {
        if (components[i].types.includes(type)) {

            if (type === 'locality') {
                return components[i]['long_name']
            } else if (type === 'administrative_area_level_1') {
                return components[i]['short_name']
            } else if (type === 'postal_code') {
                return components[i]['short_name']
            } else if (type === 'country') {
                return components[i]['short_name']
            } else if (type === 'route') {
                return components[i]['long_name'] || components[i]['short_name']
            } else if (type === 'street_number') {
                return components[i]['long_name'] || components[i]['short_name']
            } else if (type === 'neighborhood') {
                return components[i]['long_name'] || components[i]['short_name']
            } else if (type === 'colloquial_area') {
                return components[i]['short_name']
            } else if (type === 'subpremise') {
                return components[i]['long_name'] || components[i]['short_name']
            } else if (type === 'administrative_area_level_2') {
                return components[i]['short_name']
            }
            
            // return components[i]['long_name'] || components[i]['short_name'];
        }
    }
    return '';
}

function autocompleteCheckoutAddress(autocomplete, type) {
    const place = autocomplete.getPlace();
    if (!place || !place.geometry) return;

    const lat = place.geometry.location.lat();
    const lng = place.geometry.location.lng();

    const components = place.address_components;
    const addressSelectors = {
        billing: {
            state: "#billing_state",
            country: "#billing_country",
            postcode: "#billing_postcode",
            address2: "#billing_address_2",
            city: "#billing_city",
            address1: "#billing_address_1",
        },
        shipping: {
            state: "#shipping_state",
            country: "#shipping_country",
            postcode: "#shipping_postcode",
            address2: "#shipping_address_2",
            city: "#shipping_city",
            address1: "#shipping_address_1",
        },
        pickup: {
            state: "#rental_pick_up_state",
            country: "#rental_pick_up_country",
            postcode: "#rental_pick_up_postcode",
            address2: "#rental_pick_up_address_2",
            city: "#rental_pick_up_city",
            address1: "#rental_pick_up_address_1",
        },
        wish: {
            state: "#rntp-wish-state",
            country: "#rntp-wish-country",
            postcode: "#rntp-wish-zip",
            address2: "#rntp-wish-address-2",
            city: "#rntp-wish-city",
            address1: "#rntp-wish-location",
        }
    };

    const selectors = addressSelectors[type];

    // Extract components
    const city = extractAddressComponent(components, 'locality') || 
                extractAddressComponent(components, 'administrative_area_level_2') || 
                extractAddressComponent(components, 'sublocality_level_1');

    const state = extractAddressComponent(components, 'administrative_area_level_1');
    const country = extractAddressComponent(components, 'country');
    const postcode = extractAddressComponent(components, 'postal_code');
    const address2 = extractAddressComponent(components, 'subpremise');

    let address1 = '';
    const route = extractAddressComponent(components, 'route');
    const streetNumber = extractAddressComponent(components, 'street_number');
    const neighborhood = extractAddressComponent(components, 'neighborhood');
    const colloquialArea = extractAddressComponent(components, 'colloquial_area');

    if (route || streetNumber) {
        address1 = `${streetNumber} ${route}`.trim();
    } else if (neighborhood || colloquialArea) {
        address1 = `${neighborhood} ${colloquialArea}`.trim();
    } else if (components.length > 1) {
        address1 = `${components[0].long_name} ${components[1].long_name}`.trim();
    }

    // Set extracted values
    setAddressField(selectors.city, city);
    setAddressField(selectors.state, state);
    setAddressField(selectors.country, country);
    setAddressField(selectors.postcode, postcode);
    setAddressField(selectors.address2, address2);
    setAddressField(selectors.address1, address1);

    if (type === 'pickup') {
        // Store latitude and longitude in cookies
        setCookie("rental_client_pickup_address_lat", lat);
        setCookie("rental_client_pickup_address_lng", lng);
    } else if (type === 'wish') {
        // Store latitude and longitude in cookies
        setCookie("rental_client_wish_address_lat", lat);
        setCookie("rental_client_wish_address_lng", lng);
    } else {

        // Shipping or Billing type 
        // Store latitude and longitude in cookies
        setCookie("rental_client_address_lat", lat);
        setCookie("rental_client_address_lng", lng);
    }
    
}



function getPlaceComponent(components, type) {
    for (let i = 0; i < components.length; i++) {
        if (components[i].types.includes(type)) {
            return components[i]['long_name'] || components[i]['short_name'];
        }
    }
    return '';
}

function addToAddressParts(parts, key, value) {
    if (value) {
        parts.push({ key, value });
    }
}

function fillInZipCode(autocomplete, $inputZip) {
    const place = autocomplete.getPlace();
    if (!place || !place.address_components) return;

    const zip = getPlaceComponent(place.address_components, 'postal_code');
    $inputZip.val(zip || '');
}

function storeMapData(autocomplete) {
    const place = autocomplete.getPlace();
    if (!place || !place.geometry || !place.address_components) return;

    const lat = place.geometry.location.lat();
    const lng = place.geometry.location.lng();
    const components = place.address_components;
    const addressParts = [];

    const city = getPlaceComponent(components, 'locality') || 
                getPlaceComponent(components, 'administrative_area_level_2') || 
                getPlaceComponent(components, 'sublocality_level_1');
    const state = getPlaceComponent(components, 'administrative_area_level_1');
    const country = getPlaceComponent(components, 'country');
    const zip = getPlaceComponent(components, 'postal_code');
    const address2 = getPlaceComponent(components, 'subpremise');

    let address = '';
    const route = getPlaceComponent(components, 'route');
    const streetNumber = getPlaceComponent(components, 'street_number');
    const neighborhood = getPlaceComponent(components, 'neighborhood');
    const colloquialArea = getPlaceComponent(components, 'colloquial_area');

    if (route || streetNumber) {
        address = `${streetNumber} ${route}`.trim();
    } else if (neighborhood || colloquialArea) {
        address = `${neighborhood} ${colloquialArea}`.trim();
    } else if (components.length > 1) {
        address = `${components[0].long_name} ${components[1].long_name}`.trim();
    }

    // Add components to address parts
    addToAddressParts(addressParts, 'city', city);
    addToAddressParts(addressParts, 'state', state);
    addToAddressParts(addressParts, 'country', country);
    addToAddressParts(addressParts, 'zip', zip);
    addToAddressParts(addressParts, 'address_2', address2);
    addToAddressParts(addressParts, 'address', address);

    // Store data in cookies
    setCookie("rental_google_map_address", JSON.stringify(addressParts));
    setCookie("rental_client_address_lat", lat);
    setCookie("rental_client_address_lng", lng);
}


function loadGoogleMapsScript(callbackName) {
    const scriptId = "google-maps-api";
    if (document.getElementById(scriptId)) return;

    const script = document.createElement("script");
    script.id = scriptId;
    script.type = "text/javascript";
    script.src = `https://maps.googleapis.com/maps/api/js?key=${rentalGoogleMapConfig.google_map_key}&libraries=places&language=en&callback=${callbackName}&loading=async`;
    script.async = true;
    script.defer = true; // Prevents the script from blocking rendering

    // Handle errors
    script.onerror = () => {
        console.error("Failed to load Google Maps script.");
    };

    document.body.appendChild(script);
}


function initScriptLoadingBasedOnFormLayout() {
    const { form_layout: formLayout, show_location: showLocation } = rentalGoogleMapConfig;
    const callbackName = showLocation ? "initAutocompleteDeliveryInputField" : "initAutocompleteCheckoutPage";


    // Ensure script loading happens after DOM is fully loaded
    document.addEventListener("DOMContentLoaded", () => {
        if (formLayout === "in-cart") {
            loadGoogleMapsScript(callbackName);
        } else {
            if (typeof jQuery !== 'undefined') {
                jQuery(document).ajaxStop(() => {
                    loadGoogleMapsScript(callbackName);
                });
            } else {
                console.error("jQuery is not loaded. Cannot attach ajaxStop listener.");
            }
        }
    });
}

initScriptLoadingBasedOnFormLayout()