// Angular Core
import { Component, OnInit, OnDestroy, AfterViewInit, Renderer2, Inject, ComponentFactoryResolver, Injector } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

// RxJs
import { Subscription, throwError } from 'rxjs';
import { catchError, filter } from "rxjs/operators";

// Components
import { AccountSuspendedComponent } from './account-suspended/account-suspended.component';
import { TaxExemptMessageComponent } from './tax-exempt-message/tax-exempt-message.component';
import { CheckoutmessageComponent } from './checkoutmessage/checkoutmessage.component';
import { HundredSearchNotifyComponent } from './hundred-search-notify/hundred-search-notify.component';
import { PharmacyPopUpMessageComponent } from './pharmacy-pop-up-message/pharmacy-pop-up-message.component';
import { TwoHundredSearchNotifyComponent } from './two-hundred-search-notify/two-hundred-search-notify.component';
import { VawdMessagePopUpComponent } from './vawd-message-pop-up/vawd-message-pop-up.component';
import { StripePaymentModelComponent } from 'src/app/components/stripe-payment-model/stripe-payment-model.component';
import { OnboardingTourStepsModalComponent } from 'src/app/feature-modules/user/onboarding-tour/components/onboarding-tour-steps-modal/onboarding-tour-steps-modal.component';

// Services
import { AccountInfoService } from 'src/app/services/accountInfo/account-info.service';
import { ContentService } from 'src/app/services/content/content.service';
import { QuickcartService } from 'src/app/services/quickcart/quickcart.service';
import { SessionService } from 'src/app/services/session/session.service';
import { ApiService } from 'src/app/services/api/api.service';
import { ManageSupplierService } from 'src/app/services/manageSupplier/manage-supplier.service';
import { SearchService } from 'src/app/services/search/search.service';
import { CartService } from 'src/app/services/cart/cart.service';
import { LocalStorageService } from 'src/app/services/localstorage/local-storage.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

// Interfaces
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { QuickCartCountDataInterface } from 'src/app/interfaces/user/quick-cart-count-data-interface';
import { CategoriesDataInterface } from 'src/app/interfaces/user/categories-data-interface';
import { BuyingGroupListInterface } from 'src/app/interfaces/user/buying-group-list-interface';
import { SuppliersList } from 'src/app/interfaces/supplier/suppliers-list';
import { GetPreferences } from 'src/app/interfaces/user/manage-suppliers-interface';

// Third Party
import { NgbModal, NgbModalConfig, NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { environment } from 'src/environments/environment';
import { OptInPopUpComponent } from './opt-in-pop-up/opt-in-pop-up.component';
import { TrxademodalService } from 'src/app/services/trxademodal/trxademodal.service';
import { ModalServiceConfig } from 'src/app/interfaces/modal-interface';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';
import { sha256 } from 'js-sha256';
import { DOCUMENT } from '@angular/common';
import { QuickSurveyQuestionPopupComponent } from './quick-survey-question-popup/quick-survey-question-popup.component';

interface Categories {
    catName: string,
    catUrl: string
}

interface PurchaseRatios {
    [key: string]: number,
    primary_total: number,
    trxade_total: number,
    pac_savings: number,
    pct_primary: number,
    brand_total: number,
    generic_total: number,
    other_total: number,
    pct_pac_savings: number,
    pct_trxade: number,
    pct_other: number,
    pct_generic: number,
    pct_brand: number
}

interface GpoColorPercentages {
    yellow: number,
    green: number,
    red: number,
}

interface MenuSwitches {
    isLoggedIn: boolean,
    isBuyer: boolean,
    isSeller: boolean,
    isFinal: boolean,
    isAdmin: boolean,
    homeLink: string,
}

@Component({
  standalone: false,
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit, OnDestroy, AfterViewInit {
    imgUrl: string = environment.imageUrl;
    debug!: SessionDataInterface['debug'];
    isProduction: boolean = environment.production;
    isAdmin!: boolean;
    session!: SessionDataInterface['data'];
    modalConfigs!: Array<ModalServiceConfig>;
    showQuickSurveyPopUp: boolean = false;
    quickCartListener!: Subscription;
    paymentMethodsSubscribe!:Subscription;
    payMethodAdded: boolean = false;
    isAwaitingValidation: boolean = false;
    isPmsUserWithAccess: boolean = false;

    constructor(
        private sessionService: SessionService,
        private contentService: ContentService,
        private quickcartService: QuickcartService,
        private accountInfoService: AccountInfoService,
        private modalService: NgbModal,
        public activeModal: NgbActiveModal,
        public apiService: ApiService,
        public manageSupplier: ManageSupplierService,
        public searchService: SearchService,
        private cartService: CartService,
        private router: Router,
        modalConfig: NgbModalConfig,
        private localStorageService: LocalStorageService,
        private trxadeModalService: TrxademodalService,
        private dataTransmitter: DataTransmitterService,
        private utilitiesService:UtilitiesService,
        private renderer: Renderer2,
        @Inject(DOCUMENT) private _document: Document,
        private componentFactory: ComponentFactoryResolver,
        private injector: Injector
    ) {
        // customize default values of modals used by this component tree
        modalConfig.backdrop = 'static';
        modalConfig.keyboard = false;
        this.detectBrowser();
    }

    ngOnInit(): void {
        /**
         * This will listen to custom event to trigger refreshing the quickcart data
         */
        this.quickCartListener = this.cartService.QuickCart.subscribe(() => {
            this.getQuickcart();
        });
        this.router.events
            .pipe(filter(event => event instanceof NavigationEnd))
            .subscribe(() => {
                this.sessionService.reCheckSession();
            });
        this.utilitiesService.updateLiveChat();
        this.getSession();
        this.checkIfActive();
        /**
         * Grant application access as a final user with PMS restrictions
         * if:
         * 1. The PMS user has not started the initial registration process, or
         * 2. The initial registration has started and license documents are uploaded.
        */
        if (this.session.is_buyer && this.session?.is_preview_mode) {
            let isPmsRegInitiated = this.session?.is_pms_registration_initiated;
            this.isPmsUserWithAccess = !isPmsRegInitiated || (isPmsRegInitiated && this.session.reg_step === 8);
        }
        /**
         * Trigger menu rendering on load
        */
        this.renderMenu();
        if (this.session.is_buyer && this.isPmsUserWithAccess && !this.session?.is_onboarding_tour_shown) {
            this.displayOnboardTourModal();
            
            this.accountInfoService.setOnboardTourStatus({ field: 'tour_status', value: 'started' })
              .subscribe({
                  next: (res: any) => {
                  },
                  error: (err) => {
                      this.accountInfoService.errorCallBack(err);
                  },
                  complete: () => { },
              });
        }
        this.getPreferences();
        if (this.session.is_buyer && (this.session.account_status === 'final' || this.isPmsUserWithAccess)) {
            //get data on load
            this.getQuickcart();
        }
        this.checkIfBuyerAndGpoMember();
        this.dataTransmitter.sitename.next(this.session.sitename);
        /**
         * Get session data when session object is updated outside of header component
         * like AuthGuard for example.
         */
        this.sessionService.getSessionOnUpdate.subscribe(() => {
            this.getSession();
        });
    }

    ngAfterViewInit() {
        let self = this;
        /**
         * ScrollTop button will display when page scroll down(at 100px)
         * @returns {undefined}
         */
        document.onscroll = function () {
            /*
             * Updated below condition as per TRX-7708.
             * ScrollTop Button not displaying in all pages on IE Browser.
             * $window.scrollY getting as undefined on IE Browser only.
             */
            var yPosition = window.scrollY
            if (yPosition > 100) {
                self.class = "show";
            } else {
                self.class = "hide";
            }
        }
    }

    class: string = 'show';

    catLength!: number;

    /* This object represents the open state of each dropdown menu. the 'is-open' attribute is set to the matching
                  * value, and the 'ng-mouseleave' attribute sets it to false to reset the menu state on mouseout. */
    menuStates = {
        purchaseProducts: false,
        salesHistory: false,
        manageAccount: false,
        supplierInfo: false,
        manageStore: false,
        faqs: false,
        messages: false,
        managePurchases: false,
        otc: false
    };

    categories!: Categories[];

    /* Hides the menu until getSession() has been run and the visible and invisible items are updated. */
    hide = {
        leftMenu: true,
        rightMenu: true
    };
    pharmacymessage = {
        displayed: false
    };

    /*
     * On IE Browser, GPO Visual Graph Should be displayed along with Obsolete Message as per TRX-7338.
     */
    obsoleteMsgDisplay: boolean = false;
    displayGPOGraph: boolean = false;
    isIEbrowser: number = 0;//TRX-7787


    pharmacyMessage = {
        html: ''
    };
    show_primary_err_msg: boolean = false;
    show_secondary_err_msg: boolean = false;
    show_pms_err_msg: boolean = false;
    isSuppDDValid: boolean = true;

    /*
     * Default purchase ratios.
     */
    purchaseRatios: PurchaseRatios = {
        primary_total: 0,
        trxade_total: 0,
        pac_savings: 0,
        pct_primary: 0,
        brand_total: 0,
        generic_total: 0,
        other_total: 0,
        pct_pac_savings: 0,
        pct_trxade: 0,
        pct_other: 0,
        pct_generic: 0,
        pct_brand: 0
    };

    taxExemptWarningCount: number = 0;
    pmsVal: any;
    suppliers!: SuppliersList['data'];
    buyingGroups!: BuyingGroupListInterface['data'];
    pms: any;
    err_msg: any = []
    isUserAllowed: boolean = false;
    outOfStockPopupOpened: boolean = false;
    showTaxExemptMsg!: boolean;
    qtrcompliance: any;
    yaxisColors!: GpoColorPercentages;
    quickcart!: QuickCartCountDataInterface['data'];
    isCartUrl: boolean = false;
    needVawdUpdateFlag!: boolean;
    isBuyer: boolean = false;
    isFinal: boolean = false;
    isLoggedIn: boolean = false;
    is_pharmacy_msg!: boolean | number;
    menuSwitches!: MenuSwitches;
    directUrlCategories!: string[];
    shoppingCartTotal = 0;
    deaLicMsgDisplay: boolean = false;
    stateLicMsgDisplay: boolean = false;      
    deaLicenseMsg: string = 'has expired';
    stateLicenseMsg: string = 'has expired';

    /**
     * Get session data. Get debug data if dev-mode === true in server/config/local.config.php
     * @returns {promise}
     */
    getSession() {
        this.session = this.sessionService.getSession();
        this.debug = this.sessionService.getDebug();
        this.taxExemptWarningCount = this.session.tax_exempt_warning_count;
        this.isAwaitingValidation = (this.session.is_preview_mode && this.session.account_status === "ready" && this.session.state_medical_license_document && this.session.dea_medical_license_document);
    };

    /*
     * Subscribe Data.
     */
    getContentSubscribe!: Subscription;
    getSuppliersSubscribe!: Subscription;
    buyingGroupListSubscribe!: Subscription;
    getPmsListSubscribe!: Subscription;
    updateNoOfRemainingTriesSubscribe!: Subscription;
    getPreferencesSubscribe!: Subscription;
    quickcartServiceGetDataSubscribe!: Subscription;
    checkIfUserAccSuspendedSubscribe!: Subscription;

    /**
     * Check all the conditions are satisfied or not
     * to show pharmacy pop up
     * @returns {boolean}
     */
    shouldShowPharmacyPopUp() {
        var showPharmacyPopUp = false;
        if (this.session.logged_in &&
            this.session.is_buyer &&
            this.session.reg_step > 7 &&
            this.session?.layout[0]?.is_pharmacy_msg &&
            this.localStorageService.getItem('pharmacyMessageShown') !== 'shown') {
            showPharmacyPopUp = true;
        }

        return showPharmacyPopUp;
    };
    
    /**
     * Checks conditions to display Anniversary popup
     * @return boolean
    */
    shouldShowAnniversaryPopUp() {
        var showAnniversaryPopUp = false;
        if (this.isBuyer &&
            this.isFinal &&
            this.isLoggedIn &&
            this.session.show_pre_anniv_popup &&
            this.localStorageService.getItem('preAnnivPopupShown') !== 'shown') {
            showAnniversaryPopUp = true;
        } else if (!this.needVawdUpdateFlag &&
            this.isBuyer &&
            this.isFinal &&
            this.isLoggedIn &&
            localStorage.getItem('vawdMessageShown') !== 'shown') {
            showAnniversaryPopUp = true;
        }
        return showAnniversaryPopUp;
    }


    updatePmsVal(val: any) {
        this.pmsVal = val;
    };

    /**
     * Validate Phone Number
     * @return {boolean}
     */
    validatePhnNum() {
        return {
            test: function (value: any) {
                return /[0-9]{10}/.test(value) || /[0-9]{3}-[0-9]{3}-[0-9]{4}/.test(value);
            }
        };
    };

    ngOnDestroy() {
        this.checkIfActive();
        this.getContentSubscribe?.unsubscribe();
        this.getSuppliersSubscribe?.unsubscribe();
        this.buyingGroupListSubscribe?.unsubscribe();
        this.updateNoOfRemainingTriesSubscribe?.unsubscribe();
        this.quickcartServiceGetDataSubscribe?.unsubscribe();
        this.checkIfUserAccSuspendedSubscribe?.unsubscribe();
        this.quickCartListener?.unsubscribe();
    }

    /**
     * Logic to render menu
     * @returns {undefined}
     */
    renderMenu() {
        // set up our menu switches
        this.isLoggedIn = this.session?.logged_in;
        var isSupplier: boolean = false;
        this.isAdmin = false;
        var homeLink: string = '/market/home';
        let active = false;
        if (this.isLoggedIn) {
            this.isBuyer = this.session?.is_buyer;
            isSupplier = this.session?.is_supplier;
            this.isFinal = this.session?.account_status === 'final' || this.isPmsUserWithAccess;
            this.isAdmin = this.session?.is_admin;
            if (this.session.licenses?.dea_expired === true 
                || this.session.licenses?.dea_expiring_soon === true) {
                this.deaLicMsgDisplay = true;
            }

            if (this.session.licenses?.state_license_expired === true 
                    || this.session.licenses?.state_expiring_soon === true) {
                this.stateLicMsgDisplay = true;
            }

            if (this.session.licenses?.dea_expiring_soon === true) {
                this.deaLicenseMsg = "is about to expire";
            }

            if (this.session.licenses?.state_expiring_soon === true) {
                this.stateLicenseMsg = "is about to expire";
            }
            /*
              * Enabling Language Translator Dropdown
              * for only Buyer(s).
              */
            if (this.isBuyer) {
               let langTransltrDD = document.getElementById('gtranslate_wrapper');
               if (langTransltrDD) {
                   langTransltrDD.style.display = 'block';
               }
            }
            /*
            * Introduced below condition as per TRX-7634.
            * If the isUserAllowed false, the logged-in user is considered to be an admin-level 8 user.
            * If the isUserAllowed true, the logged-in user is considered to be not an admin-level 8 user.
            */
            if (this.session.is_admin_restricted) {
                this.isUserAllowed = false;
            } else {
                this.isUserAllowed = true;
            }
            homeLink = (this.session?.is_supplier) ? '/market/supplier/home' : '/market/home';
            this.is_pharmacy_msg = this.session?.layout[0]?.is_pharmacy_msg;
            this.needVawdUpdateFlag = this.session?.vawd_data_updated;
            this.showTaxExemptMsg = (this.session.reg_step > 7 && this.session.is_email_confirmed === 1 && this.session.show_tax_date_expired_pop_up && this.session.tax_exempt_warning_count > 0 && this.localStorageService.getItem('taxExempt') !== '1');
            this.showQuickSurveyPopUp = this.session.active && this.isFinal && !this.isAdmin && this.isBuyer && this.session.show_quick_survey_question_pop_up && (this.localStorageService.getItem('QSQPopupShown') !== 'shown');
        }

        /**
         * Modal configuration objects that needed to be shown to user on login. Arrange
         * the config objects in the priority required to be shown.
         */
        this.modalConfigs = [
            {
                component: new VawdMessagePopUpComponent(new NgbActiveModal, this.modalService, this.accountInfoService, this.dataTransmitter),
                data: {isCartUrl: this.isCartUrl, showPreAnnivPopup: this.session.show_pre_anniv_popup},
                showModal: this.shouldShowAnniversaryPopUp()
            },
            {
                component: new PharmacyPopUpMessageComponent(new NgbActiveModal, this.modalService, this.contentService),
                data: {},
                showModal: this.shouldShowPharmacyPopUp()
            },
            {
                component: new TaxExemptMessageComponent(new NgbActiveModal(), this.modalService, this.accountInfoService),
                data: {
                    taxExemptWarningCount: this.taxExemptWarningCount
                },
                showModal: this.showTaxExemptMsg
            },
            {
                component: new OptInPopUpComponent(new NgbActiveModal(), this.modalService, this.accountInfoService, this.dataTransmitter),
                data: {
                    legal_fax: this.session?.fax,
                    xu_mrktng_fax_opt_in_pref: this.session?.mrktng_fax_opt_in_pref
                },
                showModal: this.isBuyer && this.isFinal && !this.isAdmin && !this.session.mrktng_fax_opt_popup_displayed
            },
            {
                component: this.componentFactory.resolveComponentFactory(QuickSurveyQuestionPopupComponent).create(this.injector).instance,
                data: {},
                showModal: this.showQuickSurveyPopUp
            }
        ];

        if (!this.isPmsUserWithAccess) {
            this.modalConfigs.forEach((modalConfig) => {
                this.trxadeModalService.modalPipe.next(modalConfig);
            });
        }

        this.menuSwitches = {
            isLoggedIn: this.isLoggedIn,
            isBuyer: this.isBuyer,
            isSeller: isSupplier,
            isFinal: this.isFinal,
            isAdmin: this.isAdmin,
            homeLink: homeLink
        };
        this.dataTransmitter.menuSwitches.next(this.menuSwitches);
        // Show the menus after we retrieve the session data so they don't flicker
        this.hide.leftMenu = false;
        this.hide.rightMenu = false;
    };

    getPreferences() {
        if (this.localStorageService.getItem('preferencesSet') !== 'true' && this.isLoggedIn) {
            this.getPreferencesSubscribe = this.manageSupplier.getPreferences()
                .pipe(
                    catchError(() => {
                        return throwError(() => new Error('ups sommething happend'));
                    })
                )
                .subscribe({
                    next: (res: GetPreferences) => {
                        for (const [key, value] of Object.entries(res.data)) {
                            var flag = false;
                            if (key !== 'user_id' && value === 1) {
                                flag = true;
                            }
                            if (key === 'ndc_specific_search_only') {
                                this.searchService.setNDCSpecific.emit(flag + '')
                            }
                            if (key === 'overnight_suppliers_only' && value === 1) {
                                this.manageSupplier.updatePreference({ field: key, value: value });
                            }
                            this.localStorageService.setItem(key, JSON.stringify(flag));
                        }
                        this.localStorageService.setItem('preferencesSet', 'true');
                    },
                    error: (err) => {
                        this.accountInfoService.errorCallBack(err);
                    },
                    complete: () => { },
                })
        }
    }

    onCategoryMenuChange(data: CategoriesDataInterface['data']['categories']['categoryMenu']) {
        this.categories = [
            {
                catName: 'Controls',
                catUrl: '/market/controls'
            },
            {
                catName: 'Brands',
                /*
                 * As per TRX-7825, updated the Brands landing page from '/market/brands?mp' to '/market/brands?mdl=mp'
                 */
                catUrl: '/market/brands?mdl=mp'
            },
        ];
        data.forEach((category: CategoriesDataInterface['data']['categories']['categoryMenu'][0]) => {
            let catUrl = "/market/otc?tab=" + category.catCode;
            if (this.directUrlCategories.indexOf(category.catCode) !== -1) {
                catUrl = "/market/" + category.catCode.toLowerCase();
            }
            // As per TRX-8265 for OTC default landing page is "Most Popular"
            if (category.catCode === 'OTC') {
                catUrl = catUrl + '&mdl=mp';
            }
            if (category.catCode === 'DIA') {
                this.categories.push({
                    catName: 'Diabetic Supplies',
                    catUrl: '/market/diabeticSupplies'
                });
            } else {
                this.categories.push({
                    catName: category.catName,
                    catUrl: catUrl
                });
            }
        });
        this.catLength = Object.keys(this.categories).length;

    }

    /**
     * Return url parts basing on what the wanted part is.
     * @param category Categories
     * @param urlPart string
     * @returns string | object
     */
    categoryURL(category: Categories, urlPart: string) {
        if (urlPart === 'path') {
            return category.catUrl.split('?')[0];
        }
        if (urlPart === 'params') {
        var queryObject: object = {};
            if (category.catUrl.split('?')[1]) {
                queryObject = category.catUrl.split('?')[1].split('&').reduce((result: any, pair: any) => {
                    var parts = pair.split('=');
                    result[parts[0]] = parts[1];
                    return result;
                }, {});
            }
            
            return { ...queryObject };
        }
        return '';
    }

    onDirectUrlCategoriesChange(data: string[]) {
        this.directUrlCategories = data;
    };

    checkIfBuyerAndGpoMember() {

        // check user is buyer and also Gpo member as per TRX-7189
        if (this.session.is_buyer
            && this.session.trxade_gpo_member) {
            //update the values from api if purchase ratios property exists
            if (this.session.hasOwnProperty('purchase_ratios')) {
                Object.entries(this.session.purchase_ratios).forEach(([key, value]) => {
                    this.purchaseRatios[key] = value;
                });
            }
            var needlePos = this.purchaseRatios.pct_primary;
            if (needlePos >= 100) {
                needlePos = 100.00;
            }
            let quarterlyCompliance = [
                [needlePos] // needle position
            ];

            this.qtrcompliance = quarterlyCompliance;
            this.yaxisColors = this.session.gpo_color_percentages;
        }

    }

    /**
     * Check if the user is a GPO member and show brands or GPO deals based on that
     * @returns {unresolved}
     */
    checkIfGpoMember() {
        return this.session.trxade_gpo_member;
    };

    detectBrowser() {
        const isIE = /msie\s|trident\/|edge\//i.test(navigator.userAgent);
        let obsoleteCheck: any = this.localStorageService.getItem('obsoleteCheck')
        if (isIE) {

            /*
             * On IE Browser, GPO Visual Graph Should be displayed along with Obsolete Message as per TRX-7338.
             *
             * Scenario 1: If the pharmacy is GPO Member and login through an IE browser,
             * first we will display the obsolete message up to 30 seconds time then it will be disabled until the next login,
             * and the GPO graph will be displayed throughout the session.
             *
             * Scenario 2: If the pharmacy is not a GPO Member and login through an IE browser,
             * we will display the obsolete message throughout the session.
             */
            this.obsoleteMsgDisplay = true;
            this.displayGPOGraph = false;
            this.isIEbrowser = 1;//TRX-7787

            if (obsoleteCheck === null || obsoleteCheck === undefined) {
                if (this.session.trxade_gpo_member) {
                    setTimeout(() => {
                        this.obsoleteMsgDisplay = false;
                        this.displayGPOGraph = true;
                        let set_obsoleteCheck: number = 1;
                        this.localStorageService.setItem('obsoleteCheck', String(set_obsoleteCheck));

                    }, 30000)
                }
            } else {
                this.obsoleteMsgDisplay = false;
                this.displayGPOGraph = true;
            }
        } else {
            this.displayGPOGraph = true;
        }
    };

    /**
     * Updates the quickcart data
     * @returns {promise}
     */
    getQuickcart() {
        this.quickcartServiceGetDataSubscribe = this.quickcartService.get()
        .pipe(
            catchError(() => {
                return throwError(() => new Error('ups sommething happend'));
            })
        )
        .subscribe({
            next: (res: QuickCartCountDataInterface) => {
                this.quickcart = res.data;
                this.shoppingCartTotal = res.data.count
            },
            error: (err) => {
                this.quickcartService.errorCallBack(err);
            },
            complete: () => { },
        });
    };

    /**
     * Alert message popup
     * @return {undefined}
     */
    alertMessage() {
        this.trxadeModalService.modalPipe.next({
            component: new CheckoutmessageComponent(new NgbActiveModal, this.modalService),
            data: {},
            showModal: true
        });
    };

    /**
     * Logout user when logout is clicked on UI.
     */
    logout() {
        this.sessionService.logOut().subscribe({
            complete: () => {
              this.sessionService.reCheckSession()
              this.localStorageService.removeItem("obsoleteCheck");
              this.localStorageService.removeItem("headerBannerItemCnt");
              this.localStorageService.clear();
              this.router.navigate(['/market/login']);
            }
        });
    };

    //Method to get session and display modal if account suspended
    checkSession() {
        this.sessionService.reCheckSession();
        this.sessionService.get();
        setTimeout(() => {
            this.session = this.sessionService.getSession();
            this.trxadeModalService.modalPipe.next({
                component: new AccountSuspendedComponent(new NgbActiveModal, this.modalService, this.dataTransmitter, this.sessionService),
                data: {},
                showModal: !this.session.active
            });
            this.trxadeModalService.modalPipe.next({
                component: new HundredSearchNotifyComponent(new NgbActiveModal, this.modalService),
                data: {},
                showModal: this.session.search_count === 100 && !this.session.search_count_exception
            });
            this.trxadeModalService.modalPipe.next({
                component: new TwoHundredSearchNotifyComponent(new NgbActiveModal, this.modalService),
                data: {},
                showModal: this.session.search_count === 200 && !this.session.search_count_exception
            });
        }, 1500);
    };

    checkIfActive() {
        this.checkIfUserAccSuspendedSubscribe = this.apiService.checkIfUserAccSuspended.subscribe(() => {
            this.checkSession();
        })
    }
    
    /**
     * Navigates to the registration page when Complete Registration is clicked.
     */
    completeRegistration() {
        this.accountInfoService.trackRegisterEvent({ event_type: 'registration', event_source: 'preview_banner' })
            .subscribe({
                next: (res: any) => {
                },
                error: (err) => {
                    this.accountInfoService.errorCallBack(err);
                },
                complete: () => { },
        });
        this.router.navigate(['/market/registration']);
    }

    /**
     * Remove vawd message shown when checkout is clicked
     * @returns {undefined}
     */
    clickCheckout() {
        this.localStorageService.removeItem("vawdMessageShown");
    };

    /**
     * Will make it scroll to the top of the screen
     * @returns {undefined}
     */

    scrollTop() {
        window.scroll({
            top: 0,
            left: 0,
            behavior: 'smooth'
        });
    }
    /**
     * Task : TRX-6789
     * This method will reset the unaccepted Transaction count to zero
     * @returns {undefined}
     */
    resetUnacceptedTransCount() {
        if (this.session.unaccepted_trans_count > 0) {
            this.session.unaccepted_trans_count = 0;
            this.accountInfoService.resetUnacceptedTransCount().subscribe();
        }
    };

    /**
     * Opens the Stripe payment modal for setting up a payment method.
     * Subscribes to the addPayMethodStatus event to update the payment method status.
     */
    stripePaymentModel!: NgbModalRef
    showStripePaymentModel() {
        this.paymentMethodsSubscribe = this.accountInfoService
        .getAllPaymentMethods()
        .subscribe({
            next: (res: any) => {
                if (res.data !== false) {
                  this.payMethodAdded = true;
                  this.stripePaymentModel = this.modalService.open(StripePaymentModelComponent,{size: 'sm'});
                  this.stripePaymentModel.componentInstance.stripePaymentModel = this.stripePaymentModel;
                  this.stripePaymentModel.componentInstance.stripePaymentModelNo = this.stripePaymentModelNo;
                  this.stripePaymentModel.componentInstance.paymentMethodCards = res.data.cards;
                  this.stripePaymentModel.componentInstance.paymentMethodBank = res.data.bankAccounts;
                  this.stripePaymentModel.componentInstance.pendingBankPymentMethods = res.data?.pendingBankPayMethods || [];

                  // Subscribe to addPayMethodStatus event
                  this.stripePaymentModel.componentInstance.addPayMethodStatus.subscribe((data: any) => {
                      this.payMethodAdded = data.status;
                  });

                  this.stripePaymentModel.componentInstance.stripePaymentModelNo = () => {
                    this.stripePaymentModel.dismiss();
                  };
                }
            },
            error: (err: HttpErrorResponse) => {
              this.accountInfoService.errorCallBack(err);
            },
            complete: () => { }
        });
    };

    /**
     * Dismisses the Stripe payment modal.
     * @param action
     */
    stripePaymentModelNo(action: any) {
        this.stripePaymentModel.dismiss();
    };

    /**
     * Opens the onboarding tour steps modal
    */
    onboardStepsModal!: NgbModalRef
    displayOnboardTourModal() {
        this.onboardStepsModal = this.modalService.open(OnboardingTourStepsModalComponent,{size: 'lg'});
        this.onboardStepsModal.componentInstance.onboardStepsModal = this.onboardStepsModal;

        this.onboardStepsModal.componentInstance.closeOnboardStepsModal = () => {
           this.router.navigate(['/market/home']);
           this.onboardStepsModal.dismiss();
        };
    };
}
