import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

import NavContextProvider from "./hooks/useNav";
import DataSetContextProvider from "./hooks/useDataSet";

const DevStyles = ({ webAppId }: { webAppId: string }) => {
    const [container, setContainer] = useState<HTMLDivElement | null>(null);

    useEffect(() => {
        if (!container) {
            return;
        }

        const sourceStylesContainer = document.head;

        const tagIdComment = `/* ${webAppId} */`;

        const moveStyles = () => {
            container.innerHTML = "";
            container.append(
                ...Array.from(sourceStylesContainer.children)
                    .filter((x) => x instanceof HTMLStyleElement)
                    .filter((x) => x.textContent?.includes(tagIdComment))
                    .map((x) => x.cloneNode(true)),
            );
        };

        const observer = new MutationObserver(moveStyles);
        observer.observe(sourceStylesContainer, {
            characterData: true,
            childList: true,
            subtree: true,
        });
        moveStyles();
        return () => {
            observer.disconnect();
        };
    }, [container, webAppId]);

    return <div ref={setContainer} />;
};

const webAppId = import.meta.env.VITE_WEB_APP_ID as string;
const container = document.getElementById(webAppId);
container?.attachShadow({ mode: "open" });
const shadowRoot = container?.shadowRoot;
const dataSets = container?.dataset;

const Root = () => {
    return (
        <NavContextProvider>
            <DataSetContextProvider dataSets={dataSets}>
                {import.meta.env.DEV && <DevStyles webAppId={webAppId} />}
                <App />
            </DataSetContextProvider>
        </NavContextProvider>
    );
};

if (shadowRoot) {
    const root = createRoot(shadowRoot);
    root.render(<Root />);
}
