import { router } from '@inertiajs/react';
import { useEffect } from 'react';
import type { ReactNode } from 'react';
import { FloatingContact } from '@/site/components/layout/floating-contact';
import { ScrollProgress } from '@/site/components/layout/scroll-progress';
import { SiteFooter } from '@/site/components/layout/site-footer';
import { SiteHeader } from '@/site/components/layout/site-header';
import { useT } from '@/site/i18n';

/**
 * Persistent shell of every public page: skip link, header, main landmark
 * and footer. It stays mounted across Inertia navigations, so the header
 * keeps its state while pages change underneath it.
 */
export default function SiteLayout({ children }: { children: ReactNode }) {
    const t = useT();

    // Tell the inline script in site.blade.php that the application is
    // running: scroll effects stay on. (Without this mark it switches them
    // off after a few seconds so that no content stays hidden.)
    useEffect(() => {
        document.documentElement.setAttribute('data-site-ready', '');
    }, []);

    // After a client-side navigation, move keyboard / screen-reader focus to
    // the new page's content, as a full page load would.
    useEffect(() => {
        let first = true;

        return router.on('navigate', () => {
            if (first) {
                first = false;

                return;
            }

            document.getElementById('content')?.focus({ preventScroll: true });
        });
    }, []);

    return (
        <>
            <a
                href="#content"
                className="bg-bone text-ink fixed start-4 top-4 z-100 -translate-y-24 rounded-full px-5 py-3 text-sm font-semibold transition-transform duration-300 focus:translate-y-0"
            >
                {t.common.skipToContent}
            </a>
            <SiteHeader />
            <ScrollProgress />
            <main id="content" tabIndex={-1}>
                {children}
            </main>
            <SiteFooter />
            <FloatingContact />
        </>
    );
}
