import { SafeDictionary } from "@insite/client-framework/Common/Types";
import { setLabels } from "@insite/shell/TS";
import * as React from "react";
import { useEffect, useState } from "react";
import { fetch } from "@insite/client-framework/ServerSideRendering";

export const CmsTranslationLoader: React.FC<React.PropsWithChildren> = ({ children }) => {
    const [loadedLabels, setLoadedLabels] = useState(false);

    useEffect(() => {
        fetch(`/admin/translations`)
            .then(res => res.json())
            .then(data => {
                const labelsByKey: SafeDictionary<string> = {};
                for (const label of data.labels) {
                    labelsByKey[label.label] = label.localizedLabel;
                }
                setLabels(labelsByKey, data.isDebugModeEnabled, data.languageCode);
                setLoadedLabels(true);
            });
    }, []);

    if (!loadedLabels) {
        return <></>;
    }

    return <>{children}</>;
};
