(function($) {
    'use strict';
    window.WTC = window.WTC || {};
    WTC.Contracts = {
        init: function() {
            this.modal = $('#wtc-contract-popup');
            this.modalContent = $('#wtc-contract-content');
            this.close = $('.wtc-close');
            this.bindEvents();
            this.setupContractUpdates();
            this.initializeFormListeners();
            this.updateContractPlaceholders();
        },
        bindEvents: function() {
            var self = this;
            $(document).on('click', '.wtc-contract-link', function(e) {
                e.preventDefault();
                self.handleContractClick($(this));
            });
            this.close.on('click', this.closeModal.bind(this));
            $(window).on('click', function(e) {
                if ($(e.target).is(self.modal)) {
                    self.closeModal();
                }
            });
            $(document).on('keydown', function(e) {
                if (e.keyCode === 27) {
                    self.closeModal();
                }
            });
        },
        setupContractUpdates: function() {
            var self = this;
            var updateTimeout;
            function updateContracts() {
                var formData = {
                    action: 'wtc_update_contracts',
                    nonce: wtc_contracts_params.nonce
                };
                $('form.checkout').find('input, select, textarea').each(function() {
                    formData[$(this).attr('name')] = $(this).val();
                });
                $.ajax({
                    type: 'POST',
                    url: wtc_contracts_params.ajax_url,
                    data: formData,
                    success: function(response) {
                        if (response.success) {
                            $('#mss_text_content').html(response.data.mss);
                            $('#obf_text_content').html(response.data.obf);
                            $('#custom_text_content').html(response.data.custom);
                            if (self.modal.is(':visible')) {
                                const activeContent = $('.wtc-contract-content:visible', self.modal);
                                if (activeContent.length) {
                                    const contractType = activeContent.attr('id').replace('_popup_content', '');
                                    const content = $(`#${contractType}_text_content`).html();
                                    activeContent.html(content);
                                }
                            }
                        }
                    }
                });
            }
            $('form.checkout').on('input change', 'input, select, textarea', function() {
                clearTimeout(updateTimeout);
                updateTimeout = setTimeout(updateContracts, 500);
            });
            $(document.body).on('updated_cart_totals updated_checkout payment_method_selected', function() {
                updateContracts();
            });
            $(document.body).on('payment_method_selected change_payment_method', function() {
                updateContracts();
            });
            updateContracts();
        },
        handleContractClick: function($link) {
            const self = this;
            const contractType = $link.data('contract');
            const $container = $link.closest('.wtc-contract-container');
            if ($container.data('mode') === 'text') {
                return;
            }
            $('.wtc-contract-link').removeClass('active');
            $link.addClass('active');
            const title = $link.text().trim();
            const content = $(`#${contractType}_text_content`).html();
            $(`#${contractType}_popup_content`).html(content);
            $('.wtc-modal .wtc-contract-content').hide();
            $(`#${contractType}_popup_content`).show();
            $('.wtc-modal-title').text(title);
            this.showModal(contractType, title);
        },
        showModal: function(contractType, title) {
            const self = this;
            this.modal.attr('aria-hidden', 'false');
            $('body').addClass('modal-open');
            $(`#${contractType}_popup_content`).show().siblings('.wtc-contract-content').hide();
            this.modal.find('.wtc-modal-title').text(title);
            const $modalElements = this.modal.find('.wtc-modal-accept, .wtc-modal-close, .wtc-close, .wtc-modal-overlay');
            $modalElements.off('click');
            setTimeout(() => {
                this.modal.find('.wtc-modal-wrapper').attr('tabindex', '-1').focus();
            }, 100);
            this.modal.find('.wtc-modal-accept').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const checkboxId = `${contractType}_acceptance`;
                $('#' + checkboxId).prop('checked', true).trigger('change');
                self.closeModal();
            });
            this.modal.find('.wtc-modal-close, .wtc-close').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                self.closeModal();
            });
            this.modal.find('.wtc-modal-overlay').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                self.closeModal();
            });
        },
        closeModal: function() {
            this.modal.attr('aria-hidden', 'true');
            this.modal.find('.wtc-modal-accept, .wtc-modal-close, .wtc-close, .wtc-modal-overlay').off('click');
            $('body').removeClass('modal-open');
            $('.wtc-contract-link.active').removeClass('active');
            $('.wtc-contract-link').first().focus();
        },
        initializeFormListeners: function() {
            const self = this;
            $(document).on('change', '#billing_invoice_type', function() {
                self.updateContractPlaceholders();
            });
            $(document).on('input change', `
                #billing_first_name, 
                #billing_last_name,
                #billing_company,
                #billing_tckn,
                #billing_tax_number,
                #billing_tax_office,
                #billing_address_1,
                #billing_address_2,
                #billing_postcode,
                #billing_city,
                #billing_state,
                #billing_country,
                #billing_phone,
                #billing_email,
                #shipping_first_name,
                #shipping_last_name,
                #shipping_company,
                #shipping_address_1,
                #shipping_address_2,
                #shipping_postcode,
                #shipping_city,
                #shipping_state,
                #shipping_country
            `, function() {
                self.updateContractPlaceholders();
            });
            $(document).on('change', '#ship-to-different-address-checkbox', function() {
                self.updateContractPlaceholders();
            });
            $(document).ajaxComplete(function(event, xhr, settings) {
                if (settings.url && settings.url.indexOf('update_order_review') > -1) {
                    self.updateContractPlaceholders();
                }
            });
            $(document).on('change', 'input[name="payment_method"]', function() {
                self.updateContractPlaceholders();
            });
            self.updateContractPlaceholders();
        },
        updateContractPlaceholders: function() {
            const invoiceType = $('#billing_invoice_type').val();
            const firstName = $('#billing_first_name').val() || '';
            const lastName = $('#billing_last_name').val() || '';
            const fullName = `${firstName} ${lastName}`.trim();
            const company = $('#billing_company').val() || '';
            const tckn = $('#billing_tckn').val() || '';
            const taxNumber = $('#billing_tax_number').val() || '';
            const taxOffice = $('#billing_tax_office').val() || '';
            const address1 = $('#billing_address_1').val() || '';
            const address2 = $('#billing_address_2').val() || '';
            const postcode = $('#billing_postcode').val() || '';
            const city = $('#billing_city').val() || '';
            const state = $('#billing_state').is('select') ? 
                $('#billing_state option:selected').text() : 
                $('#billing_state').val() || '';
            const country = $('#billing_country option:selected').text() || '';
            const fullAddress = [address1, address2, postcode, city, state, country]
                .filter(Boolean)
                .join(', ');
            const phone = $('#billing_phone').val() || '';
            const email = $('#billing_email').val() || '';
            const corporateNamesRequired = wtc_contracts_params.corporate_names_required === 'yes';
            if (invoiceType === 'individual') {
                $('.wtc-billing-full-name').text(fullName);
                $('.wtc-billing-tckn').text(tckn);
                $('.wtc-billing-company').text('');
                $('.wtc-billing-tax-number').text('');
                $('.wtc-billing-tax-office').text('');
            } else {
                if (corporateNamesRequired) {
                    $('.wtc-billing-full-name').text(fullName);
                } else {
                    $('.wtc-billing-full-name').text('');
                }
                $('.wtc-billing-tckn').text('');
                $('.wtc-billing-company').text(company);
                $('.wtc-billing-tax-number').text(taxNumber);
                $('.wtc-billing-tax-office').text(taxOffice);
            }   
            $('.wtc-billing-full-address').text(fullAddress);
            $('.wtc-billing-phone').text(phone);
            $('.wtc-billing-email').text(email);
            const shipToDifferentAddress = $('#ship-to-different-address-checkbox').is(':checked');
            if (shipToDifferentAddress) {
                const shippingFirstName = $('#shipping_first_name').val() || '';
                const shippingLastName = $('#shipping_last_name').val() || '';
                const shippingFullName = `${shippingFirstName} ${shippingLastName}`.trim();
                const shippingCompany = $('#shipping_company').val() || '';
                const shippingAddress1 = $('#shipping_address_1').val() || '';
                const shippingAddress2 = $('#shipping_address_2').val() || '';
                const shippingPostcode = $('#shipping_postcode').val() || '';
                const shippingCity = $('#shipping_city').val() || '';
                const shippingState = $('#shipping_state').is('select') ? 
                    $('#shipping_state option:selected').text() : 
                    $('#shipping_state').val() || '';
                const shippingCountry = $('#shipping_country option:selected').text() || '';
                const shippingFullAddress = [shippingAddress1, shippingAddress2, shippingPostcode, shippingCity, shippingState, shippingCountry]
                    .filter(Boolean)
                    .join(', ');
                $('.wtc-shipping-full-name').text(shippingFullName);
                $('.wtc-shipping-company').text(shippingCompany);
                $('.wtc-shipping-full-address').text(shippingFullAddress);
            } else {
                if (invoiceType === 'individual') {
                    $('.wtc-shipping-full-name').text(fullName);
                    $('.wtc-shipping-company').text('');
                } else {
                    $('.wtc-shipping-full-name').text('');
                    $('.wtc-shipping-company').text(company);
                }
                $('.wtc-shipping-full-address').text(fullAddress);
            }
            const paymentMethod = $('input[name="payment_method"]:checked').closest('li').find('label').text().trim();
            $('.wtc-payment-method').text(paymentMethod);
        }
    };
    $(document).ready(function() {
        WTC.Contracts.init();
    });
})(jQuery); 