import { Link, usePage } from '@inertiajs/react';
import { Menu } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import type { MouseEvent } from 'react';
import LandingLogo from '@/components/landing/landing-logo';
import {
    Sheet,
    SheetClose,
    SheetContent,
    SheetDescription,
    SheetTitle,
    SheetTrigger,
} from '@/components/ui/sheet';
import { cn } from '@/lib/utils';
import { dashboard, home, login, register } from '@/routes';

const sectionLinks = [
    { label: 'Products', anchor: 'products' },
    { label: 'How it works', anchor: 'how' },
    { label: 'Stories', anchor: 'testimonials' },
    { label: 'FAQ', anchor: 'faq' },
] as const;

const primaryButtonClasses =
    'inline-flex items-center justify-center rounded-full bg-brand px-5 py-2.5 text-sm font-semibold text-white shadow-landing-sm transition-colors hover:bg-brand-hover focus-visible:ring-2 focus-visible:ring-highlight focus-visible:ring-offset-2 focus-visible:outline-none';

const secondaryButtonClasses =
    'inline-flex items-center justify-center rounded-full px-4 py-2.5 text-sm font-semibold text-ink-700 transition-colors hover:text-brand focus-visible:ring-2 focus-visible:ring-highlight focus-visible:ring-offset-2 focus-visible:outline-none';

const headerPrimaryButtonClasses =
    'inline-flex items-center justify-center rounded-full bg-highlight px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-highlight-dark focus-visible:ring-2 focus-visible:ring-highlight focus-visible:ring-offset-2 focus-visible:ring-offset-brand-dark focus-visible:outline-none';

const headerSecondaryButtonClasses =
    'inline-flex items-center justify-center rounded-full px-4 py-2.5 text-sm font-semibold text-white/80 transition-colors hover:text-white focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none';

export default function LandingHeader() {
    const { props, component } = usePage();
    const { auth } = props;
    const [hasScrolled, setHasScrolled] = useState(false);
    const [isMenuOpen, setIsMenuOpen] = useState(false);
    const pendingAnchor = useRef<string | null>(null);

    const isOnHomePage = component === 'welcome';

    const sectionHref = (anchor: string): string =>
        isOnHomePage ? `#${anchor}` : `${home.url()}#${anchor}`;

    /**
     * The open menu locks page scrolling, so an in-page link clicked inside
     * it would jump before the lock is released. Close the menu first and
     * scroll once it has finished closing.
     */
    const handleMenuLinkClick = (
        event: MouseEvent<HTMLAnchorElement>,
        anchor: string,
    ) => {
        if (!isOnHomePage) {
            return;
        }

        event.preventDefault();
        pendingAnchor.current = anchor;
        setIsMenuOpen(false);
    };

    const scrollToPendingAnchor = (event: Event) => {
        const anchor = pendingAnchor.current;

        if (anchor === null) {
            return;
        }

        event.preventDefault();
        pendingAnchor.current = null;

        window.setTimeout(() => {
            document
                .getElementById(anchor)
                ?.scrollIntoView({ behavior: 'smooth', block: 'start' });
            window.history.replaceState(null, '', `#${anchor}`);
        }, 0);
    };

    useEffect(() => {
        const updateScrolledState = () => setHasScrolled(window.scrollY > 8);

        updateScrolledState();
        window.addEventListener('scroll', updateScrolledState, {
            passive: true,
        });

        return () => window.removeEventListener('scroll', updateScrolledState);
    }, []);

    return (
        <header
            className={cn(
                'sticky top-0 z-40 border-b transition-[background-color,border-color,box-shadow] duration-300',
                hasScrolled
                    ? 'border-white/10 bg-brand-dark/95 shadow-landing backdrop-blur-md'
                    : 'border-white/5 bg-brand-dark',
            )}
        >
            <div className="mx-auto flex h-18 max-w-6xl items-center justify-between gap-6 px-4 sm:px-6 lg:px-8">
                <LandingLogo tone="light" />

                <nav
                    aria-label="Main"
                    className="hidden items-center gap-8 lg:flex"
                >
                    {sectionLinks.map((link) => (
                        <a
                            key={link.anchor}
                            href={sectionHref(link.anchor)}
                            className="text-sm font-medium text-white/75 transition-colors hover:text-white"
                        >
                            {link.label}
                        </a>
                    ))}
                </nav>

                <div className="hidden items-center gap-2 lg:flex">
                    {auth.user ? (
                        <Link
                            href={dashboard()}
                            className={headerPrimaryButtonClasses}
                        >
                            Dashboard
                        </Link>
                    ) : (
                        <>
                            <Link
                                href={login()}
                                className={headerSecondaryButtonClasses}
                            >
                                Sign in
                            </Link>
                            <Link
                                href={register()}
                                className={headerPrimaryButtonClasses}
                            >
                                Open an account
                            </Link>
                        </>
                    )}
                </div>

                <Sheet open={isMenuOpen} onOpenChange={setIsMenuOpen}>
                    <SheetTrigger
                        className="inline-flex size-10 items-center justify-center rounded-full text-white transition-colors hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-highlight focus-visible:outline-none lg:hidden"
                        aria-label="Open menu"
                    >
                        <Menu className="size-5" />
                    </SheetTrigger>

                    <SheetContent
                        side="right"
                        onCloseAutoFocus={scrollToPendingAnchor}
                        className="light-scope w-[85%] gap-0 border-surface-200 bg-canvas font-body text-ink scheme-light"
                    >
                        <div className="border-b border-surface-200 px-6 py-5">
                            <SheetTitle className="font-display text-lg font-semibold text-ink">
                                Menu
                            </SheetTitle>
                            <SheetDescription className="sr-only">
                                Site navigation and account links
                            </SheetDescription>
                        </div>

                        <nav
                            aria-label="Mobile"
                            className="flex flex-col gap-1 px-3 py-4"
                        >
                            {sectionLinks.map((link) => (
                                <SheetClose asChild key={link.anchor}>
                                    <a
                                        href={sectionHref(link.anchor)}
                                        onClick={(event) =>
                                            handleMenuLinkClick(
                                                event,
                                                link.anchor,
                                            )
                                        }
                                        className="rounded-landing px-3 py-3 text-base font-medium text-ink-700 transition-colors hover:bg-surface-100 hover:text-brand"
                                    >
                                        {link.label}
                                    </a>
                                </SheetClose>
                            ))}
                        </nav>

                        <div className="mt-auto flex flex-col gap-2 border-t border-surface-200 p-6">
                            {auth.user ? (
                                <Link
                                    href={dashboard()}
                                    className={primaryButtonClasses}
                                >
                                    Dashboard
                                </Link>
                            ) : (
                                <>
                                    <Link
                                        href={register()}
                                        className={primaryButtonClasses}
                                    >
                                        Open an account
                                    </Link>
                                    <Link
                                        href={login()}
                                        className={cn(
                                            secondaryButtonClasses,
                                            'border border-surface-200 bg-white',
                                        )}
                                    >
                                        Sign in
                                    </Link>
                                </>
                            )}
                        </div>
                    </SheetContent>
                </Sheet>
            </div>
        </header>
    );
}
