"use client";

import { useEffect, useRef, useState, type MouseEvent, type ReactNode } from "react";
import { createPortal } from "react-dom";
import {
  containmentPositionClass,
  useContainment,
  type Containment,
} from "./containment";
import { DIALOG_Z_INDEX, SurfaceZIndexProvider } from "./surface-z-index";
import { useModalFocus } from "./use-modal-focus";

// Open DialogShells in open order; only the last (top-most) handles Escape.
const openDialogStack: symbol[] = [];

// A nested popup (menu, listbox, non-modal picker panel, an expanded
// trigger) that should get Escape first when the key comes from inside it.
// Modal dialogs (drawers, sheets, other DialogShells) are excluded: a host
// drawer behind this dialog must not swallow its Escape, and stacked
// DialogShells are ordered by `openDialogStack`.
const NESTED_POPUP_SELECTOR = [
  '[role="menu"]',
  '[role="listbox"]',
  '[role="dialog"]:not([aria-modal="true"])',
  '[aria-expanded="true"]',
].join(", ");

function isInsideNestedPopup(
  target: EventTarget | null,
  ownOverlay: HTMLElement | null,
): boolean {
  if (!(target instanceof Element)) return false;
  const popup = target.closest(NESTED_POPUP_SELECTOR);
  return popup != null && popup !== ownOverlay;
}

/**
 * How long the dialog takes to fade in and out. On close it stays mounted for
 * this long, so the dimming fades instead of switching off.
 */
export const DIALOG_FADE_MS = 180;

/** Panel width of a {@link DialogShell}. */
export type DialogShellSize = "sm" | "md" | "lg";

const SIZE_CLASS: Record<DialogShellSize, string> = {
  sm: "max-w-sm",
  md: "max-w-md",
  lg: "max-w-lg",
};

/**
 * The dialog's accessible name: either the id of its visible heading
 * (preferred — the name then matches what is on screen) or a translated label.
 */
type DialogShellLabel =
  | { labelledBy: string; ariaLabel?: never }
  | { ariaLabel: string; labelledBy?: never };

/** Props for {@link DialogShell}. */
export type DialogShellProps = DialogShellLabel & {
  open: boolean;
  /** Called on Escape, and on a backdrop click when `dismissOnBackdrop`. */
  onClose: () => void;
  /** Panel max width. Default `"sm"`. */
  size?: DialogShellSize;
  /**
   * Close on a click on the backdrop. Default false — a decision or a
   * destructive confirm should not vanish on a stray click.
   */
  dismissOnBackdrop?: boolean;
  /**
   * Extra panel classes — padding (the panel has none of its own, so a
   * full-bleed hero can reach the edges), text alignment, a max height.
   */
  panelClassName?: string;
  /**
   * Anchor to the viewport (default — `position: fixed`, body portal) or to the
   * closest positioned ancestor (`position: absolute`, rendered inline). Falls
   * back to the nearest ContainmentProvider.
   */
  containment?: Containment;
  /** Stacking. Default {@link DIALOG_Z_INDEX}. */
  zIndex?: number;
  children: ReactNode;
};

/**
 * The shared modal frame: a dimmed backdrop and a centred, rounded, shadowed
 * panel. `ConfirmDialog` and every hand-built dialog draw this frame, so they
 * look and behave alike.
 *
 * @remarks
 * - Fades in and out ({@link DIALOG_FADE_MS}); on close it stays mounted and
 *   `inert` for that long. A caller whose children depend on what was open
 *   should keep them until then, or the panel empties while it fades.
 * - Rendered in a body portal with `position: fixed` (unless `containment` is
 *   `"container"`), so it escapes a host drawer's `overflow` clip or transform.
 * - Takes the focus while open, keeps Tab inside the panel, and gives the
 *   focus back to the opener on close (`useModalFocus`).
 * - Escape calls `onClose` — only in the top-most open shell, and not when the
 *   key comes from a nested open menu/picker. The keypress is consumed, so a
 *   hosting drawer's own Escape handler does not also fire. To block closing
 *   (e.g. while a request runs), ignore the call in `onClose`.
 * - Renders nothing while `open` is false.
 */
export function DialogShell({
  open,
  onClose,
  labelledBy,
  ariaLabel,
  size = "sm",
  dismissOnBackdrop = false,
  panelClassName,
  containment: containmentProp,
  zIndex = DIALOG_Z_INDEX,
  children,
}: DialogShellProps) {
  const panelRef = useRef<HTMLDivElement>(null);
  const overlayRef = useRef<HTMLDivElement>(null);
  const onCloseRef = useRef(onClose);
  // Fade: `rendered` outlives `open` by DIALOG_FADE_MS, `entered` turns true
  // one frame after mount — so opacity has a "from" on the way in and a "to"
  // on the way out. Opening sets `rendered` during render (no extra commit
  // with nothing on screen).
  const [rendered, setRendered] = useState(open);
  const [entered, setEntered] = useState(false);
  if (open && !rendered) setRendered(true);
  useEffect(() => {
    if (open) {
      const frame = requestAnimationFrame(() => setEntered(true));
      return () => cancelAnimationFrame(frame);
    }
    if (!rendered) return;
    const timer = setTimeout(() => {
      setRendered(false);
      setEntered(false);
    }, DIALOG_FADE_MS);
    return () => clearTimeout(timer);
  }, [open, rendered]);
  const visible = open && entered;
  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);
  // Explicit prop wins; otherwise inherit from the nearest ContainmentProvider.
  const containmentFromContext = useContainment();
  const containment = containmentProp ?? containmentFromContext;

  // Focus moves to the panel itself on open (not a button): it keeps Enter
  // from triggering a destructive action, without painting the browser's
  // focus ring on a button.
  useModalFocus(panelRef, open);

  // Capture phase + stopImmediatePropagation: the document-level bubble
  // listeners of a hosting drawer/sheet never see the same keypress, so one
  // Escape closes only the top dialog.
  useEffect(() => {
    if (!open) return;
    const id = Symbol("dialog-shell");
    openDialogStack.push(id);
    function onKeyDown(e: KeyboardEvent) {
      if (e.key !== "Escape" || e.defaultPrevented) return;
      if (openDialogStack[openDialogStack.length - 1] !== id) return;
      if (isInsideNestedPopup(e.target, overlayRef.current)) return;
      e.stopImmediatePropagation();
      onCloseRef.current();
    }
    document.addEventListener("keydown", onKeyDown, true);
    return () => {
      document.removeEventListener("keydown", onKeyDown, true);
      const index = openDialogStack.indexOf(id);
      if (index !== -1) openDialogStack.splice(index, 1);
    };
  }, [open]);

  if (!open && !rendered) return null;

  function onBackdropClick(e: MouseEvent<HTMLDivElement>) {
    if (dismissOnBackdrop && e.target === e.currentTarget) onClose();
  }

  const overlay = (
    <div
      ref={overlayRef}
      role="dialog"
      aria-modal="true"
      aria-labelledby={labelledBy}
      aria-label={ariaLabel}
      // closing: still painted for the fade, but out of the way of clicks, focus and screen readers
      inert={!open}
      style={{ zIndex, transitionDuration: `${DIALOG_FADE_MS}ms` }}
      onClick={onBackdropClick}
      className={`${containmentPositionClass(containment)} inset-0 flex items-center justify-center bg-black/50 p-6 transition-opacity ease-out motion-reduce:transition-none ${visible ? "opacity-100" : "opacity-0"}`}
    >
      <div
        ref={panelRef}
        tabIndex={-1}
        className={`flex w-full ${SIZE_CLASS[size]} flex-col rounded-2xl bg-surface-base shadow-2xl outline-none ${panelClassName ?? ""}`}
      >
        <SurfaceZIndexProvider value={zIndex}>{children}</SurfaceZIndexProvider>
      </div>
    </div>
  );

  // Container mode renders inline so `absolute inset-0` anchors to the column;
  // viewport mode portals to <body> so `fixed inset-0` covers the page.
  if (containment === "container") return overlay;
  if (typeof document === "undefined") return null;
  return createPortal(overlay, document.body);
}
