$(document).ready(function() {
    // Handle country change event for any form
    $(document).on('change', '#country', function() {
        var countryId = $(this).val();
        var stateSelect = $('#state');
        var baseUrl = $('#base_url').val();
        
        // Only proceed if state is a select element and exists
        if (stateSelect.length && stateSelect.is('select')) {
            // Clear existing states
            stateSelect.empty();
            stateSelect.append('<option value="">Select State</option>');
            
            if (countryId) {
                // Show loading state
                stateSelect.append('<option value="">Loading states...</option>');
                
                // Fetch states for selected country
                $.ajax({
                    url: baseUrl + 'state/get_states_by_country',
                    type: 'POST',
                    data: {
                        country_id: countryId
                    },
                    dataType: 'json',
                    success: function(response) {
                        // Clear loading option
                        stateSelect.empty();
                        stateSelect.append('<option value="">Select State</option>');
                        
                        if (response.success && response.states.length > 0) {
                            $.each(response.states, function(index, state) {
                                stateSelect.append('<option value="' + state.id + '">' + state.state + '</option>');
                            });
                        } else {
                            stateSelect.append('<option value="">No States Found</option>');
                        }
                    },
                    error: function() {
                        // Clear loading option
                        stateSelect.empty();
                        stateSelect.append('<option value="">Select State</option>');
                        stateSelect.append('<option value="">Error loading states</option>');
                    }
                });
            }
        }
        
        // DO NOT touch city field - it's a text input, not a dropdown
        // The city field should remain as user typed it
    });
    
    // Initialize states on page load if country is already selected
    var initialCountryId = $('#country').val();
    if (initialCountryId) {
        $('#country').trigger('change');
    }
});