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());
    });
};
import React, { useContext, useState, useMemo, useReducer, useEffect, } from "react";
import { TrackingPipelineEvents, AnalyticsEvents, } from "./types";
import * as DemographicsTabs from "./components/Content/DemographicsTabs";
import { validateOptions } from "./schema";
import { AVAILABLE_TABS } from "./constants";
import { useTracking } from "~/tracking";
import { theme } from "~/components/deprecated";
import errorTracker from "~/utils/errorTracker";
import { useLocation } from "~/hooks/useLocation";
import useEffectOnce from "~/hooks/useEffectOnce";
import { useStateManagerContext } from "~/context/stateManager";
const DemographicsContext = React.createContext({});
const useDemographics = () => useContext(DemographicsContext);
const LocalDemographicsProvider = ({ children, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const tracking = useTracking();
    const { sdkState } = useStateManagerContext();
    const [activeCategory, setActiveCategory] = useState(((_a = sdkState.options) === null || _a === void 0 ? void 0 : _a.defaultTab) &&
        AVAILABLE_TABS.includes((_b = sdkState.options) === null || _b === void 0 ? void 0 : _b.defaultTab)
        ? (_c = sdkState.options) === null || _c === void 0 ? void 0 : _c.defaultTab
        : AVAILABLE_TABS[0]);
    const [validated, setValidated] = useState(false);
    const [validationErrors, setValidationErrors] = useState([]);
    const { data: { country }, isLoading, } = useLocation({
        lat: (_d = sdkState.options) === null || _d === void 0 ? void 0 : _d.lat,
        lng: (_e = sdkState.options) === null || _e === void 0 ? void 0 : _e.lng,
    });
    useEffectOnce(() => {
        tracking.postEvent({
            eventType: TrackingPipelineEvents.SDK_VIEWED,
        });
        tracking.trackAnalyticsEvent({
            eventName: AnalyticsEvents.SDK_VIEWED,
        });
    });
    const [demographicsState, setDemographicsState] = useReducer((state, action) => (Object.assign(Object.assign({}, state), action)), {
        location: {
            lat: ((_f = sdkState.options) === null || _f === void 0 ? void 0 : _f.lat) || 43.661337,
            lng: ((_g = sdkState.options) === null || _g === void 0 ? void 0 : _g.lng) || -79.401903,
        },
        country: "CAN",
    });
    useEffect(() => {
        if (!sdkState) {
            return;
        }
        setDemographicsState(Object.assign(Object.assign({}, demographicsState), { country }));
    }, [sdkState, country]);
    useEffectOnce(() => {
        const validate = () => __awaiter(void 0, void 0, void 0, function* () {
            try {
                errorTracker.addBreadCrumb("LocalDemographicsProvider", "Validating state options", {
                    options: sdkState.options,
                });
                yield validateOptions(sdkState.options);
                setValidated(true);
            }
            catch (error) {
                const validationError = error;
                setValidationErrors(validationError.errors);
                errorTracker.addBreadCrumb("LocalDemographicsProvider", "State option validation failed", {
                    errors: validationError.errors,
                });
            }
        });
        if (!validated) {
            validate();
        }
    });
    const contextValue = useMemo(() => {
        var _a, _b;
        return ({
            country,
            demographicsState,
            setDemographicsState,
            activeCategory,
            setActiveCategory,
            locale: ((_a = sdkState.globalOptions) === null || _a === void 0 ? void 0 : _a.locale) || "en",
            hideAttribution: (_b = sdkState.options) === null || _b === void 0 ? void 0 : _b.hideAttribution,
        });
    }, [
        country,
        activeCategory,
        setActiveCategory,
        demographicsState,
        setDemographicsState,
        sdkState.globalOptions,
        (_h = sdkState.options) === null || _h === void 0 ? void 0 : _h.hideAttribution,
    ]);
    const handleTabsChange = (value) => {
        setActiveCategory(value.data);
        errorTracker.addBreadCrumb("LocalDemographicsProvider", "handleTabsChange", {
            value,
        });
        tracking.postEvent({
            eventType: TrackingPipelineEvents.TAB_CLICKED,
            eventAttributes: [
                {
                    label: "activeCategory",
                    data: value.data,
                },
            ],
        });
        tracking.trackAnalyticsEvent({
            eventName: AnalyticsEvents.CATEGORY_SELECTED,
            eventAttributes: {
                ll_selected_category: value.data,
            },
        });
    };
    const omitTabs = useMemo(() => {
        const tabsToOmit = [];
        const dataKeys = {
            income: "income",
            population: "population_age",
            housing: "housing_tenancy",
            household: "household_composition",
            education: "education_level",
            commute: "commute_mode",
            languages: "mother_tongue",
        };
        Object.entries(dataKeys).forEach(([key, value]) => {
            if (!Object.keys(demographicsState).includes(value)) {
                tabsToOmit.push(key);
            }
        });
        errorTracker.addBreadCrumb("LocalDemographicsProvider", "Updated tabs to omit", {
            tabsToOmit,
        });
        return tabsToOmit;
    }, [demographicsState]);
    if (!validated) {
        if (validationErrors.length) {
            const error = "Could not load Demographics";
            console.error(`${error}: ${validationErrors.join(", ")}`);
            return React.createElement("p", null, error);
        }
        return React.createElement(React.Fragment, null);
    }
    return (React.createElement(DemographicsContext.Provider, { value: contextValue },
        React.createElement(DemographicsTabs.Root, { options: { activeTab: activeCategory, omitTabs }, onChange: handleTabsChange },
            React.createElement("div", { style: {
                    display: "flex",
                    flexDirection: "column",
                    background: `${theme["--ll-color-background"]}`,
                    padding: `${theme["--ll-spacing-xx-small"]} ${theme["--ll-spacing-small"]} 0`,
                    borderRadius: `${theme["--ll-border-radius-medium"]}`,
                } }, !isLoading && children))));
};
export { useDemographics, LocalDemographicsProvider };
//# sourceMappingURL=context.js.map