"use client";

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";

/** Props of {@link RailPopover}. */
export interface RailPopoverProps {
  /** The rail item it opened from; null = closed. */
  anchor: HTMLElement | null;
  /** Outside tap or Escape; also call it when an entry is chosen. */
  onClose: () => void;
  /** Spoken name of the menu, e.g. t("Account"). */
  ariaLabel: string;
  children: ReactNode;
}

/** Gap between the popover and the rail item / the viewport edges, in px. */
const POPOVER_GAP = 8;

/** Where a {@link RailPopover} sits: pinned by its top edge (grows down) or its bottom edge (grows up). */
export type RailPopoverPlace =
  | { edge: "top"; left: number; top: number; maxHeight: number }
  | { edge: "bottom"; left: number; bottom: number; maxHeight: number };

/**
 * The popover's place: beside the rail item. An item in the upper half of the
 * screen (the rail's items) gets the card with top edges aligned, growing
 * down; one in the lower half (the account at the foot) with bottom edges
 * aligned, growing up.
 *
 * @returns `maxHeight` is the room on the side the card grows to (minus the
 * gap), so a long list scrolls inside the card instead of leaving the screen.
 * The host still subtracts the safe-area inset on that side, which only CSS
 * knows.
 */
export function railPopoverPlace(
  anchor: { top: number; right: number; bottom: number },
  viewportHeight: number,
): RailPopoverPlace {
  const left = anchor.right + POPOVER_GAP;
  if ((anchor.top + anchor.bottom) / 2 < viewportHeight / 2) {
    const top = Math.max(POPOVER_GAP, anchor.top);
    return { edge: "top", left, top, maxHeight: viewportHeight - top - POPOVER_GAP };
  }
  const bottom = Math.max(POPOVER_GAP, viewportHeight - anchor.bottom);
  return { edge: "bottom", left, bottom, maxHeight: viewportHeight - bottom - POPOVER_GAP };
}

/**
 * The tablet rail's menu surface: a small card beside the rail item it opened
 * from (top edges aligned for an upper item, bottom edges for a lower one),
 * above everything else. Closes on a tap outside
 * it and on Escape (the focus goes back to the item); the content closes it
 * on a choice by calling `onClose`. On open the focus moves into the card.
 * Stations, Notifications and Account open one.
 */
export function RailPopover({ anchor, ...rest }: RailPopoverProps) {
  if (!anchor || typeof document === "undefined") return null;
  return createPortal(<Panel anchor={anchor} {...rest} />, document.body);
}

function Panel({
  anchor,
  onClose,
  ariaLabel,
  children,
}: RailPopoverProps & { anchor: HTMLElement }) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [place, setPlace] = useState<RailPopoverPlace | null>(null);

  useLayoutEffect(() => {
    function measure() {
      setPlace(railPopoverPlace(anchor.getBoundingClientRect(), window.innerHeight));
    }
    measure();
    // Capture: the rail is its own scroller, and its scroll moves the anchor.
    // The card's own scrolling doesn't, so it doesn't re-measure.
    function onScroll(event: Event) {
      if (panelRef.current?.contains(event.target as Node)) return;
      measure();
    }
    window.addEventListener("resize", measure);
    window.addEventListener("scroll", onScroll, true);
    return () => {
      window.removeEventListener("resize", measure);
      window.removeEventListener("scroll", onScroll, true);
    };
  }, [anchor]);

  // Screen readers and keyboards start inside the menu.
  useEffect(() => {
    panelRef.current?.focus({ preventScroll: true });
  }, []);

  const onCloseRef = useRef(onClose);
  useEffect(() => {
    onCloseRef.current = onClose;
  });
  useEffect(() => {
    function onDown(event: PointerEvent) {
      const target = event.target as Node;
      // The item itself toggles the menu through its own click.
      if (panelRef.current?.contains(target) || anchor.contains(target)) return;
      onCloseRef.current();
    }
    function onKey(event: KeyboardEvent) {
      if (event.key !== "Escape" || event.defaultPrevented) return;
      event.preventDefault();
      onCloseRef.current();
      anchor.focus({ preventScroll: true });
    }
    document.addEventListener("pointerdown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("pointerdown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [anchor]);

  return (
    <div
      ref={panelRef}
      role="dialog"
      aria-label={ariaLabel}
      tabIndex={-1}
      data-testid="rail-popover"
      style={{
        position: "fixed",
        left: place?.left ?? 0,
        top: place?.edge === "top" ? place.top : undefined,
        bottom: place?.edge === "bottom" ? place.bottom : place ? undefined : 0,
        // Taller content scrolls inside the card instead of leaving the screen.
        maxHeight: place
          ? `calc(${place.maxHeight}px - env(safe-area-inset-${place.edge === "top" ? "bottom" : "top"}))`
          : undefined,
        zIndex: 90,
        visibility: place ? "visible" : "hidden",
      }}
      className="fade-in flex w-80 max-w-[calc(100vw-6rem)] flex-col overflow-y-auto overscroll-contain rounded-2xl border border-surface-stroke bg-surface-base py-2 shadow-floating outline-none"
    >
      {children}
    </div>
  );
}
