import {createEmotionCacheRtl} from "@/core/utils/createEmotionCache";
import theme from "@/core/utils/theme";
import createEmotionServer from "@emotion/server/create-instance";
import Document, {Head, Html, Main, NextScript} from "next/document";

export default function MyDocument(props) {
    const {emotionStyleTags} = props;

    return (
        <Html>
            <Head>
                <meta name="theme-color" content={theme.palette.primary.main}/>
                <meta name="emotion-insertion-point" content=""/>
                <link rel="shortcut icon" href="/icons/favicon.png"/>
                <link rel="manifest" href="/manifest.json"/>
                {emotionStyleTags}
            </Head>
            <body>
            <Main/>
            <NextScript/>
            </body>
        </Html>
    );
}

MyDocument.getInitialProps = async (ctx) => {
    const originalRenderPage = ctx.renderPage;
    let cache;
    switch (ctx.locale) {
        case "fa":
            cache = createEmotionCacheRtl();
            break;
    }

    const {extractCriticalToChunks} = createEmotionServer(cache);

    ctx.renderPage = () =>
        originalRenderPage({
            enhanceApp: (App) =>
                function EnhanceApp(props) {
                    return <App emotionCache={cache} {...props} />;
                },
        });

    const initialProps = await Document.getInitialProps(ctx);

    const emotionStyles = extractCriticalToChunks(initialProps.html);
    const emotionStyleTags = emotionStyles.styles.map((style) => (
        <style
            data-emotion={`${style.key} ${style.ids.join(" ")}`}
            key={style.key}
            // eslint-disable-next-line react/no-danger
            dangerouslySetInnerHTML={{__html: style.css}}
        />
    ));

    return {
        ...initialProps,
        emotionStyleTags,
    };
};
