/**
 * Simplyin Payment - Email Component Mixin
 * Integrates Simply.IN OTP authentication into the checkout email step.
 * Only activates when the Simply.IN payment method is enabled.
 */
define([
    'jquery',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Simplyin_Payment/js/modal/simplyin-modal',
    'Simplyin_Payment/js/model/session-storage-manager',
    'Simplyin_Payment/js/model/ajax-client',
    'mage/translate'
], function ($, quote, checkoutData, simplyinModal, sessionStorageManager, ajaxClient, $t) {
    'use strict';

    var emailExistData = null;

    /**
     * Check if SimplyIN is enabled in checkout config
     * @returns {Boolean}
     */
    function isSimplyinEnabled() {
        return !!(
            window.checkoutConfig &&
            window.checkoutConfig.payment &&
            window.checkoutConfig.payment.simplyin_payment &&
            window.checkoutConfig.payment.simplyin_payment.isActive
        );
    }

    return function (Component) {
        // If SimplyIN is not enabled, return the original component untouched
        if (!isSimplyinEnabled()) {
            return Component;
        }

        return Component.extend({
            defaults: {
                template: 'Simplyin_Payment/form/element/email',
                checkDelay: 1000
            },
            simplyinAuthToken: null,
            simplyinUserData: null,

            /**
             * @inheritdoc
             */
            initConfig: function () {
                this._super();
                this.simplyinEnabled = true;
                sessionStorageManager.initialize();
                return this;
            },

            /**
             * @inheritdoc
             */
            initObservable: function () {
                this._super();

                // Restore session after observables are initialized
                this.restoreSessionIfExists();

                return this;
            },

            /**
             * Restore session data if exists (after page reload)
             */
            restoreSessionIfExists: function () {
                var self = this;
                var authToken = sessionStorageManager.getAuthToken();
                var userData = sessionStorageManager.getUserData();
                var currentEmail = sessionStorageManager.getCurrentEmail();

                if (authToken && userData && currentEmail) {
                    if (self.email() === currentEmail || !self.email()) {
                        self.simplyinAuthToken = authToken;
                        self.simplyinUserData = userData;

                        setTimeout(function () {
                            self.showDataCompletedBadge();
                        }, 500);

                        $(document).trigger('simplyin:auth_successful', [authToken, userData]);
                        self.validateSessionInBackground(authToken);
                    }
                }
            },

            /**
             * Validate session with the API in background
             */
            validateSessionInBackground: function (authToken) {
                ajaxClient.postSilent('simplyin/api/getUserData', { authToken: authToken })
                    .done(function (response) {
                        if (response.success) {
                            sessionStorageManager.refreshSession();
                        }
                    });
                // Network errors are silently ignored — don't clear session
            },

            /**
             * @inheritdoc - Override emailHasChanged to add SimplyIN logic
             */
            emailHasChanged: function () {
                var self = this;

                clearTimeout(this.emailCheckTimeout);

                if (self.validateEmail()) {
                    quote.guestEmail = self.email();
                    checkoutData.setValidatedEmailValue(self.email());

                    if (sessionStorageManager.hasEmailChanged(self.email())) {
                        sessionStorageManager.clearAll();
                        self.removeDataCompletedBadge();
                        $(document).trigger('simplyin:email_changed', [self.email()]);
                    }

                    sessionStorageManager.setCurrentEmail(self.email());
                }

                this.emailCheckTimeout = setTimeout(function () {
                    if (self.validateEmail()) {
                        self.checkEmailAvailability();
                    } else {
                        self.isPasswordVisible(false);
                    }
                }, self.checkDelay);

                checkoutData.setInputFieldEmailValue(self.email());
            },

            /**
             * @inheritdoc - Override checkEmailAvailability to add SimplyIN check
             */
            checkEmailAvailability: function () {
                var self = this;

                this.validateRequest();
                this.isEmailCheckComplete = $.Deferred();

                $(this.emailInputId).removeClass('mage-error').parent().find('.mage-error').remove();
                this.removeDataCompletedBadge();
                this.isLoading(true);

                this.checkRequest = this._super();

                $.when(this.isEmailCheckComplete).done(function () {
                    self.checkSimplyinEmail();
                }).fail(function () {
                    self.isPasswordVisible(true);
                    checkoutData.setCheckedEmailValue(self.email());
                    self.isLoading(false);
                });
            },

            /**
             * Check if email exists in Simply.IN
             */
            checkSimplyinEmail: function () {
                var self = this;

                // Check if already authenticated for this email
                var existingAuthToken = sessionStorageManager.getAuthToken();
                var existingUserData = sessionStorageManager.getUserData();
                var currentEmail = sessionStorageManager.getCurrentEmail();

                if (existingAuthToken && existingUserData && currentEmail === self.email()) {
                    self.isLoading(false);
                    self.showDataCompletedBadge();
                    $(document).trigger('simplyin:auth_successful', [existingAuthToken, existingUserData]);
                    return;
                }

                // Reset recognition before re-checking so a previous email's state never persists.
                sessionStorageManager.setUserRecognized(false);

                ajaxClient.post('simplyin/api/checkEmail', { email: self.email() })
                    .done(function (response) {
                        self.isLoading(false);

                        if (response.success) {
                            if (response.userExists) {
                                // Mark user as recognized by SimplyIN (even before OTP verification)
                                sessionStorageManager.setUserRecognized(true);
                                response.authStrategy = response.authStrategy || 'sms';
                                self.showOtpModal(response);
                                self.showDataCompletedBadge();
                                emailExistData = response;
                            } else {
                                self.showNewAccountOption();
                            }
                        } else {
                            self.isPasswordVisible(false);
                            checkoutData.setCheckedEmailValue('');
                        }
                    })
                    .fail(function () {
                        self.isLoading(false);
                        self.isPasswordVisible(false);
                        checkoutData.setCheckedEmailValue('');
                    });
            },

            /**
             * Show data completed badge after email field
             */
            showDataCompletedBadge: function () {
                var self = this;
                var emailField = $(this.emailInputId).parent();

                emailField.find('.simplyin-badge-container').remove();

                var logoUrl = require.toUrl('Simplyin_Payment/images/simplyin-logo.svg');

                var badgeHtml =
                    '<div class="simplyin-badge-container">' +
                    '<div class="simplyin-badge-content">' +
                    '<div class="simplyin-show-popup-icon">' +
                    '<img src="' + logoUrl + '" alt="Simply.IN" class="simplyin-badge-logo" width="30" height="30"/>' +
                    '<svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">' +
                    '<rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>' +
                    '<path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>' +
                    '</svg></div>' +
                    '<div class="simplyin-badge-info">' +
                    '<span class="simplyin-badge-title">' + $t('Data completed') + '</span>' +
                    '<a href="javascript:void(0)" class="simplyin-badge-action" id="simplyin-change-action">' +
                    $t('Change') +
                    ' <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path></svg>' +
                    '</a></div>' +
                    '<div class="simplyin-badge-status" style="display: none;"><span class="simplyin-check-icon">&#10003;</span></div>' +
                    '</div></div>';

                emailField.append(badgeHtml);

                $('#simplyin-change-action').on('click', function (e) {
                    e.preventDefault();
                    self.reopenAddressModal();
                });
            },

            /**
             * Remove data completed badge
             */
            removeDataCompletedBadge: function () {
                $(this.emailInputId).parent().find('.simplyin-badge-container').remove();
            },

            /**
             * Reopen address selection modal
             */
            reopenAddressModal: function () {
                var self = this;
                var token = sessionStorageManager.getAuthToken();
                var userData = sessionStorageManager.getUserData();

                if (token) {
                    simplyinModal.showAccountDetailsModal({
                        email: self.email(),
                        authToken: token,
                        userData: userData,
                        onAddressSelected: function (authToken, userData, address) {
                            if (address) {
                                self.prefillShippingAddress(address);
                            }
                        }
                    });
                } else if (emailExistData) {
                    self.showOtpModal(emailExistData);
                }
            },

            /**
             * Show new account option for users not in Simply.IN
             */
            showNewAccountOption: function () {
                sessionStorageManager.setNewUser(true);
                sessionStorageManager.setNewUserEmail(this.email());
                $(document).trigger('simplyin:showNewAccountOption', [this.email()]);
            },

            /**
             * Show OTP verification modal
             */
            showOtpModal: function (response) {
                var self = this;

                simplyinModal.showOtpModal({
                    email: self.email(),
                    data: response.data,
                    authStrategy: response.authStrategy || 'sms',
                    userUsedPushNotifications: response.userUsedPushNotifications || false,
                    notificationTokenId: response.notificationTokenId || null,
                    onVerified: function (authToken, userData) {
                        self.simplyinAuthToken = authToken;
                        self.simplyinUserData = userData;

                        sessionStorageManager.setAuthToken(authToken);
                        sessionStorageManager.setUserData(userData);

                        self.showDataCompletedBadge();
                        $(document).trigger('simplyin:auth_successful', [authToken, userData]);

                        if (userData.phoneNumber) {
                            self.updatePhoneNumber(userData.phoneNumber);
                        }

                        if (userData.shippingAddresses && userData.shippingAddresses.length > 0) {
                            self.prefillShippingAddress(userData.shippingAddresses[0]);
                        }

                        self.isPasswordVisible(false);
                        checkoutData.setCheckedEmailValue('');
                    }
                });
            },

            /**
             * Pre-fill shipping address from Simply.IN user data
             */
            prefillShippingAddress: function (address) {
                $(document).trigger('simplyin:prefillAddress', [address]);

                if (address && address.phone) {
                    setTimeout(function () {
                        var shippingAddress = quote.shippingAddress();

                        if (shippingAddress) {
                            shippingAddress.telephone = address.phone;
                            quote.shippingAddress(shippingAddress);

                            var phoneInput = $('input[name="telephone"]').filter(':visible').first();

                            if (phoneInput.length) {
                                phoneInput.val(address.phone).trigger('change');
                            }
                        }
                    }, 500);
                }
            },

            /**
             * Update phone number field
             */
            updatePhoneNumber: function (phoneNumber) {
                if (!phoneNumber) {
                    return;
                }

                var attempts = 0;
                var maxAttempts = 10;

                var tryUpdate = function () {
                    attempts++;
                    var shippingAddress = quote.shippingAddress();

                    if (shippingAddress) {
                        shippingAddress.telephone = phoneNumber;
                        quote.shippingAddress(shippingAddress);
                    }

                    var phoneInput = $('input[name="telephone"]').filter(':visible').first();

                    if (phoneInput.length) {
                        phoneInput.val(phoneNumber).trigger('change').trigger('blur');
                    } else if (attempts < maxAttempts) {
                        setTimeout(tryUpdate, 400);
                    }
                };

                setTimeout(tryUpdate, 1000);
            }
        });
    };
});
