'use client';

import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { portalMenuStyle } from '@/features/objects/ui/Dropdown';
import { cn } from '@/lib/utils/cn';

/**
 * DI-3: the design's own dropdown, modal and drawer markup (`view-contact-segment.php`), so the
 * page keeps its classes. Behaviour follows `crm-assets-28-oct-2026/assets/js/components/dropdown-menu.js`
 * (outside click and Escape close a menu) and the page JS (JS:2685-2731 modals, JS:3026-3069
 * drawers, JS:4384-4391 Escape, JS:5237-5247 an item click closes its menu unless it holds a
 * checkbox or radio).
 */
/**
 * QA round 1 BUG-02/BUG-03: which side of the button a portalled menu lines up with. The design's
 * `.dropdown__menu` sits at `right: 0` unless it is `--left`.
 */
export function segMenuAlign(menuClassName: string): 'left' | 'right' {
  return /(^|\s)dropdown__menu--left(\s|$)/.test(menuClassName) ? 'left' : 'right';
}

/**
 * Puts a portalled menu where `portalMenuStyle` says, before paint (a layout effect); `!important`
 * beats the design's own `position: absolute !important` menu rules.
 */
function placeMenu(button: HTMLElement, menu: HTMLElement, align: 'left' | 'right') {
  const r = button.getBoundingClientRect();
  const vw = document.documentElement.clientWidth || window.innerWidth;
  const s = portalMenuStyle(
    r,
    { w: menu.offsetWidth, h: menu.offsetHeight },
    { vw, vh: window.innerHeight },
    align,
  );
  menu.style.setProperty('position', 'fixed', 'important');
  menu.style.setProperty('top', `${String(s.top)}px`, 'important');
  menu.style.setProperty('left', `${String(s.left)}px`, 'important');
  menu.style.setProperty('right', 'auto', 'important');
  menu.style.setProperty('bottom', 'auto', 'important');
}

export function SegDropdown({
  toggle,
  toggleClassName,
  toggleId,
  toggleTitle,
  toggleLabel,
  menuClassName = 'dropdown__menu--right',
  className,
  portal,
  listbox = false,
  toggleDisabled = false,
  children,
}: {
  toggle: React.ReactNode;
  toggleClassName?: string;
  toggleId?: string;
  toggleTitle?: string;
  toggleLabel?: string;
  menuClassName?: string;
  className?: string;
  /**
   * QA round 1 BUG-02/BUG-03: draws the open menu outside a clipping parent (a table cell with
   * `overflow: hidden`, a scrolling table wrap), placed against the button with `position: fixed`
   * as the objects `Dropdown` portal does. `true` draws it on the body; a selector draws it in the
   * closest matching ancestor, so page-scoped menu styles (`#segmentsPage .dropdown__divider`)
   * still apply. The menu sits in a copy of this dropdown's wrapper for the same reason. It closes
   * when the page scrolls or resizes. Closed, it stays in place (hidden) as without `portal`.
   */
  portal?: boolean | string;
  /** A select: the toggle says it opens a listbox and the menu is one (its items are options). */
  listbox?: boolean;
  /** The toggle can't be pressed (e.g. Use in and Actions while a segment processes, S-08). */
  toggleDisabled?: boolean;
  /** The menu; a function gets `close`. */
  children: React.ReactNode | ((close: () => void) => React.ReactNode);
}) {
  const [open, setOpen] = useState(false);
  const [host, setHost] = useState<HTMLElement | null>(null);
  const root = useRef<HTMLDivElement>(null);
  const btn = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  useEscapeLayer(open, () => setOpen(false));

  // Where the open menu is drawn: found on open, as the button's ancestors don't change.
  useLayoutEffect(() => {
    if (!open || !portal) {
      setHost(null);
      return;
    }
    const scoped = typeof portal === 'string' ? root.current?.closest<HTMLElement>(portal) : null;
    setHost(scoped ?? document.body);
  }, [open, portal]);

  useLayoutEffect(() => {
    if (!open || !host || !btn.current || !menuRef.current) return;
    placeMenu(btn.current, menuRef.current, segMenuAlign(menuClassName));
  }, [open, host, menuClassName]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (root.current?.contains(t) || menuRef.current?.contains(t)) return;
      setOpen(false);
    };
    const onMove = (e: Event) => {
      if (e.target instanceof Node && menuRef.current?.contains(e.target)) return;
      setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    if (portal) {
      window.addEventListener('scroll', onMove, true);
      window.addEventListener('resize', onMove);
    }
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('scroll', onMove, true);
      window.removeEventListener('resize', onMove);
    };
  }, [open, portal]);

  const close = () => setOpen(false);
  const onMenuClick = (e: React.MouseEvent) => {
    const item = (e.target as HTMLElement).closest('.dropdown__item');
    if (item && !item.querySelector('input[type="checkbox"], input[type="radio"]')) close();
  };

  const portalled = open && host !== null;
  const menu = (
    <div
      ref={menuRef}
      className={cn('dropdown__menu', menuClassName)}
      role={listbox ? 'listbox' : undefined}
      data-dropdown-menu=""
      hidden={!open}
      onClick={onMenuClick}
    >
      {typeof children === 'function' ? children(close) : children}
    </div>
  );

  return (
    <div className={cn('dropdown', className)} data-dropdown="" ref={root}>
      <button
        ref={btn}
        type="button"
        className={toggleClassName}
        id={toggleId}
        title={toggleTitle}
        aria-label={toggleLabel}
        data-dropdown-toggle=""
        aria-haspopup={listbox ? 'listbox' : undefined}
        aria-expanded={open}
        disabled={toggleDisabled}
        onClick={() => setOpen((v) => !v)}
      >
        {toggle}
      </button>
      {portalled
        ? createPortal(
            <div className={cn('dropdown', className)} data-dropdown-portal="">
              {menu}
            </div>,
            host,
          )
        : menu}
    </div>
  );
}

/**
 * Open layers (menus, pickers, modals, drawers), newest last. One Escape closes only the newest,
 * so Escape in the Edit email modal leaves the preview drawer under it open.
 */
const layers: Array<{ close: () => void }> = [];

function onEscapeKey(e: KeyboardEvent) {
  if (e.key !== 'Escape' || layers.length === 0) return;
  e.preventDefault();
  layers[layers.length - 1]!.close();
}

/** Puts an open layer on the Escape stack until it closes (JS:4384-4391). */
export function useEscapeLayer(open: boolean, onClose: () => void) {
  const latest = useRef(onClose);
  latest.current = onClose;
  useEffect(() => {
    if (!open) return;
    const layer = { close: () => latest.current() };
    layers.push(layer);
    if (layers.length === 1) window.addEventListener('keydown', onEscapeKey);
    return () => {
      const i = layers.indexOf(layer);
      if (i >= 0) layers.splice(i, 1);
      if (layers.length === 0) window.removeEventListener('keydown', onEscapeKey);
    };
  }, [open]);
}

/** The pure stack rule, for tests: the newest open layer is the one Escape closes. */
export function escapeTarget<T>(stack: readonly T[]): T | undefined {
  return stack[stack.length - 1];
}

const useEscape = useEscapeLayer;

/** `.lp-modal-ov > .lp-modal`; a mousedown on the backdrop closes it (JS:2720-2724). */
export function SegModal({
  open,
  onClose,
  labelledBy,
  id,
  className,
  overlayClassName,
  style,
  children,
}: {
  open: boolean;
  onClose: () => void;
  labelledBy: string;
  id?: string;
  className?: string;
  overlayClassName?: string;
  style?: React.CSSProperties;
  children: React.ReactNode;
}) {
  useEscape(open, onClose);
  if (!open) return null;
  return (
    <div
      className={cn('lp-modal-ov', overlayClassName, 'is-open')}
      id={id}
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className={cn('lp-modal', className)}
        role="dialog"
        aria-modal="true"
        aria-labelledby={labelledBy}
        style={style}
      >
        {children}
      </div>
    </div>
  );
}

/** `.lp-side-ov` + `aside.lp-side`; the overlay closes it and `html.lp-lock` stops page scroll. */
export function SegDrawer({
  open,
  onClose,
  label,
  id,
  className,
  children,
}: {
  open: boolean;
  onClose: () => void;
  label: string;
  id?: string;
  className?: string;
  children: React.ReactNode;
}) {
  useEscape(open, onClose);
  useEffect(() => {
    if (!open) return;
    document.documentElement.classList.add('lp-lock');
    return () => document.documentElement.classList.remove('lp-lock');
  }, [open]);
  if (!open) return null;
  return (
    <>
      <div className="lp-side-ov is-open" onClick={onClose} />
      <aside className={cn('lp-side', className, 'is-open')} id={id} aria-label={label}>
        {children}
      </aside>
    </>
  );
}
