import { Link, usePage } from '@inertiajs/react';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { ChevronDown, Menu, X } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import AppLogoIcon from '@/components/app-logo-icon';
import RaceImage from '@/components/race-image';
import { SiteActionLink } from '@/components/site-action';
import type { Auth } from '@/types/auth';

const exploreSections = [
    {
        label: 'Events & competition',
        links: [
            { label: 'Events', href: '/events', detail: 'Race calendar' },
            { label: 'Results', href: '/results', detail: 'Race-day results' },
            {
                label: 'Rankings',
                href: '/rankings',
                detail: 'Season standings',
            },
        ],
    },
    {
        label: 'People',
        links: [
            {
                label: 'All people',
                href: '/people?type=all',
                detail: 'The paddock',
            },
            {
                label: 'Riders',
                href: '/people?type=rider',
                detail: 'Two wheels',
            },
            {
                label: 'Drivers',
                href: '/people?type=driver',
                detail: 'Four wheels',
            },
            {
                label: 'Teams',
                href: '/people?type=team',
                detail: 'Race garages',
            },
            { label: 'Organizers', href: '/organizers', detail: 'Event teams' },
        ],
    },
    {
        label: 'Coverage',
        links: [
            {
                label: 'Media',
                href: '/media',
                detail: 'Stories & race reports',
            },
            {
                label: 'Support',
                href: '/support',
                detail: 'We’re here to help',
            },
        ],
    },
];

const footerNavigation = [
    { label: 'Events', href: '/events' },
    { label: 'People', href: '/people' },
    { label: 'Results', href: '/results' },
    { label: 'Media', href: '/media' },
    { label: 'Rankings', href: '/rankings' },
];

const primaryNavigation = [
    { label: 'Events', href: '/events' },
    { label: 'People', href: '/people' },
    { label: 'Results', href: '/results' },
    { label: 'Media', href: '/media' },
    { label: 'Rankings', href: '/rankings' },
];

const footerImage =
    'https://images.unsplash.com/photo-1504215680853-026ed2a45def?auto=format&fit=crop&w=1800&q=85';

export default function SiteLayout({
    children,
    pageClassName,
}: {
    children: React.ReactNode;
    pageClassName?: string;
}) {
    const { props, url } = usePage<{ auth: Auth }>();
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const [isExploreOpen, setIsExploreOpen] = useState(false);
    const reduceMotion = useReducedMotion();
    const mobileMenuButtonRef = useRef<HTMLButtonElement>(null);
    const mobileMenuRef = useRef<HTMLDivElement>(null);
    const firstMobileLinkRef = useRef<HTMLAnchorElement>(null);
    const exploreRootRef = useRef<HTMLDivElement>(null);
    const exploreTriggerRef = useRef<HTMLButtonElement>(null);
    const firstExploreLinkRef = useRef<HTMLAnchorElement>(null);

    useEffect(() => {
        setIsMenuOpen(false);
        setIsExploreOpen(false);
    }, [url]);

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

        const closeExplore = (event: Event) => {
            if (
                event.type === 'keydown' &&
                (event as KeyboardEvent).key === 'Escape'
            ) {
                setIsExploreOpen(false);
                exploreTriggerRef.current?.focus();
                return;
            }

            if (
                event.type === 'pointerdown' &&
                exploreRootRef.current &&
                !exploreRootRef.current.contains(event.target as Node)
            ) {
                setIsExploreOpen(false);
            }
        };

        document.addEventListener('keydown', closeExplore);
        document.addEventListener('pointerdown', closeExplore);

        return () => {
            document.removeEventListener('keydown', closeExplore);
            document.removeEventListener('pointerdown', closeExplore);
        };
    }, [isExploreOpen]);

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

        const previousOverflow = document.body.style.overflow;
        document.body.style.overflow = 'hidden';

        const focusFrame = window.requestAnimationFrame(() => {
            firstMobileLinkRef.current?.focus();
        });

        const closeOnEscape = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                setIsMenuOpen(false);
                mobileMenuButtonRef.current?.focus();
                return;
            }

            if (event.key === 'Tab' && mobileMenuRef.current) {
                const focusableElements =
                    mobileMenuRef.current.querySelectorAll<HTMLElement>(
                        'a[href], button:not([disabled])',
                    );
                const firstElement = focusableElements[0];
                const lastElement =
                    focusableElements[focusableElements.length - 1];

                if (event.shiftKey && document.activeElement === firstElement) {
                    event.preventDefault();
                    lastElement?.focus();
                } else if (
                    !event.shiftKey &&
                    document.activeElement === lastElement
                ) {
                    event.preventDefault();
                    firstElement?.focus();
                }
            }
        };

        document.addEventListener('keydown', closeOnEscape);

        return () => {
            window.cancelAnimationFrame(focusFrame);
            document.body.style.overflow = previousOverflow;
            document.removeEventListener('keydown', closeOnEscape);
        };
    }, [isMenuOpen]);

    const isActive = (href: string) => {
        const currentPath = url.split('?')[0];
        const [targetPath, targetQuery] = href.split('?');

        if (targetPath === '/people' && !targetQuery) {
            return ['/people', '/riders', '/drivers', '/teams'].some(
                (path) =>
                    currentPath === path || currentPath.startsWith(`${path}/`),
            );
        }

        if (
            currentPath !== targetPath &&
            !currentPath.startsWith(`${targetPath}/`)
        ) {
            return false;
        }

        if (targetQuery) {
            const targetParams = new URLSearchParams(targetQuery);
            const currentParams = new URLSearchParams(url.split('?')[1] ?? '');
            const targetPeopleType =
                targetPath === '/people' ? targetParams.get('type') : null;

            if (
                targetPeopleType === 'rider' &&
                currentPath.startsWith('/riders/')
            ) {
                return true;
            }

            if (
                targetPeopleType === 'driver' &&
                currentPath.startsWith('/drivers/')
            ) {
                return true;
            }

            if (
                targetPeopleType === 'team' &&
                currentPath.startsWith('/teams/')
            ) {
                return true;
            }

            return [...targetParams].every(
                ([key, value]) => currentParams.get(key) === value,
            );
        }

        return true;
    };
    const isExploreActive = exploreSections.some((section) =>
        section.links.some((item) => isActive(item.href)),
    );

    return (
        <div className="public-site min-h-screen overflow-x-clip bg-[#f4f3ef] text-[#17191b]">
            <header className="sticky top-0 z-[70] border-b border-[#d9d5ca] bg-[#f4f2eb]/95 text-[#17191b] shadow-[0_8px_24px_-24px_rgba(17,21,22,.55)] backdrop-blur-xl">
                <div className="mx-auto flex h-[70px] max-w-7xl items-center justify-between gap-4 px-4 sm:px-5 lg:px-8">
                    <Link
                        href="/"
                        className="group flex shrink-0 items-center gap-2.5 rounded-lg focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#e6342b]"
                        aria-label="racing.lk home"
                    >
                        <span className="grid size-10 place-items-center rounded-xl bg-[#e6342b] text-white shadow-[inset_0_-3px_0_rgba(0,0,0,.15)] transition-transform duration-300 group-hover:scale-105 group-hover:-rotate-3">
                            <AppLogoIcon className="size-7" />
                        </span>
                        <span className="grid leading-none">
                            <span className="text-[21px] font-black tracking-[-.085em]">
                                racing
                                <span className="text-[#ef4035]">.lk</span>
                            </span>
                            <span className="mt-1 text-[8px] font-extrabold tracking-[.3em] text-[#777b76] uppercase">
                                Pit wall · LK
                            </span>
                        </span>
                    </Link>

                    <nav
                        aria-label="Primary navigation"
                        className="hidden items-center gap-0.5 xl:flex"
                    >
                        {primaryNavigation.map((item) => {
                            const active = isActive(item.href);

                            return (
                                <Link
                                    key={item.href}
                                    href={item.href}
                                    prefetch
                                    aria-current={active ? 'page' : undefined}
                                    className={`relative rounded-lg px-3 py-2.5 text-[12px] font-extrabold transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e6342b] ${active ? 'text-[#17191b]' : 'text-[#666b67] hover:text-[#c83221]'}`}
                                >
                                    {item.label}
                                    <span
                                        aria-hidden="true"
                                        className={`absolute inset-x-3 bottom-1 h-[2px] origin-left rounded-full bg-[#cf3829] transition-transform duration-300 ease-out ${active ? 'scale-x-100' : 'scale-x-0'}`}
                                    />
                                </Link>
                            );
                        })}
                    </nav>

                    <div
                        ref={exploreRootRef}
                        className="relative hidden xl:block"
                        onMouseEnter={() => setIsExploreOpen(true)}
                        onMouseLeave={() => setIsExploreOpen(false)}
                    >
                        <button
                            ref={exploreTriggerRef}
                            type="button"
                            aria-expanded={isExploreOpen}
                            aria-controls="explore-mega-menu"
                            onClick={() =>
                                setIsExploreOpen((isOpen) => !isOpen)
                            }
                            onKeyDown={(event) => {
                                if (event.key === 'ArrowDown') {
                                    event.preventDefault();
                                    setIsExploreOpen(true);
                                    window.requestAnimationFrame(() =>
                                        firstExploreLinkRef.current?.focus(),
                                    );
                                }
                            }}
                            className={`group relative inline-flex items-center gap-2 rounded-lg px-4 py-3 text-[13px] font-extrabold tracking-[-.01em] transition-colors hover:text-[#c83221] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e6342b] ${isExploreOpen || isExploreActive ? 'text-[#17191b]' : 'text-[#666b67]'}`}
                        >
                            Explore
                            <ChevronDown
                                aria-hidden="true"
                                size={15}
                                className={`transition-transform duration-200 ${isExploreOpen ? 'rotate-180' : ''}`}
                            />
                            <span
                                aria-hidden="true"
                                className={`absolute inset-x-4 bottom-1 h-[3px] origin-left rounded-full bg-[#cf3829] transition-transform duration-300 ease-out ${isExploreOpen || isExploreActive ? 'scale-x-100' : 'scale-x-0 group-hover:scale-x-100'}`}
                            />
                        </button>

                        <AnimatePresence initial={false}>
                            {isExploreOpen && (
                                <motion.div
                                    id="explore-mega-menu"
                                    initial={
                                        reduceMotion
                                            ? false
                                            : { opacity: 0, y: -8 }
                                    }
                                    animate={{ opacity: 1, y: 0 }}
                                    exit={
                                        reduceMotion
                                            ? undefined
                                            : { opacity: 0, y: -6 }
                                    }
                                    transition={
                                        reduceMotion
                                            ? { duration: 0 }
                                            : {
                                                  duration: 0.18,
                                                  ease: 'easeOut',
                                              }
                                    }
                                    className="absolute top-full left-1/2 z-[80] w-[min(90vw,900px)] -translate-x-1/2 rounded-2xl border border-[#ded9ce] bg-[#f8f6f0] p-5 text-[#17191b] shadow-[0_24px_70px_-25px_rgba(16,20,20,.42)] xl:p-6"
                                >
                                    <div className="mb-5 flex items-center justify-between border-b border-[#ddd8cd] pb-4">
                                        <div>
                                            <p className="text-[10px] font-black tracking-[.2em] text-[#c83221] uppercase">
                                                The racing grid
                                            </p>
                                            <p className="mt-1 text-sm font-semibold text-[#666b67]">
                                                Find your next stop in the
                                                paddock.
                                            </p>
                                        </div>
                                        <span className="hidden h-[3px] w-24 overflow-hidden rounded-full bg-[#e6e0d5] sm:block">
                                            <span className="block h-full w-1/3 rounded-full bg-[#e6342b]" />
                                        </span>
                                    </div>
                                    <nav
                                        aria-label="Explore racing.lk"
                                        className="grid gap-6 sm:grid-cols-[1fr_1.35fr_1fr]"
                                    >
                                        {exploreSections.map(
                                            (section, sectionIndex) => (
                                                <section key={section.label}>
                                                    <h2 className="mb-2 text-[10px] font-black tracking-[.15em] text-[#858981] uppercase">
                                                        {section.label}
                                                    </h2>
                                                    <div className="space-y-1">
                                                        {section.links.map(
                                                            (
                                                                item,
                                                                linkIndex,
                                                            ) => {
                                                                const active =
                                                                    isActive(
                                                                        item.href,
                                                                    );
                                                                const isFirstLink =
                                                                    sectionIndex ===
                                                                        0 &&
                                                                    linkIndex ===
                                                                        0;

                                                                return (
                                                                    <Link
                                                                        key={
                                                                            item.href
                                                                        }
                                                                        ref={
                                                                            isFirstLink
                                                                                ? firstExploreLinkRef
                                                                                : undefined
                                                                        }
                                                                        href={
                                                                            item.href
                                                                        }
                                                                        prefetch
                                                                        aria-current={
                                                                            active
                                                                                ? 'page'
                                                                                : undefined
                                                                        }
                                                                        onClick={() =>
                                                                            setIsExploreOpen(
                                                                                false,
                                                                            )
                                                                        }
                                                                        className={`group block rounded-lg border-l-2 px-3 py-2.5 transition-colors focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[#e6342b] ${active ? 'border-[#e6342b] bg-white text-[#17191b]' : 'border-transparent hover:border-[#e6342b] hover:bg-white/75'}`}
                                                                    >
                                                                        <span className="block text-sm leading-tight font-extrabold">
                                                                            {
                                                                                item.label
                                                                            }
                                                                        </span>
                                                                        <span className="mt-1 block text-xs text-[#747a74]">
                                                                            {
                                                                                item.detail
                                                                            }
                                                                        </span>
                                                                    </Link>
                                                                );
                                                            },
                                                        )}
                                                    </div>
                                                </section>
                                            ),
                                        )}
                                    </nav>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </div>

                    <div className="flex shrink-0 items-center gap-2">
                        {props.auth.user ? (
                            <div className="hidden items-center gap-2 sm:flex">
                                <Link
                                    href="/orders"
                                    className="rounded-lg px-3 py-2.5 text-xs font-bold text-[#555b57] transition hover:text-[#c83221] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e6342b]"
                                >
                                    My passes
                                </Link>
                                <SiteActionLink
                                    href="/dashboard"
                                    variant="outline"
                                    size="sm"
                                    className="border-[#17191b]/20 text-[#17191b] hover:border-[#17191b] hover:bg-[#17191b] hover:text-white"
                                >
                                    Dashboard
                                </SiteActionLink>
                            </div>
                        ) : (
                            <>
                                <Link
                                    href="/login"
                                    className="hidden rounded-lg px-3 py-2.5 text-xs font-bold text-[#555b57] transition hover:text-[#c83221] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e6342b] sm:block"
                                >
                                    Log in
                                </Link>
                                <SiteActionLink
                                    href="/register"
                                    variant="primary"
                                    size="sm"
                                    className="hidden rounded-lg sm:inline-flex"
                                >
                                    Join racing.lk
                                </SiteActionLink>
                            </>
                        )}
                        <button
                            ref={mobileMenuButtonRef}
                            type="button"
                            onClick={() => setIsMenuOpen((open) => !open)}
                            className={`grid size-10 place-items-center rounded-xl border transition-all focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e6342b] xl:hidden ${isMenuOpen ? 'border-[#17191b] bg-[#17191b] text-white' : 'border-[#17191b]/15 bg-white/60 text-[#17191b] hover:border-[#e6342b]/50 hover:text-[#c83221]'}`}
                            aria-label={
                                isMenuOpen
                                    ? 'Close navigation'
                                    : 'Open navigation'
                            }
                            aria-expanded={isMenuOpen}
                            aria-controls="mobile-navigation"
                        >
                            <AnimatePresence mode="wait" initial={false}>
                                <motion.span
                                    key={isMenuOpen ? 'close' : 'menu'}
                                    initial={
                                        reduceMotion
                                            ? false
                                            : {
                                                  opacity: 0,
                                                  rotate: -30,
                                                  scale: 0.8,
                                              }
                                    }
                                    animate={{
                                        opacity: 1,
                                        rotate: 0,
                                        scale: 1,
                                    }}
                                    exit={
                                        reduceMotion
                                            ? undefined
                                            : {
                                                  opacity: 0,
                                                  rotate: 30,
                                                  scale: 0.8,
                                              }
                                    }
                                    transition={{
                                        duration: reduceMotion ? 0 : 0.16,
                                    }}
                                >
                                    {isMenuOpen ? (
                                        <X size={19} />
                                    ) : (
                                        <Menu size={19} />
                                    )}
                                </motion.span>
                            </AnimatePresence>
                        </button>
                    </div>
                </div>
            </header>
            <AnimatePresence initial={false}>
                {isMenuOpen && (
                    <motion.div
                        ref={mobileMenuRef}
                        id="mobile-navigation"
                        role="dialog"
                        aria-modal="true"
                        aria-label="Site navigation"
                        initial={
                            reduceMotion
                                ? false
                                : {
                                      opacity: 0,
                                      y: '-3%',
                                      clipPath: 'inset(0 0 100% 0)',
                                  }
                        }
                        animate={{
                            opacity: 1,
                            y: '0%',
                            clipPath: 'inset(0 0 0% 0)',
                        }}
                        exit={
                            reduceMotion
                                ? undefined
                                : {
                                      opacity: 0,
                                      y: '-2%',
                                      clipPath: 'inset(0 0 100% 0)',
                                  }
                        }
                        transition={
                            reduceMotion
                                ? { duration: 0 }
                                : { duration: 0.32, ease: [0.22, 1, 0.36, 1] }
                        }
                        className="fixed inset-x-0 top-[70px] z-[60] flex h-[calc(100dvh-70px)] flex-col overflow-y-auto overscroll-contain bg-[#111516] text-white xl:hidden"
                    >
                        <RaceImage
                            src={footerImage}
                            fallbackSrc={footerImage}
                            alt=""
                            className="pointer-events-none absolute inset-0 -z-20 size-full object-cover opacity-[.16]"
                        />
                        <div className="pointer-events-none absolute inset-0 -z-10 bg-[linear-gradient(115deg,rgba(12,16,17,.98)_0%,rgba(12,16,17,.9)_55%,rgba(12,16,17,.8)_100%)]" />

                        <div className="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col px-6 pt-7 pb-5 sm:px-10 sm:pt-9">
                            <div className="mb-5 flex items-center justify-between text-[10px] font-black tracking-[.2em] text-white/55 uppercase">
                                <span>Race control · Main menu</span>
                                <span className="font-mono text-[#f6c84f]">
                                    LK / 01
                                </span>
                            </div>

                            <nav
                                aria-label="Mobile navigation"
                                className="flex-1 pb-8"
                            >
                                {exploreSections.map(
                                    (section, sectionIndex) => (
                                        <section
                                            key={section.label}
                                            className="mb-6"
                                        >
                                            <motion.h2
                                                initial={
                                                    reduceMotion
                                                        ? false
                                                        : { opacity: 0, x: -12 }
                                                }
                                                animate={{ opacity: 1, x: 0 }}
                                                transition={{
                                                    duration: reduceMotion
                                                        ? 0
                                                        : 0.2,
                                                    delay: reduceMotion
                                                        ? 0
                                                        : 0.04 +
                                                          sectionIndex * 0.05,
                                                }}
                                                className="mb-2 flex items-center gap-3 text-[10px] font-black tracking-[.2em] text-[#f6c84f] uppercase"
                                            >
                                                <span className="h-px w-6 bg-[#e8422b]" />
                                                {section.label}
                                            </motion.h2>
                                            <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                                                {section.links.map(
                                                    (item, linkIndex) => {
                                                        const active = isActive(
                                                            item.href,
                                                        );
                                                        const index =
                                                            exploreSections
                                                                .slice(
                                                                    0,
                                                                    sectionIndex,
                                                                )
                                                                .reduce(
                                                                    (
                                                                        total,
                                                                        group,
                                                                    ) =>
                                                                        total +
                                                                        group
                                                                            .links
                                                                            .length,
                                                                    0,
                                                                ) + linkIndex;

                                                        return (
                                                            <motion.div
                                                                key={item.href}
                                                                initial={
                                                                    reduceMotion
                                                                        ? false
                                                                        : {
                                                                              opacity: 0,
                                                                              y: 8,
                                                                          }
                                                                }
                                                                animate={{
                                                                    opacity: 1,
                                                                    y: 0,
                                                                }}
                                                                transition={{
                                                                    duration:
                                                                        reduceMotion
                                                                            ? 0
                                                                            : 0.2,
                                                                    delay: reduceMotion
                                                                        ? 0
                                                                        : 0.07 +
                                                                          index *
                                                                              0.025,
                                                                    ease: 'easeOut',
                                                                }}
                                                            >
                                                                <Link
                                                                    ref={
                                                                        index ===
                                                                        0
                                                                            ? firstMobileLinkRef
                                                                            : undefined
                                                                    }
                                                                    href={
                                                                        item.href
                                                                    }
                                                                    prefetch
                                                                    aria-current={
                                                                        active
                                                                            ? 'page'
                                                                            : undefined
                                                                    }
                                                                    onClick={() =>
                                                                        setIsMenuOpen(
                                                                            false,
                                                                        )
                                                                    }
                                                                    className={`group flex min-h-[68px] touch-manipulation flex-col justify-center rounded-lg border px-3 py-2.5 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#f6c84f] active:scale-[.98] ${active ? 'border-[#e8422b]/80 bg-white/10 text-white' : 'border-white/10 bg-black/15 text-white/75 active:border-[#f6c84f]/60 active:text-white'}`}
                                                                >
                                                                    <span className="text-base leading-tight font-extrabold tracking-tight">
                                                                        {
                                                                            item.label
                                                                        }
                                                                    </span>
                                                                    <span className="mt-1 text-[10px] text-white/45">
                                                                        {
                                                                            item.detail
                                                                        }
                                                                    </span>
                                                                </Link>
                                                            </motion.div>
                                                        );
                                                    },
                                                )}
                                            </div>
                                        </section>
                                    ),
                                )}
                            </nav>
                        </div>

                        <footer className="border-t border-white/10 bg-[#f3f0e8] px-5 pt-3 pb-[max(env(safe-area-inset-bottom),.75rem)] text-[#15191a] shadow-[0_-16px_40px_rgba(0,0,0,.22)] sm:px-10">
                            <div className="mx-auto flex w-full max-w-3xl items-center justify-between gap-3">
                                <div className="min-w-0">
                                    <p className="text-[9px] font-black tracking-[.17em] text-[#777b76] uppercase">
                                        {props.auth.user
                                            ? 'You’re in the paddock'
                                            : 'Find your place on the grid'}
                                    </p>
                                    <p className="mt-1 truncate text-sm font-black tracking-tight">
                                        {props.auth.user
                                            ? props.auth.user.name
                                            : 'racing.lk'}
                                    </p>
                                </div>
                                <div className="flex shrink-0 items-center gap-2">
                                    {!props.auth.user && (
                                        <Link
                                            href="/login"
                                            onClick={() => setIsMenuOpen(false)}
                                            className="inline-flex min-h-11 items-center rounded-lg px-3 text-xs font-bold text-[#525954] transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#cf3829] active:scale-[.97]"
                                        >
                                            Log in
                                        </Link>
                                    )}
                                    {props.auth.user && (
                                        <Link
                                            href="/orders"
                                            onClick={() => setIsMenuOpen(false)}
                                            className="inline-flex min-h-11 items-center rounded-lg px-3 text-xs font-bold text-[#525954] transition focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#cf3829] active:scale-[.97]"
                                        >
                                            My passes
                                        </Link>
                                    )}
                                    <SiteActionLink
                                        href={
                                            props.auth.user
                                                ? '/dashboard'
                                                : '/register'
                                        }
                                        onClick={() => setIsMenuOpen(false)}
                                        variant="primary"
                                        size="sm"
                                        className="min-h-11 rounded-lg px-4 active:scale-[.97]"
                                    >
                                        {props.auth.user
                                            ? 'Dashboard'
                                            : 'Join the grid'}
                                    </SiteActionLink>
                                </div>
                            </div>
                        </footer>
                    </motion.div>
                )}
            </AnimatePresence>
            <main className={pageClassName}>{children}</main>
            <footer className="bg-[#111315] text-white">
                <div className="relative isolate overflow-hidden border-b border-white/10 bg-[#191b1d]">
                    <RaceImage
                        src={footerImage}
                        fallbackSrc={footerImage}
                        alt="Motorsport image"
                        className="absolute inset-0 -z-20 size-full object-cover opacity-35"
                    />
                    <div className="absolute inset-0 -z-10 bg-gradient-to-r from-[#111315] via-[#111315]/90 to-[#111315]/45" />
                    <div className="mx-auto flex max-w-7xl flex-col gap-7 px-5 py-14 sm:flex-row sm:items-end sm:justify-between lg:px-8">
                        <div>
                            <p className="text-xs font-black tracking-[.26em] text-[#ff5549] uppercase">
                                Next stop: the starting line
                            </p>
                            <h2 className="mt-3 max-w-2xl text-4xl leading-[.95] font-black tracking-[-.075em] sm:text-5xl">
                                Find your place in the action.
                            </h2>
                        </div>
                        <SiteActionLink
                            href="/events"
                            variant="primary"
                            size="lg"
                        >
                            Explore events
                        </SiteActionLink>
                    </div>
                </div>
                <div className="mx-auto grid max-w-7xl gap-10 px-5 py-12 sm:grid-cols-2 lg:grid-cols-[1.4fr_1fr_1fr] lg:px-8">
                    <div>
                        <Link
                            href="/"
                            className="inline-flex items-center gap-3 text-2xl font-black tracking-[-.08em]"
                        >
                            <span className="grid size-10 place-items-center rounded-xl bg-[#e6342b]">
                                <AppLogoIcon className="size-6" />
                            </span>
                            racing
                            <span className="-ml-3 text-[#ef4035]">.lk</span>
                        </Link>
                        <p className="mt-5 max-w-xs text-sm leading-6 text-white/55">
                            Race weekends, results and the people who move Sri
                            Lankan motorsport forward.
                        </p>
                    </div>
                    <nav aria-label="Explore racing.lk">
                        <p className="text-[10px] font-black tracking-[.23em] text-white/40 uppercase">
                            Explore
                        </p>
                        <div className="mt-5 grid grid-cols-2 gap-x-5 gap-y-3">
                            {footerNavigation.map((item) => (
                                <Link
                                    key={item.href}
                                    href={item.href}
                                    className="text-sm font-semibold text-white/65 transition hover:text-white"
                                >
                                    {item.label}
                                </Link>
                            ))}
                            <Link
                                href="/organizers"
                                className="text-sm font-semibold text-white/65 transition hover:text-white"
                            >
                                Organizers
                            </Link>
                        </div>
                    </nav>
                    <nav aria-label="Help and policies">
                        <p className="text-[10px] font-black tracking-[.23em] text-white/40 uppercase">
                            Information
                        </p>
                        <div className="mt-5 grid gap-3">
                            {[
                                ['Support', '/support'],
                                ['Ticket policy', '/policies/ticket-policy'],
                                ['Terms', '/policies/terms'],
                                ['Privacy', '/policies/privacy'],
                            ].map(([label, href]) => (
                                <Link
                                    key={href}
                                    href={href}
                                    className="text-sm font-semibold text-white/65 transition hover:text-white"
                                >
                                    {label}
                                </Link>
                            ))}
                        </div>
                    </nav>
                </div>
                <div className="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 border-t border-white/10 px-5 py-5 text-xs text-white/40 lg:px-8">
                    <span>© {new Date().getFullYear()} racing.lk</span>
                    <span>
                        Preview photography via{' '}
                        <a
                            href="https://unsplash.com"
                            target="_blank"
                            rel="noreferrer"
                            className="underline underline-offset-4 hover:text-white"
                        >
                            Unsplash
                        </a>
                    </span>
                </div>
            </footer>
        </div>
    );
}
