import { HeadAssets } from '@frontend/components/layout/HeadAssets';
import { notFoundPageMeta } from '@frontend/content/not-found-page';
import { usePagePlugins } from '@frontend/hooks/use-page-plugins';
import { restoreBrandLogo, watchBrandLogo } from '@frontend/lib/brand-logo';
import { router } from '@inertiajs/react';
import { type ReactNode, useEffect, useRef } from 'react';

type ErrorShellProps = {
    children: ReactNode;
};

/**
 * Minimal shell for full-screen error pages (no site header/footer).
 */
function ErrorShell({ children }: ErrorShellProps) {
    const contentRef = useRef<HTMLDivElement>(null);

    usePagePlugins(contentRef);

    useEffect(() => {
        restoreBrandLogo();
        watchBrandLogo();
    }, []);

    useEffect(() => {
        return router.on('success', () => {
            restoreBrandLogo();

            const preloader = document.getElementById('preloader');

            if (preloader) {
                preloader.style.display = 'none';
            }
        });
    }, []);

    return (
        <>
            <HeadAssets
                title={notFoundPageMeta.browserTitle}
                metaKeywords={notFoundPageMeta.metaKeywords}
                metaDescription={notFoundPageMeta.metaDescription}
            />
            <div ref={contentRef}>{children}</div>
            <div className="scroll-top-percentage">
                <span id="scroll-value"></span>
            </div>
        </>
    );
}

export function errorPersistentLayout(page: ReactNode): React.JSX.Element {
    return <ErrorShell>{page}</ErrorShell>;
}
