/**
 * Simplyin Payment - Custom Email Component
 * Integrates with Simply.IN API for email verification
 */
define([
    'jquery',
    'uiComponent',
    'Magento_Customer/js/model/customer',
    'Simplyin_Payment/js/action/check-email-availability',
    'Magento_Customer/js/action/login',
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/checkout-data',
    'Magento_Checkout/js/model/full-screen-loader',
    'Simplyin_Payment/js/modal/simplyin-modal',
    'Simplyin_Payment/js/model/session-storage-manager',
    'Simplyin_Payment/js/model/ajax-client',
    'mage/translate',
    'mage/validation',
], function ($, Component, customer, checkEmailAvailability, loginAction, quote, checkoutData, fullScreenLoader, simplyinModal, sessionStorageManager, ajaxClient, $t) {
    'use strict';

    var validatedEmail;
    var emailExistData = null;

    if (!checkoutData.getValidatedEmailValue() &&
        window.checkoutConfig.validatedEmailValue
    ) {
        checkoutData.setInputFieldEmailValue(window.checkoutConfig.validatedEmailValue);
        checkoutData.setValidatedEmailValue(window.checkoutConfig.validatedEmailValue);
    }

    validatedEmail = checkoutData.getValidatedEmailValue();

    if (validatedEmail && !customer.isLoggedIn()) {
        quote.guestEmail = validatedEmail;
    }

    return Component.extend({
        defaults: {
            template: 'Simplyin_Payment/form/element/email',
            email: checkoutData.getInputFieldEmailValue(),
            emailFocused: false,
            isLoading: false,
            isPasswordVisible: false,
            listens: {
                email: 'emailHasChanged',
                emailFocused: 'validateEmail'
            },
            ignoreTmpls: {
                email: true
            }
        },
        checkDelay: 1000,
        checkRequest: null,
        isEmailCheckComplete: null,
        isCustomerLoggedIn: customer.isLoggedIn,
        forgotPasswordUrl: window.checkoutConfig.forgotPasswordUrl,
        emailCheckTimeout: 0,
        emailInputId: '#customer-email',
        simplyinAuthToken: null,
        simplyinUserData: null,

        /**
         * Initializes regular properties of instance.
         */
        initConfig: function () {
            this._super();
            this.isPasswordVisible = this.resolveInitialPasswordVisibility();
            
            // Check if Simply.IN module is enabled
            this.simplyinEnabled = window.checkoutConfig && 
                                   window.checkoutConfig.payment && 
                                   window.checkoutConfig.payment.simplyin_payment &&
                                   window.checkoutConfig.payment.simplyin_payment.isActive;
            
            // Initialize session storage manager only if module is enabled
            if (this.simplyinEnabled) {
                sessionStorageManager.initialize();
            }
            
            return this;
        },

        /**
         * Initializes observable properties of instance
         */
        initObservable: function () {
            this._super()
                .observe(['email', 'emailFocused', 'isLoading', 'isPasswordVisible', 'simplyinEnabled']);
            
            // Set initial value for simplyinEnabled
            this.simplyinEnabled(window.checkoutConfig && 
                                 window.checkoutConfig.payment && 
                                 window.checkoutConfig.payment.simplyin_payment &&
                                 window.checkoutConfig.payment.simplyin_payment.isActive);
            
            // Restore session after observables are initialized
            if (this.simplyinEnabled()) {
                this.restoreSessionIfExists();
            }
            
            return this;
        },

        /**
         * Restore session data if exists (after page reload)
         * Trusts localStorage data first, validates with API in background
         * Does NOT clear session on API errors to prevent losing valid sessions
         */
        restoreSessionIfExists: function () {
            var self = this;
            var authToken = sessionStorageManager.getAuthToken();
            var userData = sessionStorageManager.getUserData();
            var currentEmail = sessionStorageManager.getCurrentEmail();
            
            // If we have auth token and user data, restore session immediately
            // This prevents losing session due to network issues
            if (authToken && userData && currentEmail) {
                
                // Set the email if it matches or if no email entered yet
                if (self.email() === currentEmail || !self.email()) {
                    // Immediately restore session (trust localStorage)
                    self.simplyinAuthToken = authToken;
                    self.simplyinUserData = userData;
                    
                    // Show the badge immediately
                    setTimeout(function () {
                        self.showDataCompletedBadge();
                    }, 500);
                    
                    // Trigger auth success event for payment component
                    $(document).trigger('simplyin:auth_successful', [authToken, userData]);
                    
                    // Validate session in background (optional - don't clear on failure)
                    self.validateSessionInBackground(authToken);
                }
            }
        },

        /**
         * Validate session with the API in background
         * Does NOT clear session on failure - only logs for debugging
         * Session will naturally expire based on localStorage timestamp
         */
        validateSessionInBackground: function (authToken) {
            var self = this;
            
            ajaxClient.postSilent('simplyin/api/getUserData', {
                authToken: authToken
            }).done(function (response) {
                if (response.success) {
                    // Refresh session timestamp since API confirmed it's valid
                    sessionStorageManager.refreshSession();
                }
                // API says session is invalid - but don't clear immediately
                // The user might have network issues or API might be temporarily down
                // Let the localStorage expiration handle cleanup
            }).fail(function () {
                // Network error - don't clear session
                // User might be offline or API might be temporarily unavailable
            });
        },

        /**
         * Callback on changing email property
         */
        emailHasChanged: function () {
            var self = this;

            clearTimeout(this.emailCheckTimeout);

            if (self.validateEmail()) {
                quote.guestEmail = self.email();
                checkoutData.setValidatedEmailValue(self.email());
                
                // Check if email has changed and clear storage if needed
                if (sessionStorageManager.hasEmailChanged(self.email())) {
                    sessionStorageManager.clearAll();
                    
                    // Remove the "Data completed" badge when email changes
                    self.removeDataCompletedBadge();
                    
                    // Trigger event to notify payment component
                    $(document).trigger('simplyin:email_changed', [self.email()]);
                }
                
                // Set current email
                sessionStorageManager.setCurrentEmail(self.email());
            }

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

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

        /**
         * Check email availability with Simply.IN integration
         */
        checkEmailAvailability: function () {
            var self = this;

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

            // Clean up errors on email
            $(this.emailInputId).removeClass('mage-error').parent().find('.mage-error').remove();
            
            // Remove badge when checking new email
            this.removeDataCompletedBadge();
            
            this.isLoading(true);

            // Call custom check-email-availability that integrates with Simply.IN
            this.checkRequest = checkEmailAvailability(this.isEmailCheckComplete, this.email());

            $.when(this.isEmailCheckComplete).done(function () {
                // Email available in Magento
                // Only check Simply.IN if module is enabled
                if (self.simplyinEnabled()) {
                    self.checkSimplyinEmail();
                } else {
                    // Module disabled - use standard Magento flow
                    self.isPasswordVisible(false);
                    checkoutData.setCheckedEmailValue('');
                    self.isLoading(false);
                }
            }.bind(this)).fail(function (response) {
                // Email exists in Magento - show password field
                self.isPasswordVisible(true);
                checkoutData.setCheckedEmailValue(self.email());
                self.isLoading(false);
            }.bind(this));
        },

        /**
         * Check if email exists in Simply.IN and handle accordingly
         */
        checkSimplyinEmail: function () {
            var self = this;
            
            // Check if user is 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);
                
                // Show badge and trigger auth event
                self.showDataCompletedBadge();
                $(document).trigger('simplyin:auth_successful', [existingAuthToken, existingUserData]);
                
                return;
            }

            // Reset recognition before re-checking so a previous email's state never persists
            // (a different or non-existing email must not keep SimplyIN methods available).
            sessionStorageManager.setUserRecognized(false);

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

                if (response.success) {
                    if (response.userExists) {
                        // User exists in Simply.IN - show OTP modal
                        // Mark user as recognized (even before OTP verification)
                        sessionStorageManager.setUserRecognized(true);
                        // Default to SMS if not specified in response
                        response.authStrategy = response.authStrategy || 'sms';
                        self.showOtpModal(response);
                        self.showDataCompletedBadge();
                        emailExistData = response;
                    } else {
                        // User doesn't exist - show new account checkbox at payment step
                        self.showNewAccountOption();
                    }
                } else {
                    console.error('Simply.IN check failed:', response.message);
                    // Continue with normal Magento flow
                    self.isPasswordVisible(false);
                    checkoutData.setCheckedEmailValue('');
                }
            }).fail(function () {
                self.isLoading(false);
                console.error('Simply.IN API error');
                // Continue with normal Magento flow
                self.isPasswordVisible(false);
                checkoutData.setCheckedEmailValue('');
            });
        },

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

            // Remove existing badge if any
            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">✓</span>
                        </div>
                    </div>
                </div>
            `;

            emailField.append(badgeHtml);

            // Bind click event to reopen modal
            $('#simplyin-change-action').on('click', function (e) {
                e.preventDefault();
                self.reopenAddressModal();
            });
        },

        /**
         * Remove data completed badge
         */
        removeDataCompletedBadge: function () {
            var emailField = $(this.emailInputId).parent();
            emailField.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 !== null && emailExistData){
                    self.showOtpModal(emailExistData);
                }
            }
        },

        /**
         * Show new account option for users not in Simply.IN
         */
        showNewAccountOption: function () {
            // Store flag that user doesn't exist in Simply.IN
            sessionStorageManager.setNewUser(true);
            sessionStorageManager.setNewUserEmail(this.email());

            // Trigger event to show checkbox at payment step
            $(document).trigger('simplyin:showNewAccountOption', [this.email()]);
        },

        /**
         * Show OTP verification modal for existing Simply.IN users
         */
        showOtpModal: function (response) {
            var self = this;

            simplyinModal.showOtpModal({
                email: self.email(),
                data: response.data,
                authStrategy: response.authStrategy || 'sms', // Pass authStrategy
                userUsedPushNotifications: response.userUsedPushNotifications || false, // Pass push notification flag
                notificationTokenId: response.notificationTokenId || null, // Pass notification token for polling
                onVerified: function (authToken, userData) {
                    self.simplyinAuthToken = authToken;
                    self.simplyinUserData = userData;

                    // Store in session storage with expiration
                    sessionStorageManager.setAuthToken(authToken);
                    sessionStorageManager.setUserData(userData);

                    // Show Data Completed badge
                    self.showDataCompletedBadge();

                    // Trigger global auth success event for payment component
                    $(document).trigger('simplyin:auth_successful', [authToken, userData]);

                    // Update phone number from userData if available
                    if (userData.phoneNumber) {
                        self.updatePhoneNumber(userData.phoneNumber);
                    }

                    // Pre-fill shipping address if available
                    if (userData.shippingAddresses && userData.shippingAddresses.length > 0) {
                        self.prefillShippingAddress(userData.shippingAddresses[0]);
                    }

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

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

            // Also update phone number if available
            if (address && address.phone) {
                var self = this;

                // Wait a bit for the shipping form to be rendered
                setTimeout(function () {
                    // Try to update the shipping address phone field
                    var shippingAddress = quote.shippingAddress();

                    if (shippingAddress) {
                        // Update the phone number in the quote
                        shippingAddress.telephone = address.phone;
                        quote.shippingAddress(shippingAddress);

                        // Also update the DOM input field directly
                        var phoneInput = $('input[name="telephone"]').filter(':visible').first();
                        if (phoneInput.length) {
                            phoneInput.val(address.phone).trigger('change');
                        }
                    }
                }, 500);
            }
        },

        /**
         * Update phone number field with Simply.IN user's phone
         */
        updatePhoneNumber: function (phoneNumber) {
            if (!phoneNumber) {
                return;
            }

            var attempts = 0;
            var maxAttempts = 10;

            var tryUpdate = function () {
                attempts++;

                // Try to update the shipping address phone field
                var shippingAddress = quote.shippingAddress();

                if (shippingAddress) {
                    // Update the phone number in the quote
                    shippingAddress.telephone = phoneNumber;
                    quote.shippingAddress(shippingAddress);
                }

                // Also update the DOM input field directly
                var phoneInput = $('input[name="telephone"]').filter(':visible').first();
                if (phoneInput.length) {
                    phoneInput.val(phoneNumber).trigger('change').trigger('blur');
                    phoneInput.val(phoneNumber);
                    return true; // Success
                } else {
                    console.warn('SimplyIn: Phone number field not found in DOM (attempt ' + attempts + '/' + maxAttempts + ')');

                    if (attempts < maxAttempts) {
                        // Retry after 300ms
                        setTimeout(tryUpdate, 400);
                    } else {
                        console.error('SimplyIn: Failed to find phone field after ' + maxAttempts + ' attempts');
                    }
                    return false;
                }
            };

            // Start trying after initial delay
            setTimeout(tryUpdate, 1000);
        },

        /**
         * If request has been sent -> abort it.
         */
        validateRequest: function () {
            if (this.checkRequest != null && $.inArray(this.checkRequest.readyState, [1, 2, 3])) {
                this.checkRequest.abort();
                this.checkRequest = null;
            }
        },

        /**
         * Local email validation.
         */
        validateEmail: function (focused) {
            var loginFormSelector = 'form[data-role=email-with-possible-login]',
                usernameSelector = loginFormSelector + ' input[name=username]',
                loginForm = $(loginFormSelector),
                validator,
                valid;

            loginForm.validation();

            if (focused === false && !!this.email()) {
                valid = !!$(usernameSelector).valid();

                if (valid) {
                    $(usernameSelector).removeAttr('aria-invalid aria-describedby');
                }

                return valid;
            }

            if (loginForm.is(':visible')) {
                validator = loginForm.validate();
                return validator.check(usernameSelector);
            }

            return true;
        },

        /**
         * Log in form submitting callback.
         */
        login: function (loginForm) {
            var loginData = {},
                formDataArray = $(loginForm).serializeArray();

            formDataArray.forEach(function (entry) {
                loginData[entry.name] = entry.value;
            });

            if (this.isPasswordVisible() && $(loginForm).validation() && $(loginForm).validation('isValid')) {
                fullScreenLoader.startLoader();
                loginAction(loginData).always(function () {
                    fullScreenLoader.stopLoader();
                    $('.loading-mask').hide();
                });
            }
        },

        /**
         * Resolves an initial state of a login form.
         */
        resolveInitialPasswordVisibility: function () {
            if (checkoutData.getInputFieldEmailValue() !== '' && checkoutData.getCheckedEmailValue() !== '') {
                return true;
            }

            if (checkoutData.getInputFieldEmailValue() !== '') {
                return checkoutData.getInputFieldEmailValue() === checkoutData.getCheckedEmailValue();
            }

            return false;
        }
    });
});
