'use client';

import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import './drawer.css';

/**
 * Overlay drawer: a right-hand panel on desktop, a full-height sheet on mobile.
 *
 * Why this is not components/ui/Modal: that one has no focus trap, no Esc
 * handler, does not mark the page behind it inert and renders inline rather
 * than through a portal — so it inherits any `overflow` or `transform` on an
 * ancestor. None of that matters much for a small centred dialog; all of it
 * matters for a panel covering 80% of the viewport that is opened from inside a
 * flight card.
 *
 * Closing is deliberately over-provided: ✕, Esc, backdrop click and swipe-down
 * all call `onClose`. The swipe is therefore an accelerator, never the only way
 * out — a gesture-only dismissal would fail both a keyboard user and anyone who
 * does not know the gesture is there.
 *
 * Browser Back is **not** handled here. A drawer that owns history has to guess
 * what the URL should say; the consumer knows (the layover drawer writes
 * `#layover=AMM`). Keeping history out of the primitive is what lets the same
 * component be used for something that should not touch the URL at all.
 */

/** Must match the transition duration in drawer.css. */
const ANIMATION_MS = 280;

/** Drag distance past which releasing closes the sheet. */
const SWIPE_CLOSE_PX = 96;
/** …or a quicker flick over a shorter distance, in px per ms. */
const SWIPE_CLOSE_VELOCITY = 0.5;

const FOCUSABLE_SELECTOR = [
  'a[href]',
  'button:not([disabled])',
  'input:not([disabled]):not([type="hidden"])',
  'select:not([disabled])',
  'textarea:not([disabled])',
  'iframe',
  '[tabindex]:not([tabindex="-1"])',
  '[contenteditable="true"]',
].join(',');

/**
 * Body scroll lock, reference counted at module level.
 *
 * Per-instance save/restore looked fine until two overlays overlapped: the
 * second to mount saved `overflow: hidden` as the "previous" value and restored
 * it on close, leaving the page unscrollable with no overlay on screen and
 * nothing in the DOM to explain why. Counting means only the first lock records
 * the real pre-lock value and only the last release puts it back.
 */
let scrollLockCount = 0;
let savedOverflow = '';
let savedPaddingRight = '';

function lockBodyScroll() {
  if (scrollLockCount++ > 0) return;
  const { body } = document;
  savedOverflow = body.style.overflow;
  savedPaddingRight = body.style.paddingRight;
  // Removing the scrollbar shifts the whole page sideways by its width. Measure
  // it and give the space back as padding, rather than assuming zero.
  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  body.style.overflow = 'hidden';
  if (scrollbarWidth > 0) body.style.paddingRight = `${scrollbarWidth}px`;
}

function unlockBodyScroll() {
  if (scrollLockCount === 0) return;
  if (--scrollLockCount > 0) return;
  document.body.style.overflow = savedOverflow;
  document.body.style.paddingRight = savedPaddingRight;
}

function focusableWithin(root: HTMLElement): HTMLElement[] {
  return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
    // offsetParent is null for display:none; a fixed-position element has none
    // either, hence the second test.
    (el) => el.offsetParent !== null || getComputedStyle(el).position === 'fixed',
  );
}

export interface DrawerProps {
  isOpen: boolean;
  onClose: () => void;
  /** Heading text. Also names the dialog for screen readers. */
  title: ReactNode;
  /** Secondary line under the title, e.g. "Amman, Jordan". */
  subtitle?: ReactNode;
  children: ReactNode;
  /** Extra classes on the panel. */
  className?: string;
  /** Accessible name when `title` is not plain text. */
  ariaLabel?: string;
  closeLabel?: string;
}

export default function Drawer({
  isOpen,
  onClose,
  title,
  subtitle,
  children,
  className = '',
  ariaLabel,
  closeLabel = 'Close',
}: DrawerProps) {
  const headingId = useId();
  const panelRef = useRef<HTMLDivElement>(null);
  /** Whatever had focus when the drawer opened, so it can be handed back. */
  const returnFocusRef = useRef<HTMLElement | null>(null);

  /** Kept in the DOM through the exit transition, then removed. */
  const [present, setPresent] = useState(isOpen);
  /** Drives the .is-open class one frame after mount so the transition runs. */
  const [entered, setEntered] = useState(false);
  /** Live finger offset during a swipe, in px. */
  const [dragY, setDragY] = useState(0);

  // ── Presence ─────────────────────────────────────────────────────────────
  //
  // Adjusted during render rather than from an effect. Both transitions have to
  // land in the same commit as the prop change: opening must put the panel in
  // the DOM immediately (an effect would cost a frame the <300ms budget cannot
  // spare), and closing must start the exit transition before the unmount timer
  // is scheduled. Both branches converge on the next render, so neither loops.
  if (isOpen && !present) {
    setPresent(true);
    setDragY(0);
  }
  if (!isOpen && entered) {
    setEntered(false);
  }

  // Remove the panel once the exit transition has had time to run. A timer, not
  // a transitionend listener: under reduced motion there is no transition to
  // end, and an interrupted one never fires — the panel would be stranded in
  // the DOM. Correctness never depends on an animation event.
  useEffect(() => {
    if (isOpen || !present) return;
    const timer = window.setTimeout(() => setPresent(false), ANIMATION_MS);
    return () => window.clearTimeout(timer);
  }, [isOpen, present]);

  // One frame after the panel is in the DOM, flip to .is-open — a transition
  // only runs if the element was painted at its start value first.
  useEffect(() => {
    if (!present || !isOpen || entered) return;
    const frame = requestAnimationFrame(() => setEntered(true));
    return () => cancelAnimationFrame(frame);
  }, [present, isOpen, entered]);

  // ── Body scroll lock ─────────────────────────────────────────────────────
  useEffect(() => {
    if (!present) return;
    lockBodyScroll();
    return unlockBodyScroll;
  }, [present]);

  // ── Hide the rest of the page from AT and from the tab order ─────────────
  useEffect(() => {
    if (!present) return;
    const container = panelRef.current?.closest('[data-drawer-root]');
    // Only the elements we actually changed are restored, so a second overlay
    // already holding something inert is left exactly as it was.
    const touched: HTMLElement[] = [];
    for (const child of Array.from(document.body.children)) {
      if (!(child instanceof HTMLElement) || child === container) continue;
      if (child.hasAttribute('inert')) continue;
      child.setAttribute('inert', '');
      touched.push(child);
    }
    return () => touched.forEach((el) => el.removeAttribute('inert'));
  }, [present]);

  // ── Focus: move in on open, hand back on close ───────────────────────────
  useEffect(() => {
    if (!present) return;
    returnFocusRef.current = document.activeElement as HTMLElement | null;
    const panel = panelRef.current;
    if (panel) {
      // The panel itself, not its first control: a drawer should be read from
      // its heading down, not entered halfway at a close button.
      const frame = requestAnimationFrame(() => panel.focus({ preventScroll: true }));
      return () => cancelAnimationFrame(frame);
    }
  }, [present]);

  useEffect(() => {
    if (present) return;
    const target = returnFocusRef.current;
    returnFocusRef.current = null;
    // Focus goes back where it came from, so a keyboard user resumes at the
    // link they opened this with rather than at the top of the document.
    if (target?.isConnected) target.focus({ preventScroll: true });
  }, [present]);

  // ── Esc and the tab trap ─────────────────────────────────────────────────
  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent<HTMLDivElement>) => {
      if (event.key === 'Escape') {
        event.stopPropagation();
        onClose();
        return;
      }
      if (event.key !== 'Tab') return;

      const panel = panelRef.current;
      if (!panel) return;
      const items = focusableWithin(panel);
      if (items.length === 0) {
        event.preventDefault();
        panel.focus({ preventScroll: true });
        return;
      }
      const first = items[0];
      const last = items[items.length - 1];
      const active = document.activeElement;

      if (event.shiftKey && (active === first || active === panel)) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && active === last) {
        event.preventDefault();
        first.focus();
      }
    },
    [onClose],
  );

  // ── Swipe down to dismiss (mobile) ───────────────────────────────────────
  const dragStart = useRef<{ y: number; time: number } | null>(null);

  const onTouchStart = useCallback((event: React.TouchEvent) => {
    const touch = event.touches[0];
    if (!touch) return;
    dragStart.current = { y: touch.clientY, time: Date.now() };
  }, []);

  const onTouchMove = useCallback((event: React.TouchEvent) => {
    const start = dragStart.current;
    const touch = event.touches[0];
    if (!start || !touch) return;
    // Downward only. Dragging up would lift the sheet off the bottom edge and
    // expose the backdrop beneath it.
    setDragY(Math.max(0, touch.clientY - start.y));
  }, []);

  const onTouchEnd = useCallback(() => {
    const start = dragStart.current;
    dragStart.current = null;
    if (!start) return;
    const elapsed = Math.max(1, Date.now() - start.time);
    const velocity = dragY / elapsed;
    if (dragY > SWIPE_CLOSE_PX || velocity > SWIPE_CLOSE_VELOCITY) {
      onClose();
    } else {
      // Short of the threshold: spring back rather than leave it half open.
      setDragY(0);
    }
  }, [dragY, onClose]);

  if (!present) return null;
  // A portal needs a real document, and on the server there is none. `present`
  // is seeded from `isOpen`, and a drawer is only ever opened by a click or a
  // hash effect — both after hydration — so in practice this short-circuits
  // only while server-rendering an already-closed drawer, which renders null on
  // the client too. No mismatch to hydrate.
  if (typeof document === 'undefined') return null;

  const isDragging = dragY > 0;

  return createPortal(
    <div data-drawer-root>
      <div
        className={`ld-backdrop${entered && isOpen ? ' is-open' : ''}`}
        onClick={onClose}
        aria-hidden="true"
      />
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={ariaLabel ? undefined : headingId}
        aria-label={ariaLabel}
        tabIndex={-1}
        onKeyDown={handleKeyDown}
        className={`ld-panel${entered && isOpen ? ' is-open' : ''} ${className}`.trim()}
        style={
          isDragging
            ? // Follow the finger exactly, with no transition fighting it.
              { transform: `translateY(${dragY}px)`, transition: 'none' }
            : undefined
        }
      >
        <div
          className="ld-panel__head"
          onTouchStart={onTouchStart}
          onTouchMove={onTouchMove}
          onTouchEnd={onTouchEnd}
          onTouchCancel={onTouchEnd}
        >
          <span className="ld-panel__grip" aria-hidden="true" />
          <div className="ld-panel__titles">
            <h2 className="ld-panel__title" id={headingId}>
              {title}
            </h2>
            {subtitle ? <p className="ld-panel__subtitle">{subtitle}</p> : null}
          </div>
          <button type="button" className="ld-panel__close" onClick={onClose} aria-label={closeLabel}>
            <svg width={18} height={18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true">
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="ld-panel__body">
          {children}
        </div>
      </div>
    </div>,
    document.body,
  );
}
