'use client';

import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { X } from 'lucide-react';
import { useEffect, useRef, type ReactNode } from 'react';

import { cn } from '@/lib/utils';

const ease = [0.2, 0.8, 0.2, 1] as const;

/** Escape to close, body scroll lock and focus restore for overlays. */
function useOverlay(open: boolean, onClose: () => void, panel: React.RefObject<HTMLDivElement | null>) {
  const closeRef = useRef(onClose);
  useEffect(() => {
    closeRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    if (!open) return undefined;
    const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const frame = window.requestAnimationFrame(() => {
      const target = panel.current?.querySelector<HTMLElement>('[data-autofocus], a[href], button:not([disabled]), input, select, textarea');
      (target ?? panel.current)?.focus();
    });
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') closeRef.current();
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.cancelAnimationFrame(frame);
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = previousOverflow;
      previousFocus?.focus();
    };
  }, [open, panel]);
}

export function Modal({
  open,
  title,
  onClose,
  children,
}: {
  open: boolean;
  title: string;
  onClose: () => void;
  children: ReactNode;
}) {
  const reduce = useReducedMotion();
  const panel = useRef<HTMLDivElement>(null);
  useOverlay(open, onClose, panel);
  return (
    <AnimatePresence>
      {open ? (
        <div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center sm:p-4">
          <motion.button
            type="button"
            className="absolute inset-0 bg-foreground/40 backdrop-blur-[4px]"
            aria-label="Close dialog"
            tabIndex={-1}
            onClick={onClose}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.18 }}
          />
          <motion.div
            ref={panel}
            role="dialog"
            aria-modal="true"
            aria-label={title}
            tabIndex={-1}
            className="relative z-10 max-h-[90vh] w-full overflow-auto rounded-t-xl border border-border bg-surface p-6 shadow-lg outline-none sm:max-w-lg sm:rounded-xl"
            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: 8 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.97, y: 8 }}
            transition={{ duration: 0.18, ease }}
          >
            <span className="mx-auto -mt-2 mb-4 block h-1 w-10 rounded-pill bg-border-strong sm:hidden" aria-hidden="true" />
            <div className="mb-5 flex items-start justify-between gap-3">
              <h2 className="font-display text-h3 font-bold">{title}</h2>
              <button type="button" className="-m-1 grid h-9 w-9 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-muted hover:text-foreground" aria-label="Close" onClick={onClose}>
                <X className="h-4 w-4" aria-hidden="true" />
              </button>
            </div>
            {children}
          </motion.div>
        </div>
      ) : null}
    </AnimatePresence>
  );
}

export function Drawer({
  open,
  title,
  onClose,
  children,
  side = 'left',
  className,
}: {
  open: boolean;
  title: string;
  onClose: () => void;
  children: ReactNode;
  side?: 'left' | 'right' | 'bottom';
  /** Extra classes for the panel (e.g. `p-0` for edge-to-edge content). */
  className?: string;
}) {
  const reduce = useReducedMotion();
  const panel = useRef<HTMLDivElement>(null);
  useOverlay(open, onClose, panel);
  const offscreen = side === 'bottom' ? { y: '100%' } : side === 'right' ? { x: '100%' } : { x: '-100%' };
  return (
    <AnimatePresence>
      {open ? (
        <div className="fixed inset-0 z-50">
          <motion.button
            type="button"
            className="absolute inset-0 bg-foreground/40 backdrop-blur-[4px]"
            aria-label="Close"
            tabIndex={-1}
            onClick={onClose}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.18 }}
          />
          <motion.div
            ref={panel}
            role="dialog"
            aria-modal="true"
            aria-label={title}
            tabIndex={-1}
            className={cn(
              'absolute overflow-auto bg-surface shadow-lg outline-none',
              side === 'bottom'
                ? 'inset-x-0 bottom-0 max-h-[85vh] rounded-t-xl border-t border-border p-4 pt-3'
                : side === 'right'
                  ? 'inset-y-0 right-0 w-[min(100vw,560px)] border-l border-border p-0'
                  : 'inset-y-0 left-0 w-[min(86vw,300px)] border-r border-border p-4',
              className,
            )}
            initial={reduce ? { opacity: 0 } : offscreen}
            animate={reduce ? { opacity: 1 } : { x: 0, y: 0 }}
            exit={reduce ? { opacity: 0 } : offscreen}
            transition={{ duration: 0.28, ease }}
          >
            {side === 'bottom' ? <span className="mx-auto mb-3 block h-1 w-10 rounded-pill bg-border-strong" aria-hidden="true" /> : null}
            {children}
          </motion.div>
        </div>
      ) : null}
    </AnimatePresence>
  );
}
