<script>
    $(document).ready(function () {
        let countryId = $('#country_id').val();
        let stateId = $('#state_id').val();
        let cityId = $('#city_id').val();
        let pageSize = 10;

        /* Country Listing */
        function initCountrySelect() {
            $('#countryData').select2({
                placeholder: `<%= trans.messages.please_select + ' ' + trans.cruds.ADDRESS.fields.country %>`,
                allowClear: true,
                minimumInputLength: 0,
                ajax: {
                    url: '/admin/countries',
                    type: 'GET',
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        return {
                            name: params.term,
                            page: params.page || 1,
                            length: pageSize
                        };
                    },
                    processResults: function(response, params) {
                        params.page = params.page || 1;

                        if (!response || !response.data || !Array.isArray(response.data.data)) {
                            console.error('Invalid response format', response);
                            return { results: [] };
                        }

                        const results = response.data.data;

                        return {
                            results: results.map(country => ({
                                id: country._id,
                                text: country.name
                            })),
                            pagination: {
                                more: results.length === pageSize
                            }
                        };
                    },
                    error: function(xhr, status, error) {
                        console.error('Select2 AJAX Error:', status, error);
                    }
                }
            });

            if (countryId) {
                $.ajax({
                    url: `/admin/countries/${countryId}`,
                    type: 'GET',
                    dataType: 'json'
                }).then(function(response) {
                    if (response.status) {
                        const country = response.data.data;
                        const option = new Option(country.name, country._id, true, true);
                        $('#countryData').append(option).trigger('change');
                        initStateSelect(countryId);
                    }
                });
            }
        }

        setTimeout(function() {
            initCountrySelect();
        }, 200);

        $('#countryData').on('change', function () {
            const newCountryId = $(this).val();
            $('#stateData').val(null).trigger('change');
            $('#cityData').val(null).trigger('change');            

            
            
            if (newCountryId && (countryId !== newCountryId)) {
                countryId = null;
                stateId = null;
                cityId = null;

                $('#state_id').val('');
                $('#city_id').val('');
                
                initStateSelect(newCountryId);
            }
        });

        function initStateSelect(countryId) {
            $('#stateData').select2({
                placeholder: `<%= trans.messages.please_select + ' ' + trans.cruds.ADDRESS.fields.state %>`,
                allowClear: true,
                minimumInputLength: 0,
                ajax: {
                    url: '/admin/states',
                    type: 'GET',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            name: params.term || '',
                            country_id: countryId,
                            page: params.page || 1,
                            length: 10
                        };
                    },
                    processResults: function (response, params) {
                        const results = response?.data?.data || [];
                        params.page = params.page || 1;

                        return {
                            results: results.map(state => ({
                                id: state._id,
                                text: state.name
                            })),
                            pagination: {
                                more: results.length === 10
                            }
                        };
                    }
                }
            });

            if (stateId) {
                $.ajax({
                    url: `/admin/states/${stateId}`,
                    type: 'GET',
                    dataType: 'json'
                }).then(function(response) {
                    if (response.status) {
                        const state = response.data.data;
                        const option = new Option(state.name, state._id, true, true);
                        $('#stateData').append(option).trigger('change');
                        initCitySelect(stateId);
                    }
                });
            }
        }

        $('#stateData').on('change', function () {
            const newStateId = $(this).val();
            $('#cityData').val(null).trigger('change');
            if (newStateId && (newStateId !== stateId)) {
                stateId = null;
                cityId = null;

                $('#state_id').val('');
                $('#city_id').val('');
                initCitySelect(newStateId);
            }
        });

        function initCitySelect(stateId) {
            $('#cityData').select2({
                placeholder: `<%= trans.messages.please_select + ' ' + trans.cruds.ADDRESS.fields.city %>`,
                allowClear: true,
                minimumInputLength: 0,
                ajax: {
                    url: '/admin/cities',
                    type: 'GET',
                    dataType: 'json',
                    delay: 250,
                    data: function (params) {
                        return {
                            name: params.term || '',
                            state_id: stateId,
                            page: params.page || 1,
                            length: 10
                        };
                    },
                    processResults: function (response, params) {
                        const results = response?.data?.data || [];
                        params.page = params.page || 1;

                        return {
                            results: results.map(city => ({
                                id: city._id,
                                text: city.name
                            })),
                            pagination: {
                                more: results.length === 10
                            }
                        };
                    }
                }
            });

            if (cityId) {
                $.ajax({
                    url: `/admin/cities/${cityId}`,
                    type: 'GET',
                    dataType: 'json'
                }).then(function(response) {
                    if (response.status) {
                        const city = response.data.data;
                        const option = new Option(city.name, city._id, true, true);
                        $('#cityData').append(option).trigger('change');
                    }
                });
            }
        }
    });
</script>