'use client';

import { useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
import { createPortal } from 'react-dom';
import { cn } from '@/lib/utils/cn';

/** `side`: beside the anchor (left when it fits, else right), as the list's cell editors open. */
export type PopoverPlacement = 'up' | 'down' | 'side';

export type Pos = {
  top: number;
  left: number;
  placement: PopoverPlacement;
  maxHeight: number;
  width: number;
  /** B10 (`design`): the design's state classes (`is-up`, `is-left`, `is-right`, `is-narrow`). */
  cls?: string;
  /** B10, point 62 (`arrow`): where the arrow points, from the popover's left (and top, beside). */
  arrowLeft?: number;
  arrowTop?: number;
  /** B10: under 640 px a panel takes the window's width (design `place()`, list-page.js:572-574). */
  narrow?: boolean;
};

/**
 * B10, points 62 and 63: the design's `place()` (list-page.js:561-602), for the popovers a page
 * opts in (`design`). Gap 11 with an arrow, 4 without. Above when the natural height is more than
 * the room below and there is more room above (B9's flip); the height is the room on that side,
 * at least 180, with no other cap. Under 640 px wide a panel (not a menu) is the window's width
 * less 16. The arrow points at the anchor's middle, at most 40 px in, kept 18 px from the ends.
 * Side popovers (cell editors) sit beside the anchor, centred on it, arrow pointing at it; when
 * neither side fits they open above or below. `w` is the box's width; `natural` its height with no
 * cap (unknown before it is drawn: it then opens down, and is placed again once measured).
 */
export function designPlace({
  r,
  vw,
  vh,
  w,
  natural,
  arrow,
  align,
  menu,
  side,
}: {
  r: { top: number; bottom: number; left: number; right: number; width: number; height: number };
  vw: number;
  vh: number;
  w: number;
  natural?: number;
  arrow: boolean;
  align: 'start' | 'center' | 'end';
  menu: boolean;
  side: boolean;
}): Pos {
  const gap = arrow ? 11 : 4;
  const narrow = vw < 640 && !menu;
  const width = narrow ? vw - 16 : w;
  const below = vh - r.bottom - gap - 8;
  const above = r.top - gap - 8;
  const up = natural !== undefined && natural > below && above > below;
  let maxHeight = Math.max(180, up ? above : below);
  let h = natural !== undefined ? Math.min(natural, maxHeight) : maxHeight;
  let left = narrow
    ? 8
    : align === 'end'
      ? r.right - width
      : align === 'center'
        ? r.left + r.width / 2 - width / 2
        : r.left;
  left = Math.round(Math.max(8, Math.min(left, vw - width - 8)));
  let top = Math.round(up ? r.top - gap - h : r.bottom + gap);
  let placement: PopoverPlacement = up ? 'up' : 'down';
  const cls = [up ? 'is-up' : '', narrow ? 'is-narrow' : ''];
  let arrowLeft = arrow
    ? Math.round(Math.max(18, Math.min(r.left + Math.min(r.width / 2, 40) - left, width - 18)))
    : undefined;
  let arrowTop: number | undefined;
  if (side && !narrow) {
    const sl = r.left - gap - width;
    const sr = r.right + gap;
    const useL = sl >= 8;
    const useR = !useL && sr + width <= vw - 8;
    if (useL || useR) {
      maxHeight = vh - 16;
      h = natural !== undefined ? Math.min(natural, maxHeight) : maxHeight;
      const tp = Math.max(8, Math.min(r.top + r.height / 2 - 70, vh - h - 8));
      left = Math.round(useL ? sl : sr);
      top = Math.round(tp);
      placement = 'side';
      cls[0] = useL ? 'is-left' : 'is-right';
      if (arrow) {
        arrowTop = Math.round(Math.max(16, Math.min(r.top + r.height / 2 - tp, h - 16)));
        arrowLeft = undefined;
      }
    }
  }
  const named = cls.filter(Boolean).join(' ');
  return {
    top,
    left,
    placement,
    maxHeight,
    width,
    ...(named ? { cls: named } : {}),
    ...(arrowLeft !== undefined ? { arrowLeft } : {}),
    ...(arrowTop !== undefined ? { arrowTop } : {}),
    ...(narrow ? { narrow } : {}),
  };
}

/** B10: a scroll inside the popover itself (its own list), which the design ignores (:626). */
export function isOwnScroll(
  e: Pick<Event, 'type' | 'target'> | undefined,
  box: Pick<Node, 'contains'> | null,
): boolean {
  return e?.type === 'scroll' && Boolean(box?.contains(e.target as Node));
}

/** B10: Escape puts focus back on the button that opened the popover (list-page.js:4425). */
export function focusBack(anchor: Pick<HTMLElement, 'isConnected' | 'focus'> | null | undefined) {
  if (anchor?.isConnected) anchor.focus({ preventScroll: true });
}

/**
 * Portal + fixed positioning so menus escape modal overflow. Flips up/down by viewport space.
 */
/** Layers opened from inside a popover but drawn on <body> (list-page operator list, date picker). */
const NESTED_LAYERS = '.lp-float, .lp-cal';

/**
 * PB4b: popovers opened from another popover (the playbook editor's picker lists, as the design's
 * `keep: p`), marked `lp-pop-sub`. Only they carry the class, so other popovers are unchanged.
 */
const SUB_LAYER = '.lp-pop-sub';

/** A sub-layer other than this popover's own box is open: it takes the click or the Escape. */
export function otherSubLayer(
  self: Pick<Node, 'contains'> | null,
  layers: ArrayLike<unknown>,
): boolean {
  return Array.from(layers).some((l) => l !== self && !self?.contains(l as Node));
}

/** The default stacking order: over the composer windows (`.acx`, 1040) and modals (1050). */
export const POPOVER_Z_INDEX = 1200;

/**
 * Above or below the anchor, its height budget and its top. Without `flip`: flips only when under
 * 180 px is left on the preferred side and the other has more. With `flip` (B9, point 30, the bulk
 * More menu): the design's `place()` (list-page.js:572-582): above when the popover's `natural`
 * height is more than the room below and there is more room above; until it has been measured
 * (`natural` unknown) it opens down. The height budget is the same rule either way.
 */
export function verticalPlacement({
  top,
  bottom,
  vh,
  gap,
  maxHeight,
  preferred,
  fillHeight = false,
  natural,
  flip = false,
}: {
  top: number;
  bottom: number;
  vh: number;
  gap: number;
  maxHeight: number;
  preferred: 'up' | 'down';
  fillHeight?: boolean;
  natural?: number;
  flip?: boolean;
}): { placement: 'up' | 'down'; maxHeight: number; top: number } {
  const spaceBelow = vh - bottom - gap - 8;
  const spaceAbove = top - gap - 8;
  let placement: 'up' | 'down' = preferred;
  if (flip) {
    placement =
      natural !== undefined && natural > spaceBelow && spaceAbove > spaceBelow ? 'up' : 'down';
  } else {
    if (preferred === 'down' && spaceBelow < 180 && spaceAbove > spaceBelow) placement = 'up';
    if (preferred === 'up' && spaceAbove < 180 && spaceBelow > spaceAbove) placement = 'down';
  }
  const available = placement === 'down' ? spaceBelow : spaceAbove;
  const height = Math.min(maxHeight, Math.max(120, available));
  // For non-fill menus, estimate from max; final top for "up" uses maxHeight budget (the effect
  // after paint pins it to the real height). A measured flip uses the real height at once.
  const shown = flip && natural !== undefined ? Math.min(natural, height) : height;
  const rawTop = placement === 'down' ? bottom + gap : top - gap - shown;
  return {
    placement,
    maxHeight: height,
    top: Math.max(8, Math.min(rawTop, vh - 8 - (fillHeight ? height : 40))),
  };
}

/** The popover's height with no cap, read and put back at once (design `place()`, :574-577). */
function naturalHeight(el: HTMLElement | null): number | undefined {
  if (!el) return undefined;
  const cap = el.style.maxHeight;
  el.style.maxHeight = 'none';
  const h = el.offsetHeight;
  el.style.maxHeight = cap;
  return h;
}

export function AnchoredPopover({
  open,
  anchorRef,
  onClose,
  children,
  className,
  width,
  maxHeight = 360,
  align = 'start',
  preferred = 'down',
  gap = 6,
  fillHeight = false,
  fitContent = false,
  zIndex = POPOVER_Z_INDEX,
  label,
  flip = false,
  design = false,
  arrow = false,
  menu = false,
  returnFocus = false,
  closeOnTab = false,
}: {
  open: boolean;
  anchorRef: RefObject<HTMLElement | null>;
  onClose?: () => void;
  children: ReactNode;
  className?: string;
  width?: number;
  maxHeight?: number;
  align?: 'start' | 'center' | 'end';
  preferred?: PopoverPlacement;
  gap?: number;
  /** Stretch to available height (assoc panel). Small menus stay content-sized. */
  fillHeight?: boolean;
  /** Size to the children instead of a fixed width (formatting pill). */
  fitContent?: boolean;
  /** Stacking order; list-page popovers open over their own dialogs (z-index 10040). */
  zIndex?: number;
  /** The dialog's accessible name (CT-003: an unnamed dialog reads as empty). */
  label?: string;
  /**
   * B9, point 30: above or below by the design's rule (`verticalPlacement`), for the bulk More
   * menu. Off: master's 180 px rule. The height budget is the same either way.
   */
  flip?: boolean;
  /**
   * B10, points 62 and 63: placed by the design's `place()` (`designPlace`): its gap, flip and
   * height from the room left, and `width` is the body's (the box adds its 1 px borders). `gap`,
   * `maxHeight` and `flip` are then not read.
   */
  design?: boolean;
  /** B10, point 62 (with `design`): draws the design's arrow (`.lp-pop__arrow`). */
  arrow?: boolean;
  /** B10 (with `design`): a menu, which keeps its width on narrow screens. */
  menu?: boolean;
  /** B10: Escape puts focus back on the anchor, as the design (list-page.js:4425). */
  returnFocus?: boolean;
  /** B10, point 5: Tab closes it, as the design's ⋮ menu (object-menu.js:159). */
  closeOnTab?: boolean;
}) {
  const popRef = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<Pos | null>(null);

  useLayoutEffect(() => {
    if (!open) {
      setPos(null);
      return;
    }

    const place = (e?: Event) => {
      const el = anchorRef.current;
      if (!el) return;
      // B10: as the design (list-page.js:626), a scroll inside the popover itself doesn't place it
      // again; measuring it there would reset the list's scroll to the top.
      if (design && isOwnScroll(e, popRef.current)) return;
      const r = el.getBoundingClientRect();
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      if (design) {
        // Before it is drawn: the given body width plus the borders; after: its real width.
        const drawn = popRef.current?.offsetWidth;
        const box = fitContent ? drawn || (width ? width + 2 : 480) : (width ?? 318) + 2;
        setPos(
          designPlace({
            r,
            vw,
            vh,
            w: Math.min(box, vw - 16),
            natural: naturalHeight(popRef.current),
            arrow,
            align,
            menu,
            side: preferred === 'side',
          }),
        );
        return;
      }
      const measured = fitContent ? popRef.current?.offsetWidth || width || 480 : (width ?? 320);
      const w = Math.min(measured, vw - 16);
      if (preferred === 'side') {
        const fitsLeft = r.left - gap - w >= 8;
        const sideLeft = fitsLeft ? r.left - gap - w : Math.min(r.right + gap, vw - w - 8);
        const height = Math.min(maxHeight, vh - 16);
        setPos({
          top: Math.max(8, Math.min(r.top, vh - 8 - 40)),
          left: Math.max(8, sideLeft),
          placement: 'side',
          maxHeight: height,
          width: w,
        });
        return;
      }
      const v = verticalPlacement({
        top: r.top,
        bottom: r.bottom,
        vh,
        gap,
        maxHeight,
        preferred,
        fillHeight,
        // Already drawn (a scroll or resize): its natural height decides the flip at once.
        natural: flip ? naturalHeight(popRef.current) : undefined,
        flip,
      });

      let left =
        align === 'center' ? r.left + r.width / 2 - w / 2 : align === 'end' ? r.right - w : r.left;
      left = Math.max(8, Math.min(left, vw - w - 8));

      setPos({ top: v.top, left, placement: v.placement, maxHeight: v.maxHeight, width: w });
    };

    place();
    window.addEventListener('resize', place);
    window.addEventListener('scroll', place, true);
    // B10: the design places a popover again after its content changes (list-page.js:2188,
    // :4142), so one opened above stays against its anchor when its list gets shorter.
    let observer: ResizeObserver | null = null;
    let watched: HTMLElement | null = null;
    const watch = () => {
      if (!design || typeof ResizeObserver === 'undefined') return;
      const box = popRef.current;
      if (!box || box === watched) return;
      observer?.disconnect();
      observer = new ResizeObserver(() => place());
      observer.observe(box);
      watched = box;
    };
    watch();
    // The box is drawn after this first pass; watch it once it is.
    const frame = design ? window.requestAnimationFrame(watch) : 0;
    return () => {
      window.removeEventListener('resize', place);
      window.removeEventListener('scroll', place, true);
      if (frame) window.cancelAnimationFrame(frame);
      observer?.disconnect();
    };
  }, [
    open,
    anchorRef,
    width,
    maxHeight,
    align,
    preferred,
    gap,
    fillHeight,
    fitContent,
    flip,
    design,
    arrow,
    menu,
  ]);

  // After paint, pin using real size (up placement + fitContent width).
  useLayoutEffect(() => {
    if (!open || !pos || fillHeight) return;
    const el = anchorRef.current;
    const pop = popRef.current;
    if (!el || !pop) return;
    const r = el.getBoundingClientRect();
    if (design) {
      // B10: placed again from its real width and natural height. It reads only those and the
      // room around the anchor, so the next pass gives the same answer and this settles.
      const vw = window.innerWidth;
      const next = designPlace({
        r,
        vw,
        vh: window.innerHeight,
        w: pos.narrow ? Math.min(pop.offsetWidth, vw - 16) : pop.offsetWidth,
        natural: naturalHeight(pop),
        arrow,
        align,
        menu,
        side: preferred === 'side',
      });
      const moved = (Object.keys(next) as Array<keyof Pos>).some((k) => {
        const a = next[k];
        const b = pos[k];
        return typeof a === 'number' && typeof b === 'number' ? Math.abs(a - b) > 1 : a !== b;
      });
      if (moved || Object.keys(next).length !== Object.keys(pos).length) setPos(next);
      return;
    }
    // B9, point 30: with `flip`, above or below is decided here from the natural height once drawn.
    // It reads only that height and the room around the anchor, so the next pass gives the same
    // answer and this settles.
    const flipped =
      flip && pos.placement !== 'side'
        ? verticalPlacement({
            top: r.top,
            bottom: r.bottom,
            vh: window.innerHeight,
            gap,
            maxHeight,
            preferred: preferred === 'up' ? 'up' : 'down',
            natural: naturalHeight(pop),
            flip: true,
          })
        : null;
    const vw = window.innerWidth;
    const h = pop.offsetHeight;
    const w = pop.offsetWidth;
    const vh = window.innerHeight;
    const nextTop = flipped
      ? flipped.top
      : pos.placement === 'up'
        ? Math.max(8, r.top - gap - h)
        : pos.placement === 'side'
          ? Math.max(8, Math.min(r.top, vh - 8 - h))
          : pos.top;
    let nextLeft = pos.left;
    if (pos.placement === 'side') {
      nextLeft =
        r.left - gap - w >= 8 ? r.left - gap - w : Math.max(8, Math.min(r.right + gap, vw - w - 8));
    } else if (fitContent) {
      nextLeft =
        align === 'center' ? r.left + r.width / 2 - w / 2 : align === 'end' ? r.right - w : r.left;
      nextLeft = Math.max(8, Math.min(nextLeft, vw - w - 8));
    }
    const flipMoved =
      flipped !== null &&
      (flipped.placement !== pos.placement || Math.abs(flipped.maxHeight - pos.maxHeight) > 1);
    if (flipMoved || Math.abs(nextTop - pos.top) > 1 || Math.abs(nextLeft - pos.left) > 1) {
      setPos((p) =>
        p
          ? {
              ...p,
              top: nextTop,
              left: nextLeft,
              width: w,
              ...(flipped ? { placement: flipped.placement, maxHeight: flipped.maxHeight } : {}),
            }
          : p,
      );
    }
  }, [
    open,
    pos,
    fillHeight,
    anchorRef,
    gap,
    fitContent,
    align,
    flip,
    maxHeight,
    preferred,
    design,
    arrow,
    menu,
  ]);

  useLayoutEffect(() => {
    if (!open || !onClose) return;
    // Capture + stopImmediatePropagation so Esc closes only this menu, not the parent popup.
    const onKey = (e: KeyboardEvent) => {
      // As the design's ⋮ menu, only a Tab from inside it (object-menu.js:152-159).
      if (closeOnTab && e.key === 'Tab' && popRef.current?.contains(document.activeElement)) {
        onClose();
        return;
      }
      if (e.key !== 'Escape') return;
      // A list or date picker floating over this popover closes first (it handles Escape).
      if (document.querySelector(NESTED_LAYERS)) return;
      if (otherSubLayer(popRef.current, document.querySelectorAll(SUB_LAYER))) return;
      e.preventDefault();
      e.stopImmediatePropagation();
      // Read before closing: the anchor may be the same element the close unmounts.
      const anchor = anchorRef.current;
      onClose();
      if (returnFocus) focusBack(anchor);
    };
    const onDoc = (e: MouseEvent) => {
      const t = e.target as Node;
      if (anchorRef.current?.contains(t)) return;
      if (popRef.current?.contains(t)) return;
      if ((t as Element).closest?.(NESTED_LAYERS)) return;
      const sub = (t as Element).closest?.(SUB_LAYER);
      if (sub && sub !== popRef.current) return;
      onClose();
    };
    const t = window.setTimeout(() => document.addEventListener('mousedown', onDoc), 0);
    window.addEventListener('keydown', onKey, true);
    return () => {
      window.clearTimeout(t);
      document.removeEventListener('mousedown', onDoc);
      window.removeEventListener('keydown', onKey, true);
    };
  }, [open, onClose, anchorRef, returnFocus, closeOnTab]);

  if (!open || !pos || typeof document === 'undefined') return null;

  return createPortal(
    <AnchoredPopoverFrame
      frameRef={popRef}
      pos={pos}
      className={className}
      fitContent={fitContent}
      fillHeight={fillHeight}
      zIndex={zIndex}
      label={label}
    >
      {children}
    </AnchoredPopoverFrame>,
    document.body,
  );
}

/** The popover's box, from its worked-out place. Pure, so its markup can be tested in Node. */
export function AnchoredPopoverFrame({
  frameRef,
  pos,
  className,
  fitContent,
  fillHeight,
  zIndex,
  label,
  children,
}: {
  frameRef?: RefObject<HTMLDivElement | null>;
  pos: Pos;
  className?: string;
  fitContent: boolean;
  fillHeight: boolean;
  zIndex: number;
  label?: string;
  children: ReactNode;
}) {
  return (
    <div
      ref={frameRef}
      className={cn('crm-anchored-popover', className, pos.cls)}
      data-placement={pos.placement}
      style={{
        position: 'fixed',
        top: pos.top,
        left: pos.left,
        width: fitContent && !pos.narrow ? 'max-content' : pos.width,
        ...(fillHeight ? { height: pos.maxHeight } : {}),
        maxHeight: pos.maxHeight,
        zIndex,
      }}
      role="dialog"
      aria-label={label}
    >
      {pos.arrowLeft !== undefined || pos.arrowTop !== undefined ? (
        // B10, point 62: the design's arrow (list-page.js:540, :587, :600).
        <span
          className="lp-pop__arrow"
          aria-hidden
          style={{
            ...(pos.arrowLeft !== undefined ? { left: pos.arrowLeft } : {}),
            ...(pos.arrowTop !== undefined ? { top: pos.arrowTop } : {}),
          }}
        />
      ) : null}
      {children}
    </div>
  );
}
