'use client';

import { ArrowRight, Menu, X } from 'lucide-react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';

import { Logo } from '@/components/layout/logo';
import { marketingLinks, useActiveMarketingLink } from '@/components/layout/marketing-nav';
import { buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';

const subscribe = () => () => undefined;
const ease = [0.2, 0.8, 0.2, 1] as const;

export function MobileNav() {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();
  const [lastPath, setLastPath] = useState(pathname);
  const active = useActiveMarketingLink();
  const reduce = useReducedMotion();
  const mounted = useSyncExternalStore(subscribe, () => true, () => false);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);

  // Close the sheet whenever the route changes.
  if (pathname !== lastPath) {
    setLastPath(pathname);
    setOpen(false);
  }

  useEffect(() => {
    if (!open) return undefined;
    const trigger = triggerRef.current;
    const previous = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    closeRef.current?.focus();

    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setOpen(false);
        return;
      }
      if (event.key !== 'Tab' || panelRef.current === null) return;
      const focusable = panelRef.current.querySelectorAll<HTMLElement>('a[href], button:not([disabled])');
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (first === undefined || last === undefined) return;
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = previous;
      window.removeEventListener('keydown', onKey);
      trigger?.focus();
    };
  }, [open]);

  const close = () => setOpen(false);

  return (
    <>
      <button
        ref={triggerRef}
        type="button"
        className="grid h-11 w-11 place-items-center rounded-md border border-border bg-surface/80 text-foreground transition-colors hover:bg-surface-muted"
        aria-expanded={open}
        aria-controls="mobile-navigation"
        aria-haspopup="dialog"
        onClick={() => setOpen(true)}
      >
        <Menu className="h-5 w-5" aria-hidden="true" />
        <span className="sr-only">Open menu</span>
      </button>
      {mounted
        ? createPortal(
            <AnimatePresence>
              {open ? (
                <div className="fixed inset-0 z-50 lg:hidden">
                  <motion.div
                    aria-hidden="true"
                    className="absolute inset-0 bg-foreground/40 backdrop-blur-[4px]"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    transition={{ duration: 0.18 }}
                    onClick={close}
                  />
                  <motion.div
                    ref={panelRef}
                    id="mobile-navigation"
                    role="dialog"
                    aria-modal="true"
                    aria-label="Menu"
                    className="absolute inset-y-0 right-0 flex w-[min(86vw,380px)] flex-col border-l border-border bg-surface px-6 pb-6 pt-4 shadow-lg"
                    initial={reduce ? { opacity: 0 } : { x: '100%' }}
                    animate={reduce ? { opacity: 1 } : { x: 0 }}
                    exit={reduce ? { opacity: 0 } : { x: '100%' }}
                    transition={{ duration: 0.28, ease }}
                  >
                    <div className="flex h-14 items-center justify-between">
                      <Logo className="rounded-md" />
                      <button
                        ref={closeRef}
                        type="button"
                        className="grid h-11 w-11 place-items-center rounded-md border border-border text-foreground transition-colors hover:bg-surface-muted"
                        onClick={close}
                      >
                        <X className="h-5 w-5" aria-hidden="true" />
                        <span className="sr-only">Close menu</span>
                      </button>
                    </div>
                    <nav className="mt-8 grid gap-1" aria-label="Mobile">
                      {marketingLinks.map((link, index) => (
                        <motion.div
                          key={link.href}
                          initial={reduce ? { opacity: 0 } : { opacity: 0, x: 12 }}
                          animate={{ opacity: 1, x: 0 }}
                          transition={{ delay: 0.08 + index * 0.04, duration: 0.28, ease }}
                        >
                          <Link
                            href={link.href}
                            aria-current={active === link.href ? 'page' : undefined}
                            className={cn(
                              'group flex items-center justify-between rounded-md px-2 py-3 font-display text-2xl font-semibold text-foreground transition-colors hover:bg-surface-muted',
                              active === link.href && 'text-primary',
                            )}
                            onClick={close}
                          >
                            {link.label}
                            <ArrowRight className="h-5 w-5 text-subtle-foreground transition-transform duration-180 group-hover:translate-x-[3px]" aria-hidden="true" />
                          </Link>
                        </motion.div>
                      ))}
                    </nav>
                    <div className="mt-auto grid gap-3">
                      <Link href="/login" className={cn(buttonVariants({ variant: 'secondary', size: 'lg' }), 'w-full')} onClick={close}>
                        Log in
                      </Link>
                      <Link href="/register" className={cn(buttonVariants({ size: 'lg' }), 'w-full')} onClick={close}>
                        Get started
                        <ArrowRight className="h-4 w-4" aria-hidden="true" />
                      </Link>
                    </div>
                  </motion.div>
                </div>
              ) : null}
            </AnimatePresence>,
            document.body,
          )
        : null}
    </>
  );
}
