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 } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import log from 'src/lib/api/services/log';
import { setIsDirect } from 'src/app/redux/slices/search';
import { useAppDispatch, useAppSelector } from 'src/app/redux/store';
import { searchSources } from 'src/lib/constants';
import { setHoveredMarkerId, setMobileMapView } from 'src/app/redux/slices/common';
import { wait } from 'src/lib/utils';
import Button from 'src/components/Button';
import ResultItem from './ResultItem';
import Loader from 'src/components/Loader';
import ResultGoogleMap from 'src/components/Maps/ResultGoogleMap';
import { Swiper, SwiperSlide } from 'swiper/react';
import Paginator from 'src/components/Paginator';
import { setClickedMarkerId } from 'src/app/redux/slices/common';
import 'swiper/css';
import 'swiper/css/pagination';
import css from './Result.module.scss';
import { _cx } from 'src/utility/class';
var cx = _cx(css);
export default function Result(_a) {
    var _this = this;
    var result = _a.result, isMobile = _a.isMobile;
    var dispatch = useAppDispatch();
    var _b = useAppSelector(function (state) { return state.common; }), filtersHeight = _b.filtersHeight, mobileMapView = _b.mobileMapView, clickedMarkerId = _b.clickedMarkerId, scrollToDocId = _b.scrollToDocId;
    var _c = useAppSelector(function (state) { return state.config.config; }), language = _c.language, stickyMap = _c.stickyMap;
    var t = useAppSelector(function (state) { return state.config.config.languageData[language]; });
    var _d = __read(useState(false), 2), isLoading = _d[0], setLoading = _d[1];
    var _e = __read(useState(null), 2), swiperRef = _e[0], setSwiperRef = _e[1];
    var _f = useAppSelector(function (state) { return state.config.config; }), pageLimit = _f.resultsPerPage, useInfiniteScrollOnResults = _f.useInfiniteScrollOnResults, useInfiniteScrollWithButtonOnWeb = _f.useInfiniteScrollWithButtonOnWeb, useInfiniteScrollWithButtonOnMobile = _f.useInfiniteScrollWithButtonOnMobile;
    var pageCount = useMemo(function () { return Math.ceil(result.length / pageLimit); }, [result]);
    var _g = __read(useState(0), 2), pageIndex = _g[0], setPageIndex = _g[1];
    var setIndex = useCallback(function (i, scroll) {
        setPageIndex(i);
        scroll && window.scrollTo(0, 0);
    }, [setPageIndex]);
    var isFirstPage = useMemo(function () { return pageIndex <= 0; }, [pageIndex]);
    var pageStart = useMemo(function () { return (useInfiniteScrollOnResults || isFirstPage ? 0 : pageIndex * pageLimit); }, [pageIndex]);
    var pageEnd = useMemo(function () { return (pageIndex + 1) * pageLimit; }, [pageIndex]);
    var resultToShow = useMemo(function () { return result.filter(function (r) { return r !== null; }).slice(pageStart, pageEnd); }, [result, pageEnd]);
    var hasMore = useMemo(function () { return pageEnd <= result.length - 1; }, [pageEnd]);
    var loadMore = function () { return __awaiter(_this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setLoading(true);
                    return [4 /*yield*/, wait(350)];
                case 1:
                    _a.sent();
                    setPageIndex(function (prevIndex) { return prevIndex + 1; });
                    setLoading(false);
                    return [2 /*return*/];
            }
        });
    }); };
    var markerLimit = useMemo(function () { return Math.round(pageLimit / 2); }, [pageLimit]);
    var _h = __read(useState(0), 2), markersToShowIndex = _h[0], setMarkersToShowIndex = _h[1];
    var setMarkerIndex = function (shift) { return setMarkersToShowIndex(shift); };
    var markersToShowByDocID = useMemo(function () {
        return useInfiniteScrollOnResults
            ? resultToShow
                .slice(markersToShowIndex, markersToShowIndex + pageLimit)
                .reduce(function (ids, res) { return __spreadArray(__spreadArray([], __read(ids), false), [res.DocID], false); }, [])
            : [];
    }, [markersToShowIndex]);
    var markerData = useMemo(function () {
        return resultToShow
            .filter(function (res) { return !useInfiniteScrollOnResults || (markersToShowByDocID === null || markersToShowByDocID === void 0 ? void 0 : markersToShowByDocID.includes(res.DocID)); })
            .reduce(function (data, doctor) {
            return __spreadArray(__spreadArray([], __read(data), false), [
                __assign({}, doctor),
            ], false);
        }, []);
    }, [resultToShow, markersToShowByDocID]);
    var observer = useRef();
    var lastElementRef = useCallback(function (node) {
        if ((!isMobile && !useInfiniteScrollOnResults) ||
            (isMobile && useInfiniteScrollWithButtonOnMobile))
            return;
        if (observer.current)
            observer.current.disconnect();
        observer.current = new IntersectionObserver(function (entries) { return __awaiter(_this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(((_a = entries[0]) === null || _a === void 0 ? void 0 : _a.isIntersecting) && hasMore)) return [3 /*break*/, 2];
                        return [4 /*yield*/, loadMore()];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        }); });
        if (node)
            observer.current.observe(node);
    }, [hasMore]);
    var isDirect = useAppSelector(function (state) { return state.search.isDirect; });
    useEffect(function () {
        if ((!useInfiniteScrollOnResults || isMobile) && result.length) {
            log.doLog('ResultsLoad', 200, isDirect ? searchSources.DIRECT : searchSources.NAVIGATE, result.length, resultToShow.reduce(function (docIds, res) { return __spreadArray(__spreadArray([], __read(docIds), false), [res.DocID], false); }, []), isMobile ? pageEnd - pageLimit : pageStart, pageEnd);
            if (!isDirect)
                dispatch(setIsDirect(true));
        }
    }, [pageStart, pageEnd, useInfiniteScrollOnResults, markersToShowIndex, isMobile]);
    useEffect(function () {
        if (useInfiniteScrollOnResults && !isMobile && result.length) {
            log.doLog('ResultsLoad', 200, isDirect ? searchSources.DIRECT : searchSources.NAVIGATE, result.length, markersToShowByDocID, markersToShowIndex, markersToShowIndex + pageLimit);
            if (!isDirect)
                dispatch(setIsDirect(true));
        }
    }, [markersToShowIndex, useInfiniteScrollOnResults, isMobile]);
    useEffect(function () {
        window.scrollTo(0, 0);
        if (mobileMapView) {
            setTimeout(function () {
                var _a;
                dispatch(setClickedMarkerId((_a = resultToShow[0]) === null || _a === void 0 ? void 0 : _a.DocID));
            }, 600);
        }
    }, [mobileMapView]);
    useEffect(function () {
        if (mobileMapView) {
            swiperRef === null || swiperRef === void 0 ? void 0 : swiperRef.slideTo(resultToShow.findIndex(function (item) { return item.DocID === scrollToDocId; }), 300);
        }
    }, [scrollToDocId, mobileMapView, swiperRef, resultToShow]);
    return (_jsx("div", { className: "result-selector ".concat(cx('bg-gray')), children: _jsxs("div", { className: cx('container', {
                'mobile-container': isMobile,
                containerMapView: mobileMapView,
            }), children: [_jsx("div", { className: cx('result-container'), children: _jsxs("div", { className: cx('results'), children: [isMobile && mobileMapView ? (_jsx(Swiper, { slidesPerView: "auto", onSwiper: setSwiperRef, centeredSlides: true, slideToClickedSlide: true, pagination: {
                                    clickable: true,
                                }, onSlideChange: function (swiperCore) {
                                    var activeIndex = swiperCore.activeIndex;
                                    var item = resultToShow[activeIndex];
                                    dispatch(setClickedMarkerId(item === null || item === void 0 ? void 0 : item.DocID));
                                    dispatch(setHoveredMarkerId(item === null || item === void 0 ? void 0 : item.DocID));
                                }, children: resultToShow.map(function (item, i) {
                                    var infScrollEnabled = (!isMobile && useInfiniteScrollOnResults) ||
                                        (isMobile && !useInfiniteScrollWithButtonOnMobile);
                                    var hasLastRef = infScrollEnabled &&
                                        !useInfiniteScrollWithButtonOnWeb &&
                                        resultToShow.length === i + 1;
                                    var needMarkerRef = infScrollEnabled && i !== 0 && i % markerLimit === 0;
                                    return (_jsx(SwiperSlide, { className: cx('slider-card'), children: _jsx(ResultItem, { item: item, isMobile: isMobile, elRef: hasLastRef ? lastElementRef : undefined, needMarkerRef: needMarkerRef, markerIndex: i, setMarkerIndex: setMarkerIndex, mapView: isMobile && mobileMapView, clickedMarkerId: clickedMarkerId, scrollToDocId: scrollToDocId }, "".concat(i, "-").concat(item.FullName)) }, "".concat(i, "-").concat(item.FullName)));
                                }) })) : (resultToShow.map(function (item, i) {
                                var infScrollEnabled = (!isMobile && useInfiniteScrollOnResults) ||
                                    (isMobile && !useInfiniteScrollWithButtonOnMobile);
                                var hasLastRef = infScrollEnabled &&
                                    !useInfiniteScrollWithButtonOnWeb &&
                                    resultToShow.length === i + 1;
                                var needMarkerRef = infScrollEnabled && i !== 0 && i % markerLimit === 0;
                                return (_jsx(ResultItem, { item: item, isMobile: isMobile, elRef: hasLastRef ? lastElementRef : undefined, needMarkerRef: needMarkerRef, markerIndex: i, setMarkerIndex: setMarkerIndex, mapView: isMobile && mobileMapView, clickedMarkerId: clickedMarkerId, scrollToDocId: scrollToDocId }, "".concat(i, "-").concat(item.FullName)));
                            })), !useInfiniteScrollOnResults && !(mobileMapView && isMobile) && pageCount > 1 && (_jsx("div", { className: cx('bottom-result-bar'), children: _jsx(Paginator, { pageCount: pageCount, currentPageIndex: pageIndex, setIndex: setIndex, showHeader: false }) })), isLoading && (_jsx("div", { style: { margin: '0 auto' }, children: _jsx(Loader, {}) }))] }) }), !(!mobileMapView && isMobile) && (_jsx("div", { className: cx('map-container'), style: {
                        position: !isMobile ? (stickyMap ? 'sticky' : 'relative') : 'relative',
                        top: !isMobile ? (stickyMap ? filtersHeight : "") : "",
                    }, children: _jsx(ResultGoogleMap, { markerData: markerData, mobileMapView: mobileMapView }) })), isMobile && (_jsx(Button, { onClick: function () {
                        dispatch(setMobileMapView(!mobileMapView));
                    }, styleType: 'fixed', children: mobileMapView ? (_jsxs("span", { children: [t.listView, _jsxs("svg", { width: "21", height: "17", viewBox: "0 0 21 17", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: [_jsx("path", { d: "M1.5 1.5H19.5", stroke: "white", strokeWidth: "3", strokeLinecap: "round" }), _jsx("path", { d: "M1.5 8.5H19.5", stroke: "white", strokeWidth: "3", strokeLinecap: "round" }), _jsx("path", { d: "M1.5 15.5H19.5", stroke: "white", strokeWidth: "3", strokeLinecap: "round" })] })] })) : (_jsxs("span", { children: [t.mapView, _jsx("svg", { width: "19", height: "19", viewBox: "0 0 19 19", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: _jsx("path", { d: "M12.625 18.875L6.375 16.6875L1.53125 18.5625C1.18403 18.7014 0.862847 18.6622 0.567708 18.4448C0.272569 18.2281 0.125 17.9375 0.125 17.5729V2.98958C0.125 2.76389 0.190278 2.56424 0.320833 2.39062C0.450694 2.21701 0.628472 2.08681 0.854167 2L6.375 0.125L12.625 2.3125L17.4687 0.4375C17.816 0.298611 18.1372 0.3375 18.4323 0.554167C18.7274 0.771528 18.875 1.0625 18.875 1.42708V16.0104C18.875 16.2361 18.8097 16.4358 18.6792 16.6094C18.5493 16.783 18.3715 16.9132 18.1458 17L12.625 18.875ZM11.5833 16.3229V4.13542L7.41667 2.67708V14.8646L11.5833 16.3229ZM13.6667 16.3229L16.7917 15.2812V2.9375L13.6667 4.13542V16.3229ZM2.20833 16.0625L5.33333 14.8646V2.67708L2.20833 3.71875V16.0625Z", fill: "white" }) })] })) }))] }) }));
}
