// signup.js
window.addEventListener('DOMContentLoaded', function () {
    const locationInput   = document.getElementById('location_name');
    const latitudeInput   = document.getElementById('latitude');
    const longitudeInput  = document.getElementById('longitude');
    const locationStatus  = document.getElementById('locationStatus');
    const getLocationBtn  = document.getElementById('getLocationBtn');
    const phoneInput      = document.getElementById('phoneInput');
    const phoneCheckStatus= document.getElementById('phoneCheckStatus');

    let autocomplete = null;
    let geocoder     = null;

    function showStatus(type, message) {
        if (!locationStatus) return;
        locationStatus.style.display = 'block';
        let html = '';
        if (type === 'success') {
            html = '<div class="alert-success"><i class="fas fa-check-circle"></i> ' + message + '</div>';
        } else if (type === 'error') {
            html = '<div class="alert-error"><i class="fas fa-exclamation-circle"></i> ' + message + '</div>';
        } else {
            html = '<div class="alert-warning"><i class="fas fa-spinner fa-spin"></i> ' + message + '</div>';
        }
        locationStatus.innerHTML = html;
    }

    // Initialize Google Places autocomplete when Maps script is ready
    function initPlaces() {
        if (!locationInput || !window.google || !google.maps || !google.maps.places) {
            return;
        }

        autocomplete = new google.maps.places.Autocomplete(locationInput, {
            types: ['geocode'],
            componentRestrictions: { country: ['us', 'ca'] }
        });

        autocomplete.addListener('place_changed', function () {
            const place = autocomplete.getPlace();
            if (!place.geometry || !place.geometry.location) {
                showStatus('error', 'Could not get coordinates for that place. Please choose another suggestion.');
                return;
            }

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

            latitudeInput.value  = lat.toFixed(6);
            longitudeInput.value = lng.toFixed(6);

            if (!locationInput.value && place.formatted_address) {
                locationInput.value = place.formatted_address;
            }

            showStatus('success', 'Location set from search: ' + lat.toFixed(4) + ', ' + lng.toFixed(4));
        });
    }

    // Initialize Geocoder
    function initGeocoder() {
        if (window.google && google.maps) {
            geocoder = new google.maps.Geocoder();
        }
    }

    // Use current device location + Google Geocoder
    if (getLocationBtn) {
        getLocationBtn.addEventListener('click', function () {
            if (!navigator.geolocation) {
                showStatus('error', 'Geolocation is not supported by your browser.');
                return;
            }

            getLocationBtn.disabled  = true;
            getLocationBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Getting location...';
            showStatus('loading', 'Requesting your device location...');

            navigator.geolocation.getCurrentPosition(
                function (position) {
                    const lat = position.coords.latitude;
                    const lng = position.coords.longitude;

                    latitudeInput.value  = lat.toFixed(6);
                    longitudeInput.value = lng.toFixed(6);

                    showStatus('loading', 'Location detected. Looking up address with Google...');

                    if (!geocoder) {
                        try {
                            geocoder = new google.maps.Geocoder();
                        } catch (e) {
                            showStatus('error', 'Could not initialize Google Geocoder.');
                            getLocationBtn.disabled  = false;
                            getLocationBtn.innerHTML = '<i class="fas fa-location-crosshairs"></i> Use My Current Location';
                            return;
                        }
                    }

                    geocoder.geocode({ location: { lat: lat, lng: lng } }, function (results, status) {
                        if (status === 'OK' && results && results.length > 0) {
                            const addr = results[0].formatted_address;
                            if (locationInput && !locationInput.value) {
                                locationInput.value = addr;
                            }
                            showStatus('success', 'Location set from device: ' + lat.toFixed(4) + ', ' + lng.toFixed(4));
                        } else {
                            showStatus('success', 'Coordinates set: ' + lat.toFixed(4) + ', ' + lng.toFixed(4));
                        }

                        getLocationBtn.disabled  = false;
                        getLocationBtn.innerHTML = '<i class="fas fa-location-crosshairs"></i> Use My Current Location';
                    });
                },
                function (error) {
                    let msg = 'Unable to get your location. ';
                    if (error.code === error.PERMISSION_DENIED) msg += 'Permission denied.';
                    else if (error.code === error.POSITION_UNAVAILABLE) msg += 'Position unavailable.';
                    else if (error.code === error.TIMEOUT) msg += 'Request timed out.';
                    else msg += 'Unknown error.';
                    showStatus('error', msg);
                    getLocationBtn.disabled  = false;
                    getLocationBtn.innerHTML = '<i class="fas fa-location-crosshairs"></i> Use My Current Location';
                }
            );
        });
    }

    // Phone blur hint: tell user about manage page (no AJAX)
    if (phoneInput && phoneCheckStatus) {
        phoneInput.addEventListener('blur', function () {
            const phone = phoneInput.value.trim();
            if (phone.length < 10) {
                phoneCheckStatus.style.display = 'none';
                return;
            }
            phoneCheckStatus.style.display = 'block';
            phoneCheckStatus.innerHTML =
                '<small style="color: #856404;">If this number is already registered, use the <a href="manage.php" style="color:#007bff;">Manage Page</a> to update your settings.</small>';
            phoneCheckStatus.style.background   = '#fff3cd';
            phoneCheckStatus.style.padding      = '8px';
            phoneCheckStatus.style.borderRadius = '4px';
            phoneCheckStatus.style.marginTop    = '8px';
        });

        phoneInput.addEventListener('input', function () {
            phoneCheckStatus.style.display = 'none';
        });
    }

    // Try to auto-set timezone from browser if empty/default
    const timezoneSelect = document.getElementById('timezone');
    if (timezoneSelect && !timezoneSelect.value) {
        try {
            const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone;
            for (let i = 0; i < timezoneSelect.options.length; i++) {
                if (timezoneSelect.options[i].value === browserTz) {
                    timezoneSelect.value = browserTz;
                    break;
                }
            }
        } catch (e) {
            // ignore
        }
    }

    // When Google script is ready, init Places + Geocoder
    if (document.readyState === 'complete') {
        initPlaces();
        initGeocoder();
    } else {
        window.addEventListener('load', function () {
            initPlaces();
            initGeocoder();
        });
    }
});