import { setupPixivnViteData } from "@drincs/pixi-vn/vite-listener";
import { ComponentType, lazy, Suspense } from "react";
import { ErrorBoundary, FallbackProps } from "react-error-boundary";
import { useI18n } from "./i18n";
import LoadingScreen from "./screens/LoadingScreen";
import { defineAssets } from "./utils/assets-utility";
import { initializeIndexedDB } from "./utils/indexedDB-utility";
import { importAllInkLabels } from "./utils/ink-utility";
import { initializeNQTR } from "./utils/nqtr-utility";

const Home = lazy(async () => {
    await Promise.all([import("./values"), import("./labels")]);
    await Promise.all([initializeIndexedDB(), defineAssets(), useI18n(), importAllInkLabels(), initializeNQTR()]);
    setupPixivnViteData();
    return import("./Home");
});

const ErrorFallback: ComponentType<FallbackProps> = ({ error, resetErrorBoundary }) => {
    return (
        <div
            role='alert'
            style={{
                pointerEvents: "auto",
                backgroundColor: "black",
            }}
        >
            <h2
                style={{
                    color: "red",
                    fontSize: "2rem",
                    textAlign: "center",
                    marginTop: "1rem",
                }}
            >
                Something went wrong
            </h2>
            <p
                style={{
                    color: "white",
                    fontSize: "1.5rem",
                    textAlign: "center",
                    marginTop: "1rem",
                }}
            >
                {(error as Error).message}
            </p>
            <div
                style={{
                    display: "flex",
                    justifyContent: "center",
                    marginTop: "1rem",
                    paddingBottom: "1rem",
                }}
            >
                <button
                    style={{
                        padding: "0.5rem 1rem",
                        backgroundColor: "white",
                        borderRadius: "0.5rem",
                    }}
                    onClick={resetErrorBoundary}
                >
                    Try again
                </button>
            </div>
        </div>
    );
};

export default function App() {
    return (
        <ErrorBoundary FallbackComponent={ErrorFallback}>
            <Suspense fallback={<LoadingScreen />}>
                <Home />
            </Suspense>
        </ErrorBoundary>
    );
}
