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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import searchApi from 'src/lib/api/services/search';
import { useAppDispatch, useAppSelector } from 'src/app/redux/store';
import { doSearch } from 'src/app/redux/slices/search';
import { setFilters, setLandingFilters, setResultFilters } from 'src/app/redux/slices/filter';
import { setComingFromInsideApp } from 'src/app/redux/slices/common';
import { useForm } from 'src/lib/common/hooks/useForm';
import { getActionScore, getAddressFromLatLng, recordAction } from 'src/lib/common/helpers';
import { canadaZipValidator, isValidZip, makePath, wait } from 'src/lib/utils';
import { apiTriggerLandingFilters } from 'src/lib/constants';
import { PatientType, SortTypes, } from 'src/lib/types/types';
import withReCaptcha from 'src/components/ReCaptcha';
import Loading from '../../components/Loading';
import Button from '../../components/Button';
import Input from '../../components/Input';
import Radio from '../../components/Radio';
import { GlobalCtx } from 'src/components/Providers/GlobalProvider';
import css from './LandingPage.module.scss';
import { _cx } from 'src/utility/class';
var cx = _cx(css);
var LandingPage = function (_a) {
    var windowSize = _a.windowSize, isMobile = _a.isMobile, captchaIsLoaded = _a.isReady, executeCaptcha = _a.execute;
    var dispatch = useAppDispatch();
    var _b = __read(useState(false), 2), preChecked = _b[0], setPreChecked = _b[1];
    var isLoading = useAppSelector(function (state) { return state.search.isLoading; });
    var filters = useAppSelector(function (state) { return state.filter.filters; });
    var landingFilters = useAppSelector(function (state) { return state.filter.landingFilters; });
    var zip = filters.zip, patientType = filters.patientType, vivera = filters.vivera, address = filters.address, lat = filters.lat, lng = filters.lng;
    var _c = useAppSelector(function (state) { return state.config.config; }), localeId = _c.localeId, language = _c.language, languageData = _c.languageData, recaptchaPromiseDelay = _c.recaptchaPromiseDelay, slug = _c.slug, implementationType = _c.implementationType, zipUtility = _c.zipUtility, colors = _c.colors, useMyLocationIcon = _c.useMyLocationIcon, corporatePartners = _c.corporatePartners, enableGoogleSearch = _c.enableGoogleSearch, useRecaptchaForAPIs = _c.useRecaptchaForAPIs;
    var initGoogleAutoComplete = useContext(GlobalCtx).initGoogleAutoComplete;
    var _d = useAppSelector(function (state) { return state.common; }), partner = _d.partner, zipLatLng = _d.zipLatLng;
    var t = languageData[language];
    var isCa = localeId === null || localeId === void 0 ? void 0 : localeId.toLowerCase().includes('ca');
    var useRecaptcha = useMemo(function () { return useRecaptchaForAPIs === true; }, [implementationType, useRecaptchaForAPIs]);
    var showContent = useMemo(function () { return (useRecaptcha && captchaIsLoaded) || !useRecaptcha; }, [useRecaptcha, captchaIsLoaded]);
    var submitDependencies = useMemo(function () { return [zip, patientType, landingFilters]; }, [zip, patientType, landingFilters]);
    var LoadACOnce = useRef(false);
    var loadResultPage = useCallback(function () {
        var _a;
        dispatch(setComingFromInsideApp(true));
        dispatch(setLandingFilters({ zip: zip, patientType: patientType, address: address, lat: lat, lng: lng }));
        dispatch(setResultFilters(filters));
        (_a = document.getElementById('result-route-helper')) === null || _a === void 0 ? void 0 : _a.click();
    }, __spreadArray([], __read(submitDependencies), false));
    var ageSectionWidth = useMemo(function () {
        if (isMobile)
            return '100%';
        if ((localeId === null || localeId === void 0 ? void 0 : localeId.split('-')[1]) === 'CA')
            return "32%";
        return "24.4%";
    }, [isMobile, localeId]);
    var _e = useForm({
        customData: filters,
        onChangeDispatch: setFilters,
        errorOnInit: true,
        validations: {
            zip: {
                custom: {
                    isValid: function (value) { return isValidZip(value.trim(), isCa); },
                    message: isCa ? 'Enter Valid ZIP' : 'ZIP Code must be 5 characters long.',
                },
            },
        },
        onSubmit: useCallback(function () {
            var newSearch = apiTriggerLandingFilters.some(function (key) { return landingFilters[key] !== filters[key]; });
            var searchProps = { customProps: { newSearch: newSearch }, callback: loadResultPage };
            setTimeout(function () {
                if (useRecaptcha) {
                    executeCaptcha('do_search').then(function (token) { return __awaiter(void 0, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, wait(recaptchaPromiseDelay)];
                                case 1:
                                    _a.sent();
                                    dispatch(doSearch(__assign({ customFilters: { token: "".concat(token, "|").concat(getActionScore()) } }, searchProps)));
                                    return [2 /*return*/];
                            }
                        });
                    }); });
                }
                else {
                    dispatch(doSearch(__assign({}, searchProps)));
                }
            }, 500);
        }, __spreadArray(__spreadArray([], __read(submitDependencies), false), [useRecaptcha, executeCaptcha, filters, landingFilters], false)),
    }), errors = _e.errors, handleSubmit = _e.handleSubmit, handleChange = _e.handleChange;
    var getLocation = useCallback(function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (pos) { return __awaiter(void 0, void 0, void 0, function () {
                var lat, lng, address, zip;
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            lat = String(pos.coords.latitude);
                            lng = String(pos.coords.longitude);
                            return [4 /*yield*/, getAddressFromLatLng(lat, lng)];
                        case 1:
                            address = _b.sent();
                            zip = (_a = address === null || address === void 0 ? void 0 : address.address_compnents) === null || _a === void 0 ? void 0 : _a.find(function (adr) {
                                return adr.types.includes('postal_code');
                            }).long_name;
                            if (zip)
                                dispatch(setFilters({ zip: zip.slice(0, 5) }));
                            return [2 /*return*/];
                    }
                });
            }); });
        }
        else {
            alert(t.geo_not_supported);
        }
    }, []);
    useEffect(function () {
        if (useRecaptcha) {
            if (showContent) {
                var doPreCheck = function () { return __awaiter(void 0, void 0, void 0, function () {
                    var ok;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4 /*yield*/, executeCaptcha('pre_check').then(function (token) { return __awaiter(void 0, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0: return [4 /*yield*/, searchApi.checkCaptcha({ token: token })];
                                            case 1: return [2 /*return*/, _a.sent()];
                                        }
                                    });
                                }); })];
                            case 1:
                                ok = _a.sent();
                                if (!ok)
                                    alert(t.func_temporarily_disabled);
                                setPreChecked(Boolean(ok));
                                return [2 /*return*/];
                        }
                    });
                }); };
                doPreCheck();
                recordAction('hc');
            }
        }
        else
            setPreChecked(true);
        if (showContent && zip && zip.length < 5 && zip.length > 0) {
            alert(t.unrecognized_zip);
        }
    }, [showContent, useRecaptcha]);
    var dispatchCallback = function (_a) {
        var _b, _c;
        var geometry = _a.geometry, formatted_address = _a.formatted_address;
        if (geometry) {
            dispatch(setFilters({
                address: formatted_address,
                lat: String((_b = geometry.location) === null || _b === void 0 ? void 0 : _b.lat()),
                lng: String((_c = geometry.location) === null || _c === void 0 ? void 0 : _c.lng()),
            }));
        }
    };
    var hasGeometry = useCallback(function () { return Boolean(zipLatLng.lat && zipLatLng.lng); }, [zipLatLng]);
    var searchUrl = useMemo(function () {
        return "".concat(makePath((partner === null || partner === void 0 ? void 0 : partner.redirectSlug) || slug), "?").concat(enableGoogleSearch && hasGeometry()
            ? "lat=".concat(zipLatLng.lat, "&lng=").concat(zipLatLng.lng).concat(zipLatLng.address ? "&address=".concat(zipLatLng.address) : "")
            : "zip=".concat(zip), "&searchType=").concat(patientType, "&vivera=").concat(vivera ? 'yes' : 'no').concat(!(partner === null || partner === void 0 ? void 0 : partner.redirectSlug) && (partner === null || partner === void 0 ? void 0 : partner.cpValue)
            ? "&".concat((corporatePartners === null || corporatePartners === void 0 ? void 0 : corporatePartners.cpQuery) || "b2b_partnership", "=").concat(partner === null || partner === void 0 ? void 0 : partner.cpValue)
            : "");
    }, [zipLatLng]);
    return showContent && preChecked ? (_jsxs(_Fragment, { children: [_jsx("a", { id: "result-route-helper", style: { display: 'none' }, href: searchUrl, rel: "noreferrer noopener" }), _jsx("div", { className: cx('styled-section', { isLoading: isLoading }), children: _jsx(Loading, { isLoading: isLoading, children: _jsx("form", { onSubmit: handleSubmit, children: _jsxs("div", { className: cx('container', { isMobile: isMobile }), children: [_jsxs("div", { className: cx('form-group zip-bar'), children: [_jsx("label", { htmlFor: "find_a_doctor", className: cx('upper'), color: colors === null || colors === void 0 ? void 0 : colors.black, children: t.search_zip_label }), _jsxs("div", { className: cx('input-wrap'), children: [_jsx(Input, { id: "find_a_doctor", value: enableGoogleSearch ? address || zip : zip, type: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.type, mode: "presentation", onChange: function (e) {
                                                        if (isCa) {
                                                            if (e.target.value.length > 7) {
                                                                return false;
                                                            }
                                                            var res = canadaZipValidator(e.target.value, zip);
                                                            if (res !== false && typeof res === 'string') {
                                                                // @ts-ignore
                                                                handleChange('zip')({ target: { value: res } });
                                                            }
                                                        }
                                                        else {
                                                            handleChange(enableGoogleSearch ? 'address' : 'zip')(e);
                                                        }
                                                    }, mask: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.mask, maskChar: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.maskChar, maxLength: zipUtility === null || zipUtility === void 0 ? void 0 : zipUtility.maxLength, isInValid: zip.length > 0 ? Boolean(errors.zip) : undefined, placeholder: t.search_zip_input_placeholder, borderColor: colors === null || colors === void 0 ? void 0 : colors.primary, bgColor: "#ffffff", autoFocus: true, onSelect: function () { return __awaiter(void 0, void 0, void 0, function () {
                                                        return __generator(this, function (_a) {
                                                            switch (_a.label) {
                                                                case 0:
                                                                    if (!(enableGoogleSearch && initGoogleAutoComplete)) return [3 /*break*/, 2];
                                                                    if (LoadACOnce.current)
                                                                        return [2 /*return*/];
                                                                    LoadACOnce.current = true;
                                                                    return [4 /*yield*/, initGoogleAutoComplete('find_a_doctor', localeId || 'pt-BR', dispatchCallback)];
                                                                case 1:
                                                                    _a.sent();
                                                                    return [3 /*break*/, 3];
                                                                case 2: return [2 /*return*/];
                                                                case 3: return [2 /*return*/];
                                                            }
                                                        });
                                                    }); }, inputStyle: {
                                                        width: '100%',
                                                        padding: '10px 15px 10px 20px',
                                                        border: '1px solid #efefef',
                                                        borderRadius: '100px',
                                                        color: '#727272',
                                                        height: '50px',
                                                        fontSize: '14px',
                                                        marginBottom: '32px',
                                                    } }), _jsxs(Button, { styleType: "icon", onClick: getLocation, type: "button", color: colors === null || colors === void 0 ? void 0 : colors.black, buttonStyle: {
                                                        position: 'absolute',
                                                        right: '15px',
                                                        bottom: '10px',
                                                        padding: '0',
                                                        margin: '0',
                                                    }, children: [_jsx("i", { style: { display: 'none' }, children: "search" }), _jsx("svg", { width: "21.9", height: "21.9", viewBox: "0 0 22 23", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: _jsx("path", { d: "M10 22.4501V20.4501C7.91672 20.2167 6.12938 19.3544 4.63805 17.8631C3.14605 16.3711 2.28338 14.5834 2.05005 12.5H0.0500488V10.5H2.05005C2.28338 8.41672 3.14605 6.62905 4.63805 5.13705C6.12938 3.64572 7.91672 2.78338 10 2.55005V0.550049H12V2.55005C14.0834 2.78338 15.8711 3.64572 17.3631 5.13705C18.8544 6.62905 19.7167 8.41672 19.9501 10.5H21.9501V12.5H19.9501C19.7167 14.5834 18.8544 16.3711 17.3631 17.8631C15.8711 19.3544 14.0834 20.2167 12 20.4501V22.4501H10ZM11 18.5C12.9334 18.5 14.5834 17.8167 15.95 16.45C17.3167 15.0834 18 13.4334 18 11.5C18 9.56672 17.3167 7.91672 15.95 6.55005C14.5834 5.18338 12.9334 4.50005 11 4.50005C9.06672 4.50005 7.41672 5.18338 6.05005 6.55005C4.68338 7.91672 4.00005 9.56672 4.00005 11.5C4.00005 13.4334 4.68338 15.0834 6.05005 16.45C7.41672 17.8167 9.06672 18.5 11 18.5ZM11 15.5C9.90005 15.5 8.95838 15.1084 8.17505 14.325C7.39172 13.5417 7.00005 12.6 7.00005 11.5C7.00005 10.4 7.39172 9.45838 8.17505 8.67505C8.95838 7.89172 9.90005 7.50005 11 7.50005C12.1 7.50005 13.0417 7.89172 13.825 8.67505C14.6084 9.45838 15 10.4 15 11.5C15 12.6 14.6084 13.5417 13.825 14.325C13.0417 15.1084 12.1 15.5 11 15.5Z", fill: "#3D3935" }) })] })] })] }), _jsxs("div", { className: cx('form-group age-group'), children: [_jsx("label", { className: cx('upper'), color: colors === null || colors === void 0 ? void 0 : colors.black, children: t.search_age_label }), _jsxs("div", { className: cx('flex-row-wrapper'), style: { height: 53 }, children: [_jsx(Radio, { id: "age_teen", label: t.search_age_teen, value: PatientType.TEEN, checked: patientType === PatientType.TEEN, onChange: function (e) {
                                                        var sortTypeEvent = { target: { value: SortTypes.teen } };
                                                        handleChange('patientType')(e);
                                                        handleChange('sortType')(sortTypeEvent);
                                                    }, useSpaceAfter: true, useSpaceBelow: !isMobile && windowSize.width < 936 ? 20 : 0 }), _jsx(Radio, { id: "age_adult", label: t.search_age_adult, value: PatientType.ADULT, checked: patientType === PatientType.ADULT, onChange: handleChange('patientType') })] })] }), _jsx("div", { className: cx('form-group btn-wrapper'), children: _jsx("div", { style: { position: 'relative', height: '100%' }, children: _jsx(Button, { type: "submit", styleType: "primary", dataTeliumEvent: t.event_fad_search_main, disabled: Object.keys(errors).length !== 0, textWeight: 600, width: "100%", children: t.search_search_button_label }) }) })] }) }) }) })] })) : (_jsx(_Fragment, {}));
};
export default withReCaptcha(LandingPage);
