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, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, 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 { isEqual, setCookie, wait } from 'src/lib/utils';
import { apiTriggerResultFilters } from 'src/lib/constants';
import withReCaptcha from 'src/components/ReCaptcha';
import Result from './Result';
import FilterBar from './FilterBar/FilterBar';
import Loading from '../../components/Loading';
import { setResultFilters } from 'src/app/redux/slices/filter';
import { getActionScore } from 'src/lib/common/helpers';
import Button from 'src/components/Button';
import css from './ResultPage.module.scss';
import { _cx } from 'src/utility/class';
var cx = _cx(css);
export var renderAddress = function (line1, line2, city, state, postalCode, breakLines) {
    return (_jsxs(_Fragment, { children: [breakLines ? (_jsxs(_Fragment, { children: [line1, _jsx("br", {}), line2] })) : ("".concat(line1).concat(line2 ? ", ".concat(line2) : "")), _jsx("br", {}), "".concat(city).concat(state ? ", ".concat(state) : "").concat(postalCode ? ", ".concat(postalCode) : "")] }));
};
export var getLink = function (url, children, className, pointer, trackCb) {
    return (_jsx("a", { className: className, href: url, rel: pointer ? 'noreferrer noopener' : undefined, target: pointer ? '_blank' : undefined, onClick: trackCb ? function () { return trackCb(); } : undefined, children: children }));
};
var ResultPage = function (_a) {
    var isMobile = _a.isMobile, windowSize = _a.windowSize, captchaIsLoaded = _a.isReady, executeCaptcha = _a.execute, setUniversalFadSearch = _a.setUniversalFadSearch, setFromMiniSearch = _a.setFromMiniSearch;
    var _b = __read(useState(false), 2), preChecked = _b[0], setPreChecked = _b[1];
    var dispatch = useAppDispatch();
    var comingFromInsideApp = useAppSelector(function (state) { return state.common.comingFromInsideApp; });
    var _c = useAppSelector(function (state) { return state.config.config; }), localeId = _c.localeId, language = _c.language, languageData = _c.languageData, recaptchaPromiseDelay = _c.recaptchaPromiseDelay, implementationType = _c.implementationType, universalFadSearch = _c.universalFadSearch, mainToggleFilter = _c.mainToggleFilter, useRecaptchaForAPIs = _c.useRecaptchaForAPIs, fromMiniSearch = _c.fromMiniSearch;
    var t = languageData[language];
    var useRecaptcha = useMemo(function () { return useRecaptchaForAPIs === true; }, [implementationType, useRecaptchaForAPIs]);
    var allowUnivFadSearch = useMemo(function () { return (localeId === null || localeId === void 0 ? void 0 : localeId.split('-')[1]) === 'CA'; }, [localeId]);
    var _d = useAppSelector(function (state) { return state.search; }), data = _d.result, isLoading = _d.isLoading, hasSearched = _d.hasSearched;
    var searchCache = useAppSelector(function (state) { return state.cache.search; });
    var filters = useAppSelector(function (state) { return state.filter.filters; });
    var resultFilters = useAppSelector(function (state) { return state.filter.resultFilters; });
    var showResult = useMemo(function () { return data.length > 0; }, [data]);
    var doRadiusSearch = useCallback(function (customFilters) {
        var currentFilters = customFilters ? __assign(__assign({}, filters), customFilters) : filters;
        if (searchCache &&
            Object.keys(searchCache).length > 0 &&
            isEqual(currentFilters, resultFilters)) {
            return;
        }
        var triggerFilters = __spreadArray(__spreadArray([], __read(apiTriggerResultFilters), false), [
            mainToggleFilter,
            'zip',
            'lat',
            'lng',
            'address',
        ], false);
        var newSearch = triggerFilters.some(function (key) { return currentFilters[key] !== resultFilters; });
        var customProps = {
            newSearch: newSearch,
            setUniversalFadSearch: allowUnivFadSearch && universalFadSearch ? setUniversalFadSearch : undefined,
            setFromMiniSearch: fromMiniSearch ? setFromMiniSearch : undefined,
        };
        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({
                                customFilters: { token: "".concat(token, "|").concat(getActionScore()) },
                                customProps: customProps,
                            }));
                            return [2 /*return*/];
                    }
                });
            }); });
        }
        else {
            dispatch(doSearch({ customProps: customProps }));
        }
        dispatch(setResultFilters(currentFilters));
    }, [useRecaptcha, filters, resultFilters, executeCaptcha]);
    var _e = __read(useState(false), 2), showModal = _e[0], setShowModal = _e[1];
    useEffect(function () {
        if (useRecaptcha && !comingFromInsideApp) {
            if (captchaIsLoaded) {
                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();
            }
        }
        else
            setPreChecked(true);
    }, [captchaIsLoaded, useRecaptcha]);
    useEffect(function () {
        setCookie('visitedDocLocSearch', true, 0);
    }, []);
    return preChecked ? (_jsxs(_Fragment, { children: [_jsx(FilterBar, { doSearch: doRadiusSearch, isMobile: isMobile, windowSize: windowSize, captchaIsLoaded: captchaIsLoaded, openFilterModal: showModal, setOpenFilterModal: setShowModal }), _jsxs(Loading, { isLoading: isLoading, children: [showResult && _jsx(Result, { result: data, isMobile: isMobile }), hasSearched && !isLoading && !showResult && (_jsxs("div", { className: cx('no_results'), children: [_jsx("h2", { children: t.error_no_result }), _jsx("p", { children: t.error_no_result_paragraph }), _jsx(Button, { type: "submit", styleType: "normal", onClick: function () { return setShowModal(true); }, children: t.error_no_result_button })] }))] })] })) : (_jsx(_Fragment, {}));
};
export default withReCaptcha(ResultPage);
