jQuery(function($) {
    'use strict';
    window.WTC = window.WTC || {};
    WTC.MyAccount = {
        init: function() {
            if (!$('body').hasClass('woocommerce-edit-address')) {
                return;
            }
            this.bindEvents();
            this.correctInitialNeighborhoods('#billing_address_1');
            this.correctInitialNeighborhoods('#shipping_address_1');
            $('#billing_address_1').trigger('change');
            $('#shipping_address_1').trigger('change');
            $('#billing_invoice_type').trigger('change');
            if ($('#billing_state').data('prefilled') !== true) {
                $('#billing_state').trigger('change');
            }
            if ($('#shipping_state').data('prefilled') !== true) {
                $('#shipping_state').trigger('change');
            }
        },
        bindEvents: function() {
            var self = this;
            $('#billing_invoice_type').on('change', function() {
                self._toggleInvoiceFields($(this).val());
            });
            $('body').on('change', '#billing_state, #shipping_state', function() {
                const prefix = $(this).attr('id').includes('billing') ? 'billing' : 'shipping';
                const stateCode = $(this).val();
                $(`#${prefix}_postcode`).val('');
                $(`#${prefix}_city`).empty().append('<option value="">İlçe seçiniz</option>').trigger('change');
                $(`#${prefix}_address_1`).empty().append('<option value="">Mahalle seçiniz</option>').prop('disabled', true).trigger('change');
                if (stateCode) {
                    self.loadCities(stateCode, $(`#${prefix}_city`));
                }
            });
            $('body').on('change', '#billing_city, #shipping_city', function() {
                const prefix = $(this).attr('id').includes('billing') ? 'billing' : 'shipping';
                const city = $(this).val();
                const stateCode = $(`#${prefix}_state`).val();
                $(`#${prefix}_postcode`).val('');
                $(`#${prefix}_address_1`).empty().append('<option value="">Mahalle seçiniz</option>').trigger('change');
                if (city && stateCode) {
                    $(`#${prefix}_address_1`).prop('disabled', false);
                    self.loadNeighborhoods(stateCode, city, $(`#${prefix}_address_1`));
                } else {
                    $(`#${prefix}_address_1`).prop('disabled', true);
                }
            });
            $('body').on('change', '#billing_address_1, #shipping_address_1', function() {
                const prefix = $(this).attr('id').includes('billing') ? 'billing' : 'shipping';
                const postalCode = $(this).find('option:selected').data('postal-code');
                $(`#${prefix}_postcode`).val(postalCode || '');
            });
            self.checkNeighborhoodFieldsState();
            $('#billing_invoice_type').select2({
                width: '100%',
                minimumResultsForSearch: Infinity,
                dropdownParent: $('#billing_invoice_type_field')
            });
            $('#billing_state, #shipping_state, #billing_city, #shipping_city, #billing_address_1, #shipping_address_1').select2({
                width: '100%'
            });
        },
        _toggleInvoiceFields: function(invoiceType) {
            const nameFields = $('#billing_first_name_field, #billing_last_name_field');
            const tcknField = $('#billing_tckn_field');
            const tcknInput = $('#billing_tckn');
            const corporateFields = $('#billing_company_field, #billing_tax_number_field, #billing_tax_office_field');
            const tcknRequired = wtc_params.tckn_required === 'yes';
            const corporateNamesRequired = wtc_params.corporate_names_required === 'yes';
            if (invoiceType === 'individual') {
                corporateFields.hide();
                $('#billing_company, #billing_tax_number, #billing_tax_office').prop('required', false);
                nameFields.show();
                $('#billing_first_name, #billing_last_name').prop('required', true);
                tcknField.show();
                tcknInput.prop('required', tcknRequired);
            } else { 
                tcknField.hide();
                tcknInput.prop('required', false);
                corporateFields.show();
                $('#billing_company, #billing_tax_number, #billing_tax_office').prop('required', true);
                if (corporateNamesRequired) {
                    nameFields.show();
                    $('#billing_first_name, #billing_last_name').prop('required', true);
                } else {
                    nameFields.hide();
                    $('#billing_first_name, #billing_last_name').prop('required', false);
                }
            }
        },
        _makeAjaxRequest: function(action, data, field, isNeighborhood = false) {
            $.ajax({
                url: wtc_params.ajax_url,
                type: 'POST',
                data: {
                    action: action,
                    nonce: wtc_params.nonce,
                    ...data
                },
                beforeSend: function() {
                    field.prop('disabled', true).empty().append('<option value="">Yükleniyor...</option>').trigger('change');
                },
                success: function(response) {
                    if (response.success && response.data) {
                        const placeholderText = field.prev('label').text() + ' seçiniz';
                        field.empty().append(`<option value="">${placeholderText}</option>`);
                        $.each(response.data, function(key, value) {
                            if(key) {
                                const option = $('<option></option>').attr('value', key).text(key);
                                if(isNeighborhood) {
                                    option.attr('data-postal-code', value);
                                }
                                field.append(option);
                            }
                        });
                    }
                },
                error: function() {
                     field.empty().append(`<option value="">Hata oluştu</option>`).trigger('change');
                },
                complete: function() {
                    field.prop('disabled', false).trigger('change.select2');
                }
            });
        },
        loadCities: function(stateCode, cityField) {
            this._makeAjaxRequest('wtc_get_cities', { state_code: stateCode }, cityField);
        },
        loadNeighborhoods: function(stateCode, city, neighborhoodField) {
            this._makeAjaxRequest('wtc_get_neighborhoods', { state_code: stateCode, city: city }, neighborhoodField, true);
        },
        checkNeighborhoodFieldsState: function() {
            const self = this;
            ['billing', 'shipping'].forEach(function(prefix) {
                const cityField = $(`#${prefix}_city`);
                const neighborhoodField = $(`#${prefix}_address_1`);
                if (cityField.length && neighborhoodField.length) {
                    const cityValue = cityField.val();
                    const stateValue = $(`#${prefix}_state`).val();
                    if (!cityValue || !stateValue) {
                        neighborhoodField.prop('disabled', true);
                    } else {
                        neighborhoodField.prop('disabled', false);
                    }
                }
            });
        },
        correctInitialNeighborhoods: function(selector) {
            const field = $(selector);
            if (field.length && field.find('option').length > 1 && !field.data('corrected')) {
                const selectedValue = field.val();
                const newOptions = [];
                field.find('option').each(function() {
                    const $option = $(this);
                    const name = $option.val();
                    const postal = $option.text(); 
                    if (!name) return; 
                    newOptions.push(
                        $('<option></option>').attr('value', name).attr('data-postal-code', postal).text(name)
                    );
                });
                if (newOptions.length > 0) {
                    const placeholder = field.find('option:first').clone();
                    field.empty().append(placeholder).append(newOptions);
                    field.val(selectedValue);
                    field.data('corrected', true); 
                }
            }
        }
    };
    WTC.MyAccount.init();
});