import React, { useContext, useEffect, useState, useMemo, useCallback, } from "react";
import { transformScoresMenuData } from "./utils/transformScoresMenuData";
import { getPOICategoriesWithAvailableData } from "./utils/getPOICategoriesWithAvailableData";
import { orderPOICategories } from "./utils/orderPOICategories";
import { TrackingPipelineEvents, AnalyticsEvents, } from "./types";
import { useTracking } from "~/tracking";
import { useScoreSelection } from "~/sdks/LocalContent/hooks/useScoreSelection";
import { useMarkers } from "~/hooks/useMarkers";
import { useCommute } from "~/sdks/LocalContent/hooks/useCommute";
import useEffectOnce from "~/hooks/useEffectOnce";
import { useStateManagerContext } from "~/context/stateManager";
import { useLocation } from "~/hooks/useLocation";
import { DEFAULT_TRAVEL_MODE, DEFAULT_RADIUS, DEFAULT_NUMBER_OF_POIS, SCORE_POI_CATEGORIES, } from "~/sdks/LocalContent/constants";
import { getIdFromMarker } from "~/utils/map/getIdFromMarker";
const LocalContentContext = React.createContext({});
const useLocalContent = () => useContext(LocalContentContext);
const LocalContentProvider = ({ children, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
    const { sdkState } = useStateManagerContext();
    const tracking = useTracking();
    const [isCategoriesMenuOpen, setIsCategoriesMenuOpen] = useState(false);
    const [isCommuteCalculatorOpen, setIsCommuteCalculatorOpen] = useState(false);
    const [isSidebarExpanded, setIsSidebarExpanded] = useState((_c = (_b = (_a = sdkState.options) === null || _a === void 0 ? void 0 : _a.scoresMenu) === null || _b === void 0 ? void 0 : _b.defaultOpen) !== null && _c !== void 0 ? _c : true);
    const [availablePoiSubcategories, setAvailablePoiSubcategories] = useState([]);
    const [selectedPoiSubcategory, setSelectedPoiSubcategory] = useState(null);
    const [activeMarker, setActiveMarker] = useState(undefined);
    const [commuteOptions, setCommuteOptions] = useState({
        destination: undefined,
        commuteType: DEFAULT_TRAVEL_MODE,
        label: undefined,
    });
    const { data: location } = useLocation({
        lat: (_e = (_d = sdkState.options) === null || _d === void 0 ? void 0 : _d.marker) === null || _e === void 0 ? void 0 : _e.lat,
        lng: (_g = (_f = sdkState.options) === null || _f === void 0 ? void 0 : _f.marker) === null || _g === void 0 ? void 0 : _g.lng,
    });
    const { data: commuteData, isLoading: isCommuteDataLoading } = useCommute({
        mode: commuteOptions.commuteType,
        locale: ((_h = sdkState.globalOptions) === null || _h === void 0 ? void 0 : _h.locale) || "en",
        units: (_j = sdkState.options) === null || _j === void 0 ? void 0 : _j.distanceUnit,
        label: commuteOptions.label,
        origin: {
            lat: ((_k = sdkState.options) === null || _k === void 0 ? void 0 : _k.lat) || 0,
            lng: ((_l = sdkState.options) === null || _l === void 0 ? void 0 : _l.lng) || 0,
        },
        destination: commuteOptions.destination,
    });
    useEffectOnce(() => {
        var _a, _b, _c, _d, _e, _f, _g;
        const eventAttributes = {
            mapProviderHasCustomKey: typeof ((_b = (_a = sdkState.options) === null || _a === void 0 ? void 0 : _a.mapProvider) === null || _b === void 0 ? void 0 : _b.key) !== "undefined",
            mapProviderHasCustomTheme: typeof ((_d = (_c = sdkState.options) === null || _c === void 0 ? void 0 : _c.mapProvider) === null || _d === void 0 ? void 0 : _d.theme) !== "undefined",
            centerMarkerProvided: typeof ((_e = sdkState.options) === null || _e === void 0 ? void 0 : _e.marker) !== "undefined",
            sidebarDefaultOpen: (_g = (_f = sdkState.options) === null || _f === void 0 ? void 0 : _f.scoresMenu) === null || _g === void 0 ? void 0 : _g.defaultOpen,
        };
        tracking.postEvent({
            eventType: TrackingPipelineEvents.SDK_VIEWED,
            eventAttributes: Object.entries(eventAttributes).map(([key, value]) => ({
                label: key,
                data: value,
            })),
        });
        tracking.trackAnalyticsEvent({
            eventName: AnalyticsEvents.SDK_VIEWED,
            eventAttributes,
        });
    });
    const handleToggleIsCommuteCalculatorOpen = useCallback(() => {
        setIsCommuteCalculatorOpen((prev) => {
            if (!prev) {
                setIsCategoriesMenuOpen(false);
            }
            else {
                setCommuteOptions(Object.assign(Object.assign({}, commuteOptions), { label: undefined, destination: undefined }));
            }
            return !prev;
        });
        // Close any open popup when toggling commute calculator
        setActiveMarker(undefined);
    }, [commuteOptions]);
    const handleToggleIsSidebarExpanded = useCallback(() => {
        setIsSidebarExpanded((prev) => !prev);
        // Close any open popup when toggling sidebar to avoid positioning issues
        setActiveMarker(undefined);
    }, []);
    const handleSelectPoiSubcategory = useCallback((subcategory) => {
        setSelectedPoiSubcategory((prev) => prev === subcategory ? null : subcategory);
    }, []);
    const handleMarkerClick = useCallback((marker) => {
        if ((activeMarker === null || activeMarker === void 0 ? void 0 : activeMarker.latitude) === (marker === null || marker === void 0 ? void 0 : marker.latitude) &&
            (activeMarker === null || activeMarker === void 0 ? void 0 : activeMarker.longitude) === (marker === null || marker === void 0 ? void 0 : marker.longitude)) {
            setActiveMarker(undefined);
            return;
        }
        setActiveMarker(marker);
    }, [activeMarker, isCategoriesMenuOpen]);
    const handleCalculateCommute = (options) => {
        setCommuteOptions(options);
        handleMarkerClick();
        if (!isCommuteCalculatorOpen) {
            handleToggleIsCommuteCalculatorOpen();
        }
    };
    const sortedScoresMenu = useMemo(() => { var _a; return transformScoresMenuData((_a = sdkState.options) === null || _a === void 0 ? void 0 : _a.scoresMenu); }, [(_o = (_m = sdkState.options) === null || _m === void 0 ? void 0 : _m.scoresMenu) === null || _o === void 0 ? void 0 : _o.categories]);
    const { isLoading: isScoresLoading, scoresData, activeScore, activeScoreData, activeCategory, activeCategoryData, handleSelectScore, handleSelectCategory, } = useScoreSelection({
        scoresMenu: sortedScoresMenu,
        lat: ((_p = sdkState === null || sdkState === void 0 ? void 0 : sdkState.options) === null || _p === void 0 ? void 0 : _p.lat) || 0,
        lng: ((_q = sdkState === null || sdkState === void 0 ? void 0 : sdkState.options) === null || _q === void 0 ? void 0 : _q.lng) || 0,
    });
    const { isLoading: isMarkersLoading, data: markersData } = useMarkers({
        lat: ((_r = sdkState === null || sdkState === void 0 ? void 0 : sdkState.options) === null || _r === void 0 ? void 0 : _r.lat) || 0,
        lng: ((_s = sdkState === null || sdkState === void 0 ? void 0 : sdkState.options) === null || _s === void 0 ? void 0 : _s.lng) || 0,
        categoriesDeprecated: activeScore
            ? SCORE_POI_CATEGORIES[activeScore]
            : undefined,
        radius: DEFAULT_RADIUS,
        limit: DEFAULT_NUMBER_OF_POIS,
    });
    useEffect(() => {
        if (!activeScore ||
            isMarkersLoading ||
            typeof markersData === "undefined" ||
            Object.keys(markersData).length === 0) {
            if (selectedPoiSubcategory !== null) {
                handleSelectPoiSubcategory(null);
            }
            return;
        }
        const filteredSubcategories = getPOICategoriesWithAvailableData(markersData);
        if (filteredSubcategories.length === 0) {
            handleSelectPoiSubcategory(null);
            return;
        }
        // If a valid subcategory is already selected and still exists in the data, keep it
        if (selectedPoiSubcategory !== null &&
            filteredSubcategories.includes(selectedPoiSubcategory)) {
            return;
        }
        orderPOICategories(activeScore, filteredSubcategories);
        setAvailablePoiSubcategories(filteredSubcategories);
        // Otherwise, select the first available subcategory
        handleSelectPoiSubcategory(filteredSubcategories[0]);
    }, [isMarkersLoading, markersData, selectedPoiSubcategory]);
    /**
     * This is used to determine which scores should be hidden in the UI.
     * It is mainly calculated here to avoid recalculating it in multiple components.
     */
    const hideScoresList = useMemo(() => {
        let tempHideScoresList = [];
        if (!sortedScoresMenu)
            return tempHideScoresList;
        sortedScoresMenu.categories.forEach(([, categoryValue]) => {
            var _a;
            if (categoryValue.hide || ((_a = sdkState.options) === null || _a === void 0 ? void 0 : _a.hideScores)) {
                tempHideScoresList = tempHideScoresList.concat(categoryValue.scores.flatMap(([scoreKey]) => scoreKey));
            }
            else {
                tempHideScoresList = tempHideScoresList.concat(categoryValue.scores
                    .filter(([, scoreValue]) => scoreValue.hideScore)
                    .map(([scoreKey]) => scoreKey));
            }
        });
        return tempHideScoresList;
    }, [sortedScoresMenu, sdkState.options]);
    const activeMarkerDetails = useMemo(() => {
        var _a;
        if (!markersData ||
            !selectedPoiSubcategory ||
            !activeMarker ||
            activeMarker.markers.length !== 1) {
            return null;
        }
        return (((_a = markersData[selectedPoiSubcategory]) === null || _a === void 0 ? void 0 : _a.find((marker) => activeMarker.markers[0].id ===
            getIdFromMarker(marker.lat, marker.lng, marker.name))) || null);
    }, [activeMarker, markersData, selectedPoiSubcategory]);
    const contextValue = useMemo(() => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
        return ({
            isLoading: isScoresLoading || isMarkersLoading,
            isScoresLoading,
            isMarkersLoading,
            isCommuteDataLoading,
            isCategoriesMenuOpen,
            isCommuteCalculatorOpen,
            isSidebarExpanded,
            locale: ((_a = sdkState.globalOptions) === null || _a === void 0 ? void 0 : _a.locale) || "en",
            location: {
                lat: (_b = sdkState.options) === null || _b === void 0 ? void 0 : _b.lat,
                lng: (_c = sdkState.options) === null || _c === void 0 ? void 0 : _c.lng,
            },
            country: (location === null || location === void 0 ? void 0 : location.country) || "CAN",
            centerMarker: (_d = sdkState.options) === null || _d === void 0 ? void 0 : _d.marker,
            distanceUnit: (_e = sdkState.options) === null || _e === void 0 ? void 0 : _e.distanceUnit,
            map: {
                mapProvider: (_f = sdkState.options) === null || _f === void 0 ? void 0 : _f.mapProvider,
                zoom: (_g = sdkState.options) === null || _g === void 0 ? void 0 : _g.zoom,
                pitch: (_h = sdkState.options) === null || _h === void 0 ? void 0 : _h.pitch,
                bearing: (_j = sdkState.options) === null || _j === void 0 ? void 0 : _j.bearing,
                cooperativeGestures: (_k = sdkState.options) === null || _k === void 0 ? void 0 : _k.cooperativeGestures,
            },
            scoresMenu: sortedScoresMenu,
            activeScore,
            activeScoreData,
            activeCategory,
            activeCategoryData,
            activeMarker,
            activeMarkerDetails,
            markersData,
            scoresData,
            availablePoiSubcategories,
            selectedPoiSubcategory,
            hideScoresList,
            hideAllScores: (_l = sdkState.options) === null || _l === void 0 ? void 0 : _l.hideScores,
            showSchoolRatings: (_m = sdkState.options) === null || _m === void 0 ? void 0 : _m.showSchoolRatings,
            commuteData: commuteData || null,
            commuteOptions,
            hideAttribution: (_o = sdkState.options) === null || _o === void 0 ? void 0 : _o.hideAttribution,
            handleToggleIsCommuteCalculatorOpen,
            handleToggleIsSidebarExpanded,
            handleSelectScore,
            handleSelectCategory,
            handleSelectPoiSubcategory,
            handleMarkerClick,
            handleCalculateCommute,
        });
    }, [
        isScoresLoading,
        isMarkersLoading,
        isCategoriesMenuOpen,
        isCommuteCalculatorOpen,
        isSidebarExpanded,
        isCommuteDataLoading,
        sdkState.globalOptions,
        sdkState.options,
        location,
        sortedScoresMenu,
        activeScore,
        activeScoreData,
        activeCategory,
        activeCategoryData,
        activeMarker,
        activeMarkerDetails,
        markersData,
        scoresData,
        availablePoiSubcategories,
        selectedPoiSubcategory,
        commuteData,
        hideScoresList,
        commuteOptions,
        (_t = sdkState.options) === null || _t === void 0 ? void 0 : _t.hideAttribution,
        handleToggleIsCommuteCalculatorOpen,
        handleToggleIsSidebarExpanded,
        handleSelectScore,
        handleSelectCategory,
        handleSelectPoiSubcategory,
        handleMarkerClick,
        handleCalculateCommute,
    ]);
    return (React.createElement(LocalContentContext.Provider, { value: contextValue }, children));
};
export { useLocalContent, LocalContentProvider };
//# sourceMappingURL=context.js.map