import { __awaiter } from "tslib";
import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import React from "react";
import { useTracking } from "react-tracking";
import aixp from "./integrations/aixp";
import Runtime from "./Runtime";
import { QoreClient } from "@qorebase/client";
import qore from "./hooks/qore";
import { RuntimeContext } from "@qorebase/app-component";
import { useLocation, useNavigate } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import { RuntimeThemeProvider } from "./RuntimeTheme";
const UserScope = (props) => {
    const config = RuntimeContext.useSelectState((state) => state.config);
    const loggedInPage = RuntimeContext.useSelectState((state) => { var _a; return (_a = state.config.initialPage) === null || _a === void 0 ? void 0 : _a.loggedInPage; });
    const navigate = useNavigate();
    const location = useLocation();
    const client = React.useMemo(() => new QoreClient({
        endpoint: config.endpoint,
        getToken: () => localStorage.getItem(`${config.projectID}_user_token`),
        onError: (error) => {
            var _a, _b;
            if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) === 401 &&
                !["/page/login", "/page/register"].includes(location.pathname) &&
                error.config.url !== "/v1/user") {
                navigate(`/page/login?nextPage=${loggedInPage || location.pathname}`);
            }
            if (((_b = error.response) === null || _b === void 0 ? void 0 : _b.status) === 403) {
                navigate("/page/forbidden");
            }
        },
    }), [config]);
    return _jsx(qore.QoreProvider, Object.assign({ value: client }, { children: props.children }));
};
export default function RuntimePage() {
    const aixpIntegration = aixp.useIntegration();
    const client = qore.useClient();
    const { Track } = useTracking({ data: {} }, {
        dispatch: ({ data }) => __awaiter(this, void 0, void 0, function* () {
            const user = yield client.currentUser();
            aixpIntegration.run((integration) => {
                integration.track({
                    userId: user.external_id,
                    anonymousId: uuidv4(),
                    event: data.event,
                    properties: data.properties,
                    context: data.context,
                });
            });
        }),
    });
    return (_jsx(Track, { children: _jsx(RuntimeThemeProvider, { children: _jsx(UserScope, { children: _jsx(Runtime, {}) }) }) }));
}
//# sourceMappingURL=RuntimePage.js.map