define(
    [
        'jquery',
        'ko',
        'mage/translate',
        'Magento_Checkout/js/view/payment/default',
        'Oney_ThreeByFour/js/model/config',
        'Magento_Checkout/js/model/quote',
        'mage/url'
    ],
    function ($, ko, t, Component, config, quote, url) {
        'use strict';
        return Component.extend({
            defaults: {
                template: 'Oney_ThreeByFour/payments/method',
                validate_url: 'threebyfour/validate/phone',
                error: ko.observable(null),
                verifiedBilling: ko.observable(false),
                verifiedShipping: ko.observable(false),
            },
            getBillingAddressFormName: function () {
                return "billing-address-form-oney_threebyfour";
            },
            verifyAddress: function (address) {
                if (address == null) return false;

                const postalValidated = config.getPostalRegex().test(address.postcode)
                if (!postalValidated) {
                    this.error(config.getError('postal'));
                }
                const phoneValidated = config.getPhoneRegex().test(address.telephone)
                if (!phoneValidated) {
                    this.error(config.getError('phone'));
                }
                const countryValidated = config.getCountry().test(address.countryId)
                if (!countryValidated) {
                    this.error(config.getError('country'));
                }
                return postalValidated && phoneValidated && countryValidated;
            },
            verified: function () {
                return this.verifiedBilling() && this.verifiedShipping();
            },
            initialize: function () {
                var self = this;

                this._super();
                this.verifiedBilling(this.verifyAddress(quote.billingAddress()));
                this.verifiedShipping(this.verifyAddress(quote.shippingAddress()));

                quote.getTotals().subscribe(function(value) {
                    self.threebyfourOneyCheckoutWidget(value);
                });

                quote.shippingAddress.subscribe(function(address) {
                    self.verifiedShipping(self.verifyAddress(address));
                });

                quote.billingAddress.subscribe(function(address) {
                    self.verifiedBilling(self.verifyAddress(address));
                });

                return true;
            },
            afterPlaceOrder: function () {
                window.location.replace(window.checkoutConfig.payment.oney_threebyfour.redirect_url);
                sleep(5);
            },
            getTitle: function () {
                return config.getTitle(this.getCode());
            },
            getNumber: function () {
                return config.getNumber(this.getCode());
            },
            getContentId: function () {
                return this.getCode() + "_content";
            },
            getBubbleId: function () {
                return this.getCode() + "_bubble";
            },
            getMerchantGuid: function () {
                return config.getMerchantGuid();
            },
            getSimulationContainerId: function () {
                return 'threebyfourOneyCheckoutSimulationContainer_' + this.getCode();
            },
            threebyfourOneyCheckoutWidget: function(value) {
                // Show loader immediately when widget starts loading
                if (typeof window.showOneyLoader === 'function') {
                    window.showOneyLoader();
                }
                var hideLoaderSafely = function () {
                    if (typeof window.hideOneyLoader === 'function') {
                        window.hideOneyLoader();
                    }
                };
                
                $.get(
                    url.build('threebyfour/payment/simulation') + "?amount=" + value['base_grand_total'] + "&code=" + this.getCode()
                ).done(function (response) {                  
                    var countryCode = window.checkoutConfig.payment.oney_threebyfour.country;
                    var languageCode = window.checkoutConfig.payment.oney_threebyfour.language || countryCode;
                    var frWidgetOptions = window.checkoutConfig.payment.oney_threebyfour.fr_widget_options || {};
                    var rawContainerId = 'threebyfourOneyCheckoutSimulationContainer_threebyfour_' + response.business_transaction_details.business_transaction_code;
                    var containerSelector = '#' + rawContainerId;
                    var container = document.getElementById(rawContainerId);
                    var markWidgetLoaded = function () {
                        var element = document.getElementById(rawContainerId);
                        if (element) {
                            element.dataset.widgetLoaded = "true";
                        }
                        hideLoaderSafely();
                    };
                    var waitForWidgetContent = function () {
                        var element = document.getElementById(rawContainerId);
                        if (element && element.childElementCount > 0) {
                            markWidgetLoaded();
                            return true;
                        }
                        return false;
                    };
                    
                    if (container && container.dataset.widgetLoaded === "true") {
                        hideLoaderSafely();
                        return;
                    }

                    var options = {
                        country: countryCode,
                        language: languageCode,
                        merchant_guid: config.getMerchantGuid(),
                        payment_amount: response.payment_amount,
                        filter_by: "business_transaction_code",
                        business_transaction_code: response.business_transaction_details.business_transaction_code,
                        hide_logo: false,
                        checkout_placeholder: containerSelector,
                        successCallback: function (status, widgetResponse) {
                            console.log("[INFO] [JS] Oney widget loaded:", status || 'success', widgetResponse || {});
                            if (!waitForWidgetContent()) {
                                var observerTarget = document.getElementById(rawContainerId);
                                if (observerTarget) {
                                    var observer = new MutationObserver(function () {
                                        if (waitForWidgetContent()) {
                                            observer.disconnect();
                                        }
                                    });
                                    observer.observe(observerTarget, {childList: true});
                                    setTimeout(function () {
                                        observer.disconnect();
                                        markWidgetLoaded();
                                    }, 5000);
                                } else {
                                    markWidgetLoaded();
                                }
                            }
                        },
                        errorCallback: function (status, widgetResponse) {
                            console.error("[ERROR] [JS] Oney widget reported failure:", status || 'error', widgetResponse || {});
                            hideLoaderSafely();
                        }
                    };
                    if (countryCode === 'FR' && Object.keys(frWidgetOptions).length) {
                        options = Object.assign(options, frWidgetOptions);
                    }

                    try {
                        loadOneyWidget(function () {
                            oneyMerchantApp.loadCheckoutSection({ options });
                        });
                    } catch (error) {
                        console.error("[ERROR] [JS] Error when loading Oney widget: ", error);
                        hideLoaderSafely();
                    }
                    
                }).fail(function () {
                    console.error("[ERROR] [JS] Error when retrieving Oney's simulation data from widget.");
                    hideLoaderSafely();
                });
            }
        });
    }
);