jQuery(document).ready(function($) {
    const $countrySelect = $('#user_country');
    const $stateSelect = $('#user_state');
    const $stateOtherInput = $('#user_state_other');

    // Function to populate states/provinces
    function loadStates(country) {
        console.log(`Loading states/provinces for ${country}`); // Keep log for debugging
        $stateSelect.find('option').not('[value=""],[value="Other"]').remove(); // Clear existing options except defaults

        let options = {};
        if (country === 'United States' && typeof hvacRegistrationData !== 'undefined' && hvacRegistrationData.states) {
            options = hvacRegistrationData.states;
        } else if (country === 'Canada' && typeof hvacRegistrationData !== 'undefined' && hvacRegistrationData.provinces) {
            options = hvacRegistrationData.provinces;
        } else {
            // If country is not US/CA or data is missing, ensure 'Other' is selected and input shown
             $stateSelect.val('Other').trigger('change'); // Trigger change to show 'Other' input if needed
             return;
        }

        // Append new options
        $.each(options, function(value, label) {
            // Append before the 'Other' option if it exists, otherwise just append
            const $otherOption = $stateSelect.find('option[value="Other"]');
            const $newOption = $('<option></option>').val(value).text(label);
            if ($otherOption.length > 0) {
                 $newOption.insertBefore($otherOption);
            } else {
                 $stateSelect.append($newOption);
            }
        });

         // Ensure the 'Other' input is hidden initially when states/provinces are loaded
         $stateOtherInput.hide().val('');
         // Reset state selection to default prompt
         $stateSelect.val('');
    }

    // Handle state/province field visibility based on 'Other' selection
    $stateSelect.change(function() {
        if ($(this).val() === 'Other') {
            $stateOtherInput.show().prop('required', true); // Make required if Other is selected
        } else {
            $stateOtherInput.hide().val('').prop('required', false); // Hide and make not required
        }
    }).trigger('change'); // Trigger on load to set initial visibility

    // Handle country change to show/hide/populate state field
    $countrySelect.change(function() {
        const country = $(this).val();

        if (country === 'United States' || country === 'Canada') {
            loadStates(country);
            $stateSelect.show().prop('required', true); // Show and require state select
            $stateOtherInput.prop('required', false); // Ensure 'Other' input is not required initially
        } else if (country) {
            // For other countries, hide state select, select 'Other', show/require 'Other' input
            $stateSelect.hide().val('Other').prop('required', false); // Hide and make not required
            $stateOtherInput.show().prop('required', true); // Show and require 'Other' input
        } else {
            // No country selected
            $stateSelect.hide().val('').prop('required', false); // Hide and make not required
            $stateOtherInput.hide().val('').prop('required', false); // Hide and make not required
        }
    }).trigger('change'); // Trigger on load to set initial state based on pre-selected country (if any)

});