import React, { useContext, useEffect, useState } from "react";
import { C3ProfileProvider } from "./c3-profile-provider/c3-profile-provider";
import { decodeJWT } from "./authToken";
import { C3HelpCenterProvider } from "../c3-help-center/c3-help-center-provider";
export const C3UserConfigurationContext = React.createContext({
    stage: "dev",
    activeOrganizationId: "",
    setActiveOrgId: () => undefined,
    userToken: "",
    decodedToken: null,
    domain: null,
    decodedAudience: null,
    getNewUserToken: () => Promise.resolve(""),
    enableLogs: false,
    noCloudInUrl: false,
});
const C3UserConfigurationProvider = ({ children, activeOrganizationId, ...config }) => {
    const [decodedToken, setDecodedToken] = useState(null);
    const [decodedAudience, setDecodedAudience] = useState(null);
    const [domain, setDomain] = useState(null);
    const [activeOrgId, setActiveOrgId] = useState(activeOrganizationId);
    useEffect(() => {
        if (config.userToken)
            setDecodedToken(decodeJWT(config.userToken));
    }, [config.userToken]);
    useEffect(() => {
        setActiveOrgId(activeOrganizationId);
    }, [activeOrganizationId]);
    useEffect(() => {
        const { audience } = decodedToken || {};
        setDecodedAudience((typeof audience === "string" ? audience : audience?.[0]) || null);
    }, [decodedToken]);
    useEffect(() => {
        if (decodedAudience)
            setDomain(config.noCloudInUrl
                ? decodedAudience.replace("cloud.", "")
                : decodedAudience);
    }, [decodedAudience, config.noCloudInUrl]);
    return (React.createElement(C3UserConfigurationContext.Provider, { value: {
            ...config,
            activeOrganizationId: activeOrgId,
            setActiveOrgId,
            decodedToken,
            decodedAudience,
            domain,
        } },
        React.createElement(C3ProfileProvider, null,
            React.createElement(C3HelpCenterProvider, null, children))));
};
export const useC3UserConfiguration = () => useContext(C3UserConfigurationContext);
export default C3UserConfigurationProvider;
