"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createEmotionSsrAdvancedApproach = void 0;
/* eslint-disable @typescript-eslint/ban-types */
const React = __importStar(require("react"));
const react_1 = require("@emotion/react");
const cache_1 = __importDefault(require("@emotion/cache"));
const assert_1 = require("../tools/assert");
/**
 * @see <https://docs.tss-react.dev/ssr/next>
 * This utility implements https://emotion.sh/docs/ssr#advanced-approach
 * */
function createEmotionSsrAdvancedApproach(
/** This is the options passed to createCache() from 'import createCache from "@emotion/cache"' */
options, 
/**
 * By default <CacheProvider /> from 'import { CacheProvider } from "@emotion/react"'
 *
 * NOTE: The actual expected type is `React.Provider<EmotionCache>` but we use `Function` because
 * to make it work regardless of if you are using React 18 or React 19 type def.
 */
CacheProvider = react_1.CacheProvider) {
    const { prepend } = options, optionsWithoutPrependProp = __rest(options, ["prepend"]);
    const appPropName = `${options.key}EmotionCache`;
    const insertionPointId = `${options.key}-emotion-cache-insertion-point`;
    function augmentDocumentWithEmotionCache(Document) {
        var _a;
        let super_getInitialProps = (_a = Document.getInitialProps) === null || _a === void 0 ? void 0 : _a.bind(Document);
        if (super_getInitialProps === undefined) {
            Promise.resolve().then(() => __importStar(require("next/document"))).then(({ default: DefaultDocument }) => (super_getInitialProps =
                DefaultDocument.getInitialProps.bind(DefaultDocument)));
        }
        const createEmotionServerOrPr = Promise.resolve().then(() => __importStar(require("@emotion/server/create-instance"))).then(({ default: createEmotionServer }) => createEmotionServer);
        Document.getInitialProps = (documentContext) => __awaiter(this, void 0, void 0, function* () {
            const cache = (0, cache_1.default)(optionsWithoutPrependProp);
            const createEmotionServer = createEmotionServerOrPr instanceof Promise
                ? yield createEmotionServerOrPr
                : createEmotionServerOrPr;
            const emotionServer = createEmotionServer(cache);
            const originalRenderPage = documentContext.renderPage;
            documentContext.renderPage = (_a) => {
                var { enhanceApp } = _a, params = __rest(_a, ["enhanceApp"]);
                return originalRenderPage(Object.assign(Object.assign({}, params), { "enhanceApp": (App) => {
                        var _a;
                        const EnhancedApp = (_a = enhanceApp === null || enhanceApp === void 0 ? void 0 : enhanceApp(App)) !== null && _a !== void 0 ? _a : App;
                        return function EnhanceApp(props) {
                            return (React.createElement(EnhancedApp, Object.assign({}, Object.assign(Object.assign({}, props), { [appPropName]: cache }))));
                        };
                    } }));
            };
            (0, assert_1.assert)(super_getInitialProps !== undefined, "Default document not yet loaded. Please submit an issue to the tss-react repo");
            const initialProps = yield super_getInitialProps(documentContext);
            const emotionStyles = [
                React.createElement("style", { id: insertionPointId, key: insertionPointId }),
                ...emotionServer
                    .extractCriticalToChunks(initialProps.html)
                    .styles.filter(({ css }) => css !== "")
                    .map(style => (React.createElement("style", { nonce: options.nonce, "data-emotion": `${style.key} ${style.ids.join(" ")}`, key: style.key, dangerouslySetInnerHTML: { "__html": style.css } })))
            ];
            const otherStyles = React.Children.toArray(initialProps.styles);
            return Object.assign(Object.assign({}, initialProps), { "styles": prepend
                    ? [...emotionStyles, ...otherStyles]
                    : [...otherStyles, ...emotionStyles] });
        });
    }
    function withAppEmotionCache(App) {
        const createClientSideCache = (() => {
            let cache = undefined;
            return () => {
                if (cache !== undefined) {
                    return cache;
                }
                return (cache = (0, cache_1.default)(Object.assign(Object.assign({}, optionsWithoutPrependProp), { "insertionPoint": (() => {
                        // NOTE: Under normal circumstances we are on the client.
                        // It might not be the case though, see: https://github.com/garronej/tss-react/issues/124
                        const isBrowser = typeof document === "object" &&
                            typeof (document === null || document === void 0 ? void 0 : document.getElementById) === "function";
                        if (!isBrowser) {
                            return undefined;
                        }
                        const htmlElement = document.getElementById(insertionPointId);
                        (0, assert_1.assert)(htmlElement !== null);
                        return htmlElement;
                    })() })));
            };
        })();
        function AppWithEmotionCache(props) {
            const _a = props, _b = appPropName, cache = _a[_b], rest = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
            return (React.createElement(CacheProvider, { value: cache !== null && cache !== void 0 ? cache : createClientSideCache() },
                React.createElement(App, Object.assign({}, rest))));
        }
        Object.keys(App).forEach(staticMethod => (AppWithEmotionCache[staticMethod] = App[staticMethod]));
        AppWithEmotionCache.displayName = AppWithEmotionCache.name;
        return AppWithEmotionCache;
    }
    return { withAppEmotionCache, augmentDocumentWithEmotionCache };
}
exports.createEmotionSsrAdvancedApproach = createEmotionSsrAdvancedApproach;
