jQuery(function($) {
    'use strict';
    window.WTC = window.WTC || {};
    WTC.Checkout = {
        init: function() {
            if (typeof $ !== 'function') {
                return;
            }
            this.billingFields = $('.woocommerce-billing-fields__field-wrapper');
            this.billingTitle = $('.woocommerce-billing-fields > h3');
            this.initializeBillingFields();
            this.bindEvents();
            this.correctInitialNeighborhoods('#billing_address_1');
            this.correctInitialNeighborhoods('#shipping_address_1');
            $('#billing_address_1').trigger('change');
            $('#shipping_address_1').trigger('change');
        },
        initializeBillingFields: function() {
            if (wtc_params.is_user_logged_in !== '1') {
                this.billingFields.show();
                return;
            }
            const hasCompleteBillingInfo = (wtc_params.saved_invoice_type === 'individual' && wtc_params.saved_tckn) ||
                                         (wtc_params.saved_invoice_type === 'corporate' && wtc_params.saved_tax_number);
            if (hasCompleteBillingInfo) {
                this.billingFields.hide();
                const savedBillingInfo = $('<div/>', { class: 'wtc-saved-billing-info' });
                let infoHtml = '';
                if (wtc_params.saved_invoice_type === 'individual') {
                    infoHtml += `<p><strong>${wtc_params.saved_first_name || ''} ${wtc_params.saved_last_name || ''}</strong></p>
                                 <p><strong>Bireysel Fatura </strong>| TC Kimlik No: ${wtc_params.saved_tckn || ''}</p>`;
                } else if (wtc_params.saved_invoice_type === 'corporate') {
                    infoHtml += `<p><strong>${wtc_params.saved_company || ''}</strong></p>
                                 <p><strong>Kurumsal Fatura </strong>| Vergi Dairesi/No: ${wtc_params.saved_tax_office || ''} / ${wtc_params.saved_tax_number || ''}</p>`;
                }
                infoHtml += `<p>${wtc_params.saved_address_1 || ''}, ${wtc_params.saved_address_2 || ''}, ${wtc_params.saved_postcode || ''}, ${wtc_params.saved_city || ''}, ${wtc_params.saved_state_name || wtc_params.saved_state || ''}, ${wtc_params.saved_country_name || wtc_params.saved_country || 'TR'}</p>
                             <p><strong>Telefon:</strong> ${wtc_params.saved_phone || ''}</p>`;
                savedBillingInfo.html(infoHtml).insertAfter(this.billingTitle);
                $('<div class="form-row form-row-wide"><label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"><input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox" id="toggle-billing-fields"> <span>' + wtc_params.billing_toggle_text + '</span></label></div>').insertAfter(this.billingTitle);
            } else {
                this.billingFields.show();
            }
        },
        loadUserDataToFields: function() {
            if (wtc_params.is_user_logged_in !== '1') {
                return;
            }
            const fieldMappings = {
                'saved_invoice_type': '#billing_invoice_type',
                'saved_first_name': '#billing_first_name',
                'saved_last_name': '#billing_last_name',
                'saved_company': '#billing_company',
                'saved_tckn': '#billing_tckn',
                'saved_tax_number': '#billing_tax_number',
                'saved_tax_office': '#billing_tax_office',
                'saved_country': '#billing_country',
                'saved_state': '#billing_state',
                'saved_city': '#billing_city',
                'saved_address_1': '#billing_address_1',
                'saved_address_2': '#billing_address_2',
                'saved_postcode': '#billing_postcode',
                'saved_phone': '#billing_phone',
                'saved_shipping_first_name': '#shipping_first_name',
                'saved_shipping_last_name': '#shipping_last_name',
                'saved_shipping_company': '#shipping_company',
                'saved_shipping_country': '#shipping_country',
                'saved_shipping_state': '#shipping_state',
                'saved_shipping_city': '#shipping_city',
                'saved_shipping_address_1': '#shipping_address_1',
                'saved_shipping_address_2': '#shipping_address_2',
                'saved_shipping_postcode': '#shipping_postcode',
                'saved_shipping_name': '#shipping_name'
            };
            $.each(fieldMappings, function(paramKey, fieldId) {
                if (wtc_params[paramKey]) {
                    const field = $(fieldId);
                    if (field.length) {
                        field.val(wtc_params[paramKey]);
                        if (field.is('select')) {
                            const isBillingState = fieldId === '#billing_state';
                            const isShippingState = fieldId === '#shipping_state';
                            if (isBillingState && !wtc_params.saved_city) {
                            }
                            else if (isShippingState && !wtc_params.saved_shipping_city) {
                            }
                            else {
                                field.trigger('change');
                            }
                        }
                    }
                }
            });
        },
        bindEvents: function() {
            var self = this;
            $(document).on('change', '#toggle-billing-fields', function() {
                if ($(this).is(':checked')) {
                    $('.wtc-saved-billing-info').slideUp(200);
                    self.billingFields.slideDown(200);
                    $(this).prop('disabled', true);
                }
            });
            this.loadUserDataToFields();
            const selectedInvoiceType = $('#billing_invoice_type').val();
            self._toggleInvoiceFields(selectedInvoiceType); 
            $('#billing_invoice_type').on('change', function() {
                self._toggleInvoiceFields($(this).val()); 
            });
            const orderNotesField = $('#order_comments_field');
            if (orderNotesField.length) {
                orderNotesField.hide();
                $('#toggle-order-notes').on('change', function() {
                    if ($(this).is(':checked')) {
                        orderNotesField.slideDown(200);
                    } else {
                        orderNotesField.slideUp(200);
                        $('#order_comments').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().find('input').prop('required', false);
                nameFields.show().find('input').prop('required', true);
                tcknField.show();
                tcknInput.prop('required', tcknRequired);
            } else { 
                tcknField.hide();
                tcknInput.prop('required', false);
                corporateFields.show().find('input').prop('required', true);
                if (corporateNamesRequired) {
                    nameFields.show().find('input').prop('required', true);
                } else {
                    nameFields.hide().find('input').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);
                },
                success: function(response) {
                    if (response.success && response.data) {
                        const placeholderText = isNeighborhood ? 'Mahalle seçiniz' : 'İlçe 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() {
                },
                complete: function() {
                    field.prop('disabled', false).trigger('change');
                    field.select2({ width: '100%' });
                }
            });
        },
        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.Checkout.init();
});