import { atom } from 'jotai';
import { atomWithStorage, createJSONStorage } from 'jotai/utils';
import { LayoutVariant } from '@redocly/config';
import { IS_BROWSER } from '@redocly/theme/core/openapi';
import { getCookie, removeCookie, setCookie } from '../utils/cookies.js';
import { globalOptionsAtom } from './store.js';
import { mergeEnvData } from '../utils/environments.js';
import { fromSessionStorage, safeJsonParse, toSessionStorage } from '../utils/index.js';
const defaultAppStoreValue = {
    isSidebarOpened: true,
    activeMimeName: '',
    layout: LayoutVariant.THREE_PANEL,
    language: '',
    environment: '',
    environments: {},
    userClaims: {},
};
// get environment from sessionStorage and other values from cookies (so it works during SSR)
const customStorage = {
    getItem: (ctx) => {
        const cookieValue = safeJsonParse(getCookie(ctx, globalThis.redoclyCookieStorage?.getStore?.()));
        const sessionValue = safeJsonParse(fromSessionStorage(ctx));
        return {
            ...defaultAppStoreValue,
            ...sessionValue,
            ...cookieValue,
        };
    },
    setItem: (ctx, value) => {
        const { environments, ...cookieValue } = value;
        const sessionValue = { environments };
        setCookie(ctx, JSON.stringify(cookieValue));
        toSessionStorage(ctx, JSON.stringify(sessionValue));
    },
    removeItem: (ctx) => {
        removeCookie(ctx);
        sessionStorage.removeItem(ctx);
    },
};
export const appStore = atomWithStorage('redoc.appStore', defaultAppStoreValue, customStorage);
// allow some parts of appStore to be overridden
export const appStoreOverrideAtom = atom({});
export const environmentsAtom = atom((get) => {
    const state = get(appStore);
    const override = get(appStoreOverrideAtom);
    const envs = mergeEnvData(state.environments, override?.environments || {});
    return envs;
});
export const environmentAtom = atom((get) => {
    const state = get(appStore);
    const override = get(appStoreOverrideAtom);
    const envs = mergeEnvData(state.environments, override?.environments || {});
    const selectedEnvironment = override?.environment || state.environment;
    const envName = envs[selectedEnvironment] ? selectedEnvironment : Object.keys(envs)[0];
    const env = envs[envName] || {};
    return [env, envName || ''];
}, (get, set, { environment, environments }) => {
    const state = get(appStore);
    set(appStore, {
        ...state,
        environment: environment || state.environment,
        environments: mergeEnvData(state.environments || {}, environments),
    });
});
export const isSidebarOpenedAtom = atom((get) => get(appStore).isSidebarOpened, (get, set, isSidebarOpened) => {
    const state = get(appStore);
    set(appStore, { ...state, isSidebarOpened });
});
export const activeMimeNameAtom = atom((get) => get(appStore).activeMimeName, (get, set, activeMimeName) => {
    const state = get(appStore);
    set(appStore, { ...state, activeMimeName });
});
export const layoutAtom = atom((get) => get(appStore).layout, (get, set, layout = LayoutVariant.STACKED) => {
    const state = get(appStore);
    set(appStore, { ...state, layout });
});
export const userClaimsAtom = atom((get) => get(appStore).userClaims, (get, set, userClaims) => {
    const state = get(appStore);
    set(appStore, { ...state, userClaims });
});
/**
 * appSessionStore saved to session storage
 */
export const appSessionStore = atomWithStorage(// FIXME: get rid of it, need to remove versions code
'redoc.appSessionStore', {
    collapsedSidebar: false,
    unsupportedFeatureScreen: false,
}, IS_BROWSER ? createJSONStorage(() => sessionStorage) : undefined);
export const collapsedSidebarAtom = atom((get) => get(appSessionStore).collapsedSidebar, (get, set, collapsedSidebar) => {
    const state = get(appSessionStore);
    set(appSessionStore, { ...state, collapsedSidebar });
});
export function getLangKey({ lang, label }) {
    return (label || lang).toLowerCase();
}
export const languageAtom = atom((get) => {
    const { codeSamples } = get(globalOptionsAtom);
    const languages = codeSamples.languages.map(({ lang, label }, index) => ({
        key: getLangKey({ lang, label }),
        lang,
        title: label || lang,
        order: index,
    }));
    const activeLanguage = get(appStore).language || languages[0]?.key;
    return {
        languages,
        activeLanguage: languages.find(({ key }) => key === activeLanguage)?.key || languages[0]?.key,
    };
}, (get, set, activeLanguage) => {
    const state = get(appStore);
    set(appStore, { ...state, language: activeLanguage });
});
//# sourceMappingURL=app.js.map