import { Box } from "@mui/material";
import { startTransition, useEffect, useRef, useState } from "react";
import QuizAnswerer from "./QuizAnswerer";
import { QuizIdContext } from "./contexts/QuizIdContext";
import { RootContainerWidthContext } from "./contexts/RootContainerWidthContext";


interface Props {
    quizId: string;
}

export default function WidgetApp({ quizId }: Props) {
    const [rootContainerSize, setRootContainerSize] = useState<number>(() => window.innerWidth);
    const rootContainerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleWindowResize = () => {
            startTransition(() => {
                if (rootContainerRef.current) setRootContainerSize(rootContainerRef.current.clientWidth);
            });
        };
        window.addEventListener("resize", handleWindowResize);

        return () => {
            window.removeEventListener("resize", handleWindowResize);
        };
    }, []);

    return (
        <RootContainerWidthContext.Provider value={rootContainerSize}>
            <QuizIdContext.Provider value={quizId}>
                <Box
                    ref={rootContainerRef}
                    sx={{
                        width: "100%",
                        height: "100%",
                    }}
                >
                    <QuizAnswerer />
                </Box>
            </QuizIdContext.Provider>
        </RootContainerWidthContext.Provider>
    );
}
