(function($) {
    'use strict';

    var omInvoicing = {
        lastState: null, // Track last known state to prevent loops
        isUpdating: false, // Flag to prevent update loops

        init: function() {
            this.bindEvents();
            this.checkInitialState();
        },

        bindEvents: function() {
            var self = this;

            // Toggle invoice fields on selection change (user initiated)
            $(document).on('change', '#billing_timologio', function() {
                self.toggleInvoiceFields($(this).val() === 'YES', true);
            });

            // AADE lookup on VAT blur
            if (window.omCheckoutInvoice && window.omCheckoutInvoice.aadeEnabled) {
                $(document).on('blur', '#billing_vat', function() {
                    self.aadeLookup($(this).val());
                });

                // Also on paste
                $(document).on('paste', '#billing_vat', function() {
                    var $input = $(this);
                    setTimeout(function() {
                        self.aadeLookup($input.val());
                    }, 100);
                });
            }

            // Re-check on checkout update (but don't trigger another update)
            $(document.body).on('updated_checkout', function() {
                self.checkInitialState();
            });
        },

        checkInitialState: function() {
            var $select = $('#billing_timologio');
            if ($select.length) {
                // Don't trigger update_checkout - just sync the UI state
                this.toggleInvoiceFields($select.val() === 'YES', false);
            }
        },

        toggleInvoiceFields: function(show, triggerUpdate) {
            // Prevent redundant updates if state hasn't changed
            if (this.lastState === show) {
                return;
            }
            this.lastState = show;

            var $form = $('form.checkout, form.woocommerce-checkout');

            if (show) {
                $form.addClass('timologio-show');
                $('.timologio-hide').slideDown('fast');
                this.setRequired(true);
            } else {
                $form.removeClass('timologio-show');
                $('.timologio-hide').slideUp('fast');
                this.setRequired(false);
            }

            // Only trigger checkout update when explicitly requested (user changed selection)
            // This prevents the infinite loop: change -> update_checkout -> updated_checkout -> checkInitialState -> toggleInvoiceFields -> update_checkout
            if (triggerUpdate) {
                $(document.body).trigger('update_checkout');
            }
        },

        setRequired: function(required) {
            var fields = ['#billing_vat', '#billing_company', '#billing_irs'];
            var requiredHtml = '<abbr class="required" title="required">*</abbr>';

            fields.forEach(function(field) {
                var $field = $(field);
                var $label = $(field + '_field label');

                if (required) {
                    // Remove optional
                    $label.find('.optional').remove();
                    // Add required if not present
                    if (!$label.find('.required').length) {
                        $label.append(requiredHtml);
                    }
                    $field.prop('required', true);
                } else {
                    // Remove required
                    $label.find('.required').remove();
                    $field.prop('required', false);
                }
            });
        },

        aadeLookup: function(vat) {
            var self = this;

            // Validate VAT format (9 digits for Greece)
            vat = vat.replace(/\D/g, '');
            if (vat.length !== 9) {
                return;
            }

            var $field = $('#billing_vat_field');
            $field.removeClass('om-ai-aade-success om-ai-aade-error').addClass('om-ai-aade-loading');

            $.ajax({
                url: window.omCheckoutInvoice.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'om_checkout_aade_lookup',
                    nonce: window.omCheckoutInvoice.nonce,
                    vat: vat
                },
                success: function(response) {
                    $field.removeClass('om-ai-aade-loading');

                    if (response.success && response.data) {
                        $field.addClass('om-ai-aade-success');
                        self.populateFromAade(response.data);
                    } else {
                        $field.addClass('om-ai-aade-error');
                    }
                },
                error: function() {
                    $field.removeClass('om-ai-aade-loading').addClass('om-ai-aade-error');
                }
            });
        },

        populateFromAade: function(data) {
            // Company name
            var company = '';
            if (data.commer_title) company = data.commer_title;
            if (data.onomasia) company += (company ? ' ' : '') + data.onomasia;
            if (company) $('#billing_company').val(company);

            // DOY/IRS
            if (data.doy_descr) {
                $('#billing_irs').val(data.doy_descr);
            }

            // Address
            var address = '';
            if (data.postal_address) address = data.postal_address;
            if (data.postal_address_no) address += ' ' + data.postal_address_no;
            if (address) $('#billing_address_1').val(address);

            // City
            if (data.postal_area_description) {
                $('#billing_city').val(data.postal_area_description);
            }

            // Postcode
            if (data.postal_zip_code) {
                $('#billing_postcode').val(data.postal_zip_code);
            }

            // Activity/Profession
            if (data.activities && data.activities.length > 0) {
                $('#billing_store').val(data.activities[0]);
            }

            // Trigger checkout update
            $(document.body).trigger('update_checkout');
        }
    };

    $(document).ready(function() {
        omInvoicing.init();
    });

})(jQuery);
