var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Component, useContext, useEffect, useState } from 'react';
import { useAppDispatch, useAppSelector } from 'src/app/redux/store';
import { GlobalCtx } from '../Providers/GlobalProvider';
import { setConfig } from 'src/app/redux/slices/config';
import { setFilters } from 'src/app/redux/slices/filter';
import { setView, setPartner, setAlertModal, setProgramEnabled } from 'src/app/redux/slices/common';
import { changePath, getAllFilters, getFiltersFromUrl, getPageView, getSortType, recordAction, } from 'src/lib/common/helpers';
import Modal from '../Modal/ModalModule';
import { getHostEnv, makePath, initGoogleAutoCompleteBackup } from 'src/lib/utils';
import { action_time_out, googleLocationApi } from 'src/lib/constants';
import { DocLocViews, PatientType, SortTypes } from 'src/lib/types/types';
import useWindowSize from 'src/lib/common/hooks/useWindowSize';
import CacheWatcher from '../CacheWatcher';
import Providers from '../Providers';
import LandingPage from '../../pages/LandingPage';
import ResultPage from '../../pages/ResultPage';
import ProfilePage from 'src/pages/ProfilePage/ProfilePage';
import css from './DocLocator.module.scss';
import { _cx } from 'src/utility/class';
import { updateAppointment } from 'src/app/redux/slices/doctor';
var cx = _cx(css);
var DocLocator = function (_a) {
    var _b;
    var config = _a.config;
    var dispatch = useAppDispatch();
    var _c = useAppSelector(function (state) { return state.config.config; }), language = _c.language, languageData = _c.languageData, defaultSort = _c.defaultSort, fadFromNav = _c.fadFromNav, availablePrograms = _c.availablePrograms, googleKey = _c.googleKey, localeId = _c.localeId, enableGoogleSearch = _c.enableGoogleSearch, enableHfd = _c.enableHfd, enablePreferredContactTime = _c.enablePreferredContactTime;
    var isCa = (_b = localeId === null || localeId === void 0 ? void 0 : localeId.toLowerCase().includes('ca')) !== null && _b !== void 0 ? _b : false;
    var _d = useAppSelector(function (state) { return state.common; }), partner = _d.partner, view = _d.view, alertModal = _d.alertModal;
    var sortTypeFilter = useAppSelector(function (state) { return state.filter.filters.sortType; });
    var vivera = useAppSelector(function (state) { return state.filter.filters.vivera; });
    var landingZip = useAppSelector(function (state) { return state.filter.landingFilters.zip; });
    var t = languageData[language];
    var _e = useContext(GlobalCtx), setChangeView = _e.setChangeView, setSendAppointment = _e.setSendAppointment, setInitGoogleAutoComplete = _e.setInitGoogleAutoComplete;
    var windowSize = useWindowSize();
    var isMobile = windowSize.width < 768;
    var _f = __read(useState(false), 2), isMounted = _f[0], setIsMounted = _f[1];
    useEffect(function () {
        enableHfd && document.body.classList.add('hfdEnable');
        enablePreferredContactTime && document.body.classList.add('preferredContactTimeEnable');
        var mouseUpTouchEndListener = function () { return recordAction('ms'); };
        window.addEventListener('mouseup', mouseUpTouchEndListener);
        window.addEventListener('touchend', mouseUpTouchEndListener);
        var intervalId = setInterval(function () {
            var time = window.sessionStorage.getItem('total_time');
            if (time == undefined)
                time = 0;
            else
                time = parseInt(time);
            if (time > action_time_out) {
                clearInterval(intervalId);
                recordAction('ts');
            }
            window.sessionStorage.setItem('total_time', time + 1);
        }, 1000);
        // Google Maps script loading with proper error handling
        var loadGoogleMapsScript = function () {
            // Check if script is already loaded or loading
            if (document.querySelector('script[src*="maps.googleapis.com"]')) {
                console.log('Google Maps script already loaded or loading');
                return;
            }
            // Check if Google Maps API is already available
            if (typeof window.google === 'object' &&
                typeof window.google.maps === 'object' &&
                typeof window.google.maps.places === 'object') {
                console.log('Google Maps API already available');
                return;
            }
            var script = document.createElement('script');
            var apiKey = googleKey || process.env.REACT_APP_GOOGLE_KEY;
            if (!apiKey) {
                console.error('Google Maps API key not found');
                return;
            }
            script.src = "".concat(googleLocationApi, "?libraries=geometry,places&key=").concat(apiKey, "&language=").concat(localeId || 'en');
            script.async = true;
            script.defer = true;
            script.onload = function () {
                console.log('Google Maps script loaded successfully');
            };
            script.onerror = function (error) {
                console.error('Error loading Google Maps script:', error);
            };
            document.head.appendChild(script);
        };
        // Load Google Maps script
        loadGoogleMapsScript();
        // Add Google Autocomplete styles
        var googleAutoCompleteStyle = document.createElement('style');
        googleAutoCompleteStyle.textContent = "\n      .pac-container {\n        min-width: 150px;\n        z-index: 9999;\n      }\n      .pac-item {\n        padding: 8px 12px;\n        cursor: pointer;\n      }\n      .pac-item:hover {\n        background-color: #f5f5f5;\n      }\n    ";
        document.head.appendChild(googleAutoCompleteStyle);
        // Cleanup function
        return function () {
            window.removeEventListener('mouseup', mouseUpTouchEndListener);
            window.removeEventListener('touchend', mouseUpTouchEndListener);
            clearInterval(intervalId);
        };
    }, [googleKey, localeId, enableHfd]);
    useEffect(function () {
        var changeView = config.changeView, sendAppointment = config.sendAppointment, setFadFromNav = config.setFadFromNav, initGoogleAutoComplete = config.initGoogleAutoComplete, pageSlugs = config.pageSlugs, appConfig = __rest(config, ["changeView", "sendAppointment", "setFadFromNav", "initGoogleAutoComplete", "pageSlugs"]);
        var pageView = getPageView({
            doctorLocatorUrl: (pageSlugs === null || pageSlugs === void 0 ? void 0 : pageSlugs.doctorLocatorUrl) || 'find-a-doctor/results',
            doctorProfileUrl: (pageSlugs === null || pageSlugs === void 0 ? void 0 : pageSlugs.doctorProfileUrl) || 'find-a-doctor/profile',
        }, isCa !== null && isCa !== void 0 ? isCa : false, appConfig.zipUtility);
        if (changeView)
            setChangeView(changeView);
        if (initGoogleAutoComplete)
            setInitGoogleAutoComplete(initGoogleAutoComplete);
        else
            setInitGoogleAutoComplete(initGoogleAutoCompleteBackup);
        if (sendAppointment)
            setSendAppointment(sendAppointment);
        if (setFadFromNav)
            setFadFromNav(false);
        appConfig.optin &&
            dispatch(updateAppointment({ alignInfoAgreed: !!appConfig.optin.preChecked }));
        pageView !== view && dispatch(setView(pageView));
        !isMounted && setIsMounted(true);
    }, [config]);
    useEffect(function () {
        var _a, _b;
        var filtersFromUrl = getFiltersFromUrl();
        if (view === DocLocViews.RESULT) {
            var allFilters = getAllFilters(view);
            var defSortType = (_a = getSortType(defaultSort)) !== null && _a !== void 0 ? _a : sortTypeFilter;
            var finalSortType = allFilters.sortType ||
                (allFilters.patientType === PatientType.TEEN ? SortTypes.teen : defSortType);
            dispatch(setFilters(__assign(__assign(__assign(__assign({}, allFilters), { sortType: finalSortType }), (partner && { partner: partner === null || partner === void 0 ? void 0 : partner.name })), ((filtersFromUrl === null || filtersFromUrl === void 0 ? void 0 : filtersFromUrl.address) && { address: decodeURI(filtersFromUrl === null || filtersFromUrl === void 0 ? void 0 : filtersFromUrl.address) }))));
        }
        if (view === DocLocViews.WELCOME) {
            var viveraFromUrl = (_b = filtersFromUrl.vivera) !== null && _b !== void 0 ? _b : vivera;
            var newZip = !fadFromNav ? landingZip !== null && landingZip !== void 0 ? landingZip : filtersFromUrl.zip : '';
            dispatch(setFilters(__assign(__assign({ zip: newZip || '', vivera: viveraFromUrl }, ((filtersFromUrl === null || filtersFromUrl === void 0 ? void 0 : filtersFromUrl.address) && { address: decodeURI(filtersFromUrl.address) })), (partner && { partner: partner.name }))));
            recordAction('hp');
        }
    }, [view, partner]);
    var urlParams = getFiltersFromUrl();
    var isProgtamEnabled = urlParams.program && (availablePrograms === null || availablePrograms === void 0 ? void 0 : availablePrograms.includes(urlParams.program));
    dispatch(setProgramEnabled(isProgtamEnabled && urlParams.program ? urlParams.program : ''));
    return isMounted ? (_jsxs("div", { className: cx('styled-doc-locator'), children: [_jsx(CacheWatcher, { cacheKey: "search" }), (view === DocLocViews.WELCOME || view === DocLocViews.RESULT) && (_jsx(_Fragment, { children: _jsxs("section", { className: cx('hero'), id: "hero", children: [_jsx("h1", { className: cx('eyebrow-head'), children: isProgtamEnabled
                                ? t["search_hero_title_".concat(urlParams.program)] || t.search_hero_title
                                : t.search_hero_title }), isProgtamEnabled && t["search_hero_subtitle_".concat(urlParams.program)] && (_jsx("p", { className: cx('eyebrow-subhead'), dangerouslySetInnerHTML: {
                                __html: isProgtamEnabled
                                    ? t["search_hero_subtitle_".concat(urlParams.program)] || ''
                                    : t.search_hero_subtitle || '',
                            } }))] }) })), _jsx("div", { id: "scroll-helper" }), view === DocLocViews.WELCOME && _jsx(LandingPage, { isMobile: isMobile, windowSize: windowSize }), view === DocLocViews.RESULT && (_jsx(ResultPage, { isMobile: isMobile, windowSize: windowSize, setUniversalFadSearch: config.setUniversalFadSearch, setFromMiniSearch: config.setFromMiniSearch })), view === DocLocViews.DOC_PROFILE && (_jsx(ProfilePage, { isMobile: isMobile, windowSize: windowSize })), alertModal.show && (_jsx(Modal, { setShowModal: function () {
                    return dispatch(setAlertModal({ show: false, title: '', description: '', imgUrl: '' }));
                }, size: "sm", subTitle: alertModal.title, description: alertModal.description, closeButton: true, children: alertModal.imgUrl ? (_jsx("img", { className: cx('modal-img'), src: alertModal.imgUrl, alt: "" })) : (_jsx(_Fragment, {})) }))] })) : (_jsx(_Fragment, {}));
};
var UpdateInitialStateAndRenderDoclocComponent = function (config) {
    var _a, _b, _c, _d, _e;
    var queryParams = Object.fromEntries(new URLSearchParams(window.location.search));
    var path = window.location.pathname;
    var changeView = config.changeView, sendAppointment = config.sendAppointment, setFadFromNav = config.setFadFromNav, initGoogleAutoComplete = config.initGoogleAutoComplete, enableGoogleSearch = config.enableGoogleSearch, testTokenApiUrlNA = config.testTokenApiUrlNA, testTokenClientIdNA = config.testTokenClientIdNA, testTokenClientSecretNA = config.testTokenClientSecretNA, 
    //test:
    testRadiusUrl_US = config.testRadiusUrl_US, testDocUrl_US = config.testDocUrl_US, testLogUrl_US = config.testLogUrl_US, testCheckCaptchaUrl = config.testCheckCaptchaUrl, testRadiusUrl_LATAM = config.testRadiusUrl_LATAM, testDocUrl_LATAM = config.testDocUrl_LATAM, testLogUrl_LATAM = config.testLogUrl_LATAM, 
    //prod:
    prodRadiusUrl_US = config.prodRadiusUrl_US, prodDocUrl_US = config.prodDocUrl_US, prodLogUrl_US = config.prodLogUrl_US, prodCheckCaptchaUrl = config.prodCheckCaptchaUrl, prodRadiusUrl_LATAM = config.prodRadiusUrl_LATAM, prodDocUrl_LATAM = config.prodDocUrl_LATAM, prodLogUrl_LATAM = config.prodLogUrl_LATAM, appConfig = __rest(config, ["changeView", "sendAppointment", "setFadFromNav", "initGoogleAutoComplete", "enableGoogleSearch", "testTokenApiUrlNA", "testTokenClientIdNA", "testTokenClientSecretNA", "testRadiusUrl_US", "testDocUrl_US", "testLogUrl_US", "testCheckCaptchaUrl", "testRadiusUrl_LATAM", "testDocUrl_LATAM", "testLogUrl_LATAM", "prodRadiusUrl_US", "prodDocUrl_US", "prodLogUrl_US", "prodCheckCaptchaUrl", "prodRadiusUrl_LATAM", "prodDocUrl_LATAM", "prodLogUrl_LATAM"]);
    var partner = (_b = (_a = appConfig.corporatePartners) === null || _a === void 0 ? void 0 : _a.partner) === null || _b === void 0 ? void 0 : _b.find(function (p) {
        var _a, _b, _c, _d, _e;
        if (queryParams.hasOwnProperty(((_a = appConfig.corporatePartners) === null || _a === void 0 ? void 0 : _a.cpQuery) || '')) {
            return (((_c = queryParams[((_b = appConfig.corporatePartners) === null || _b === void 0 ? void 0 : _b.cpQuery) || '']) === null || _c === void 0 ? void 0 : _c.toLowerCase()) ===
                ((_d = p === null || p === void 0 ? void 0 : p.cpValue) === null || _d === void 0 ? void 0 : _d.toLowerCase()));
        }
        return (_e = makePath((p === null || p === void 0 ? void 0 : p.redirectSlug) || '')) === null || _e === void 0 ? void 0 : _e.includes(path);
    });
    var hadCpQueryValueButDeleted = false;
    if ((partner === null || partner === void 0 ? void 0 : partner.redirectSlug) && queryParams[((_c = appConfig.corporatePartners) === null || _c === void 0 ? void 0 : _c.cpQuery) || '']) {
        delete queryParams[((_d = appConfig.corporatePartners) === null || _d === void 0 ? void 0 : _d.cpQuery) || ''];
        hadCpQueryValueButDeleted = true;
        changePath(changeView, partner === null || partner === void 0 ? void 0 : partner.redirectSlug, new URLSearchParams(queryParams).toString());
    }
    var dispatch = useAppDispatch();
    if (partner)
        dispatch(setPartner(partner));
    if (path === config.doctorLocatorUrl &&
        !hadCpQueryValueButDeleted &&
        !queryParams[((_e = appConfig.corporatePartners) === null || _e === void 0 ? void 0 : _e.cpQuery) || '']) {
        dispatch(setPartner({}));
    }
    var region = config.region || 'US', isLatam = region === 'LATAM' ? true : false, isApac = region === 'APAC' ? true : false, isUS = region === 'US' ? true : false;
    var prodTokenApiUrl = !isLatam
        ? process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE
        : process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE_LATAM;
    var prodTokenClientId = !isLatam
        ? process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE_CLIENT_ID
        : process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE_CLIENT_ID_LATAM;
    var prodTokenClientSecret = !isLatam
        ? process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE_CLIENT_SECRET
        : process.env.REACT_APP_DOC_LOC_TOKEN_SERVICE_CLIENT_SECRET_LATAM;
    var prodRadiusSvc = !isLatam
        ? prodRadiusUrl_US || process.env.REACT_APP_PROD_RADIUS_SVC
        : prodRadiusUrl_LATAM || process.env.REACT_APP_PROD_RADIUS_SVC_LATAM;
    var prodDocSvc = !isLatam
        ? prodDocUrl_US || process.env.REACT_APP_PROD_DOCTOR_SVC
        : prodDocUrl_LATAM || process.env.REACT_APP_PROD_DOCTOR_SVC_LATAM;
    var prodLogSvc = !isLatam
        ? prodLogUrl_US || process.env.REACT_APP_PROD_LOG_SVC
        : prodLogUrl_LATAM || process.env.REACT_APP_LATAM_PROD_LOG_SVC;
    var prodCheckCaptcha = prodCheckCaptchaUrl || process.env.REACT_APP_PROD_CHECK_CAPTCHA;
    var prodCaptchaKey = process.env.REACT_APP_PROD_RECAPTCHA_KEY;
    var testTokenApiUrl = !isLatam
        ? testTokenApiUrlNA || process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE
        : process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE_LATAM;
    var testTokenApiClientId = !isLatam
        ? testTokenClientIdNA || process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE_CLIENT_ID
        : process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE_CLIENT_ID_LATAM;
    var testTokenApiClientSecret = !isLatam
        ? testTokenClientSecretNA || process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE_CLIENT_SECRET
        : process.env.REACT_APP_TEST_DOC_LOC_TOKEN_SERVICE_CLIENT_SECRET_LATAM;
    var testRadiusSvc = !isLatam
        ? testRadiusUrl_US || process.env.REACT_APP_TEST_RADIUS_SVC
        : testRadiusUrl_LATAM || process.env.REACT_APP_TEST_RADIUS_SVC_LATAM;
    var testDocSvc = !isLatam
        ? testDocUrl_US || process.env.REACT_APP_TEST_DOCTOR_SVC
        : testDocUrl_LATAM || process.env.REACT_APP_TEST_DOCTOR_SVC_LATAM;
    var testLogSvc = !isLatam
        ? testLogUrl_US || process.env.REACT_APP_TEST_LOG_SVC
        : testLogUrl_LATAM || process.env.REACT_APP_TEST_LATAM_LOG_SVC;
    var testCheckCaptcha = testCheckCaptchaUrl || process.env.REACT_APP_TEST_CHECK_CAPTCHA;
    var hostEnv = getHostEnv(appConfig.testHosts);
    var isProd = hostEnv === 'production';
    var isTest = hostEnv === 'test';
    var pageSlugs = {
        doctorLocatorUrl: (partner === null || partner === void 0 ? void 0 : partner.redirectSlug) || appConfig.doctorLocatorUrl || 'find-a-doctor/results',
        doctorProfileUrl: appConfig.doctorProfileUrl || 'find-a-doctor/profile',
    };
    config = __assign(__assign(__assign(__assign({}, appConfig), (isProd
        ? {
            radiusSvcUrl: prodRadiusSvc,
            doctorSvcUrl: prodDocSvc,
            logSvcUrl: prodLogSvc,
            checkCaptchaUrl: prodCheckCaptcha,
            recaptchaKey: prodCaptchaKey,
            tokenApiUrl: prodTokenApiUrl,
            tokenClientId: prodTokenClientId,
            tokenClientSecret: prodTokenClientSecret,
        }
        : {})), (isTest
        ? {
            radiusSvcUrl: testRadiusSvc,
            doctorSvcUrl: testDocSvc,
            logSvcUrl: testLogSvc,
            checkCaptchaUrl: testCheckCaptcha,
            tokenApiUrl: testTokenApiUrl,
            tokenClientId: testTokenApiClientId,
            tokenClientSecret: testTokenApiClientSecret,
        }
        : {})), { pageSlugs: pageSlugs, changeView: changeView, sendAppointment: sendAppointment, setFadFromNav: setFadFromNav, initGoogleAutoComplete: initGoogleAutoComplete, isLatam: isLatam, isApac: isApac, isUS: isUS, enableGoogleSearch: enableGoogleSearch, hostEnv: hostEnv });
    dispatch(setConfig(config));
    return _jsx(DocLocator, { config: config });
};
var DocLocatorRoot = /** @class */ (function (_super) {
    __extends(DocLocatorRoot, _super);
    function DocLocatorRoot(props) {
        return _super.call(this, props) || this;
    }
    DocLocatorRoot.prototype.render = function () {
        return (_jsx(Providers, { children: _jsx(UpdateInitialStateAndRenderDoclocComponent, __assign({}, this.props)) }));
    };
    return DocLocatorRoot;
}(Component));
export default DocLocatorRoot;
