'use client';

/**
 * The 13 Nov design's snippets.js widgets in React, with its classNames: icon sprite, popover
 * (`.mt-pop`, stacked: a click outside closes the ones above it, Esc the top one), menu, list box,
 * select and modal (`.mt-overlay` / `.mt-modal`). Popovers and modals render in a
 * `.mt-page.mt-portal` on <body>, as the design moves them, so the shell never clips them.
 */
import {
  createContext,
  Fragment,
  useContext,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
import { cn } from '@/lib/utils/cn';
import { placePop, type MtPlace, type MtPlaceOpts } from './mtPlace';
import { MT_SPRITE } from './sprite';

export function MtSprite() {
  return (
    <svg
      width="0"
      height="0"
      style={{ position: 'absolute' }}
      aria-hidden="true"
      focusable="false"
      dangerouslySetInnerHTML={{ __html: `<defs>${MT_SPRITE}</defs>` }}
    />
  );
}

export function MtIcon({
  name,
  size = 16,
  className,
}: {
  name: string;
  size?: number;
  className?: string;
}) {
  return (
    <svg className={cn('icon', `iconSize-${size}`, className)} aria-hidden="true" focusable="false">
      <use href={`#mt-i-${name}`} />
    </svg>
  );
}

/**
 * The page class portals carry (`mt-page`, the Snippets page). HUB-721: the Message templates page
 * uses `mtt-page`, the scope its design CSS is kept under.
 */
export const MtScopeContext = createContext('mt-page');

/** Children on <body> inside the page's scope (`.mt-page` variables and selectors). */
export function MtPortal({ children }: { children: ReactNode }) {
  const scope = useContext(MtScopeContext);
  // Popovers and modals only open after a click, so there is always a document by then.
  if (typeof document === 'undefined') return null;
  return createPortal(<div className={cn(scope, 'mt-portal')}>{children}</div>, document.body);
}

// --- Popover stack -------------------------------------------------------------------------------

type PopEntry = { el: HTMLElement; trigger: HTMLElement; close: () => void };
const pops: PopEntry[] = [];

/** Whether a popover is open (a modal's Esc waits for them). */
export const popsOpen = () => pops.length > 0;

function onDocDown(e: MouseEvent) {
  const t = e.target as Node;
  let idx = -1;
  for (let i = pops.length - 1; i >= 0; i--) {
    if (pops[i]!.el.contains(t) || pops[i]!.trigger.contains(t)) {
      idx = i;
      break;
    }
  }
  for (let j = pops.length - 1; j > idx; j--) pops[j]!.close();
}
function onDocKey(e: KeyboardEvent) {
  if (e.key !== 'Escape' && e.key !== 'Esc') return;
  const top = pops[pops.length - 1];
  if (!top) return;
  e.preventDefault();
  e.stopPropagation();
  top.close();
  if (document.body.contains(top.trigger)) top.trigger.focus();
}
function register(entry: PopEntry) {
  if (!pops.length) {
    document.addEventListener('mousedown', onDocDown, true);
    document.addEventListener('keydown', onDocKey, true);
  }
  pops.push(entry);
}
function unregister(entry: PopEntry) {
  const i = pops.indexOf(entry);
  if (i !== -1) pops.splice(i, 1);
  if (!pops.length) {
    document.removeEventListener('mousedown', onDocDown, true);
    document.removeEventListener('keydown', onDocKey, true);
  }
}

/** The design's `openPop`: a `.mt-pop` placed by its trigger. Render it only while open. */
export function MtPop({
  anchor,
  onClose,
  children,
  className,
  role = 'dialog',
  label,
  ...place
}: {
  anchor: HTMLElement | null;
  onClose: () => void;
  children: ReactNode;
  className?: string;
  role?: string;
  label?: string;
} & MtPlaceOpts) {
  const ref = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<MtPlace | null>(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;
  const { align, arrow, placement } = place;

  useLayoutEffect(() => {
    const el = ref.current;
    if (!el || !anchor) return;
    const update = () =>
      setPos(
        placePop(
          anchor.getBoundingClientRect(),
          { w: el.offsetWidth, h: el.offsetHeight },
          { vw: window.innerWidth, vh: window.innerHeight },
          { align, arrow, placement },
        ),
      );
    update();
    const onScroll = (e: Event) => {
      if (e.target instanceof Element && e.target.closest('.mt-pop')) return;
      update();
    };
    window.addEventListener('resize', update);
    document.addEventListener('scroll', onScroll, true);
    const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update);
    ro?.observe(el);
    return () => {
      window.removeEventListener('resize', update);
      document.removeEventListener('scroll', onScroll, true);
      ro?.disconnect();
    };
  }, [anchor, align, arrow, placement]);

  useEffect(() => {
    const el = ref.current;
    if (!el || !anchor) return;
    const entry: PopEntry = { el, trigger: anchor, close: () => closeRef.current() };
    register(entry);
    return () => unregister(entry);
  }, [anchor]);

  if (!anchor) return null;
  return (
    <MtPortal>
      <div className="mt-layer">
        <div
          ref={ref}
          className={cn('mt-pop', arrow === false && 'mt-pop--noarrow', className)}
          role={role}
          aria-label={label}
          data-place={pos?.place}
          style={{
            left: pos?.left ?? 0,
            top: pos?.top ?? 0,
            visibility: pos ? undefined : 'hidden',
            ['--arrow-x' as string]: pos ? `${pos.arrowX}px` : undefined,
          }}
        >
          {children}
        </div>
      </div>
    </MtPortal>
  );
}

// --- Menu ----------------------------------------------------------------------------------------

export interface MtMenuItem {
  label: string;
  onClick?: () => void;
  disabled?: boolean;
  danger?: boolean;
  icon?: string;
  sub?: string;
}

/** The design's `toggleMenu` content: `.mt-menu` buttons, arrow keys move, first one focused. */
export function MtMenu({ items, onClose }: { items: MtMenuItem[]; onClose: () => void }) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    ref.current?.querySelector<HTMLButtonElement>('button:not([disabled])')?.focus();
  }, []);
  const onKeyDown = (e: ReactKeyboardEvent) => {
    if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
    e.preventDefault();
    const btns = [...(ref.current?.querySelectorAll<HTMLButtonElement>('button') ?? [])].filter(
      (b) => !b.disabled,
    );
    let i = btns.indexOf(document.activeElement as HTMLButtonElement);
    i = e.key === 'ArrowDown' ? i + 1 : i - 1;
    if (i < 0) i = btns.length - 1;
    if (i >= btns.length) i = 0;
    btns[i]?.focus();
  };
  return (
    <div className="mt-menu" role="menu" ref={ref} onKeyDown={onKeyDown}>
      {items.map((it) => (
        <button
          key={it.label}
          type="button"
          className={cn('mt-menu__item', it.danger && 'mt-menu__item--danger')}
          role="menuitem"
          disabled={it.disabled}
          onClick={() => {
            onClose();
            it.onClick?.();
          }}
        >
          {it.icon ? <MtIcon name={it.icon} /> : null}
          <span className="mt-menu__txt">
            <span>{it.label}</span>
            {it.sub ? <span className="mt-menu__sub">{it.sub}</span> : null}
          </span>
        </button>
      ))}
    </div>
  );
}

// --- List box ------------------------------------------------------------------------------------

export interface MtOption {
  value: string;
  label: string;
  sub?: string;
  group?: string;
  icon?: string;
  disabled?: boolean;
}

/** The design's `toggleListbox` content: optional search, groups, arrow keys and Enter. */
export function MtListbox({
  items,
  selected,
  searchable,
  searchPlaceholder = 'Search',
  width,
  footer,
  emptyText = 'No results found',
  onSelect,
}: {
  items: MtOption[];
  selected?: string | null;
  searchable?: boolean;
  searchPlaceholder?: string;
  width?: number;
  footer?: ReactNode;
  emptyText?: string;
  onSelect: (item: MtOption) => void;
}) {
  const [q, setQ] = useState('');
  const query = q.toLowerCase();
  const visible = items.filter(
    (it) => !query || `${it.label} ${it.sub ?? ''}`.toLowerCase().includes(query),
  );
  const selIdx = Math.max(
    0,
    visible.findIndex((v) => v.value === selected),
  );
  const [focus, setFocus] = useState(selIdx);
  const listRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (inputRef.current) inputRef.current.focus();
    else listRef.current?.focus();
  }, []);
  useEffect(() => {
    listRef.current
      ?.querySelectorAll('.mt-opt')
      [focus]?.scrollIntoView?.({ block: 'nearest' } as ScrollIntoViewOptions);
  }, [focus]);

  const choose = (it: MtOption) => {
    if (!it.disabled) onSelect(it);
  };
  const onKeyDown = (e: ReactKeyboardEvent) => {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      if (!visible.length) return;
      let i = e.key === 'ArrowDown' ? focus + 1 : focus - 1;
      if (i < 0) i = visible.length - 1;
      if (i >= visible.length) i = 0;
      setFocus(i);
    } else if (e.key === 'Enter' && visible[focus]) {
      e.preventDefault();
      choose(visible[focus]!);
    }
  };

  let lastGroup: string | undefined;
  return (
    <div className="mt-listbox" style={width ? { width } : undefined} onKeyDown={onKeyDown}>
      {searchable ? (
        <div className="mt-listbox__search">
          <input
            ref={inputRef}
            className="input"
            type="search"
            placeholder={searchPlaceholder}
            aria-label={searchPlaceholder}
            autoComplete="off"
            value={q}
            onChange={(e) => {
              setQ(e.target.value);
              setFocus(0);
            }}
          />
          <MtIcon name="search" className="mt-search__icon" />
        </div>
      ) : null}
      <div className="mt-listbox__list" role="listbox" tabIndex={-1} ref={listRef}>
        {visible.map((it, i) => {
          const head =
            it.group && it.group !== lastGroup ? (
              <div className="mt-group" role="presentation">
                {it.group}
              </div>
            ) : null;
          lastGroup = it.group ?? lastGroup;
          return (
            <Fragment key={it.value}>
              {head}
              <div
                className={cn('mt-opt', i === focus && 'is-focus')}
                role="option"
                aria-selected={it.value === selected ? 'true' : 'false'}
                aria-disabled={it.disabled ? 'true' : undefined}
                onClick={() => choose(it)}
              >
                {it.icon ? <MtIcon name={it.icon} /> : null}
                <span className="mt-opt__txt">
                  <span className="mt-opt__title">{it.label}</span>
                  {it.sub ? <span className="mt-opt__sub">{it.sub}</span> : null}
                </span>
              </div>
            </Fragment>
          );
        })}
        {!visible.length ? <div className="mt-empty-opt">{emptyText}</div> : null}
      </div>
      {footer ? <div className="mt-listbox__foot">{footer}</div> : null}
    </div>
  );
}

/** The design's `createSelect`: a `.mt-select` button opening a list box its width. */
export function MtSelect({
  value,
  options,
  placeholder = '',
  searchable,
  onChange,
}: {
  value: string | null;
  options: MtOption[];
  placeholder?: string;
  searchable?: boolean;
  onChange: (value: string) => void;
}) {
  const [btn, setBtn] = useState<HTMLButtonElement | null>(null);
  const [open, setOpen] = useState(false);
  const opt = options.find((o) => o.value === value);
  return (
    <>
      <button
        ref={setBtn}
        type="button"
        className="mt-select"
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        onKeyDown={(e) => {
          if (e.key === 'ArrowDown' && !open) {
            e.preventDefault();
            setOpen(true);
          }
        }}
      >
        <span className={cn('mt-select__label', !opt && 'is-placeholder')}>
          {opt ? opt.label : placeholder}
        </span>
        <MtIcon name="chevron-down" />
      </button>
      {open ? (
        <MtPop anchor={btn} onClose={() => setOpen(false)} arrow={false}>
          <MtListbox
            items={options}
            selected={value}
            searchable={searchable}
            searchPlaceholder={searchable ? placeholder || 'Search' : ''}
            width={Math.max(btn?.getBoundingClientRect().width ?? 0, 200)}
            onSelect={(it) => {
              setOpen(false);
              onChange(it.value);
            }}
          />
        </MtPop>
      ) : null}
    </>
  );
}

// --- Modal ---------------------------------------------------------------------------------------

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

function visibleFocusables(root: HTMLElement): HTMLElement[] {
  return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
    (n) => !!(n.offsetWidth || n.offsetHeight || n.getClientRects().length),
  );
}

let openModals = 0;

/**
 * The design's modal manager for one `.mt-overlay`: body scroll lock, focus on open (the
 * `focus` selector, else the first control that is not the close button), Tab kept inside,
 * Esc (after any popover) and a backdrop click close it — not for `staticBackdrop`.
 * The opener gets focus back. Render it only while open.
 */
export function MtModal({
  id,
  onClose,
  labelledBy,
  describedBy,
  role = 'dialog',
  className,
  staticBackdrop,
  focus,
  drawer,
  children,
}: {
  id: string;
  onClose: () => void;
  labelledBy: string;
  describedBy?: string;
  role?: 'dialog' | 'alertdialog';
  className?: string;
  staticBackdrop?: boolean;
  focus?: string;
  /** HUB-721: the design's side drawer (`.mt-overlay--drawer` > `aside.mt-drawer`). */
  drawer?: boolean;
  children: ReactNode;
}) {
  const ovRef = useRef<HTMLDivElement>(null);
  const downRef = useRef<EventTarget | null>(null);
  const closeRef = useRef(onClose);
  closeRef.current = onClose;

  useEffect(() => {
    const opener = document.activeElement as HTMLElement | null;
    openModals++;
    document.body.classList.add('mt-lock');
    const t = window.setTimeout(() => {
      const ov = ovRef.current;
      if (!ov) return;
      let f = focus ? ov.querySelector<HTMLElement>(focus) : null;
      if (!f) {
        const list = visibleFocusables(ov);
        f = list.find((n) => !n.matches('.icon-btn')) ?? list[0] ?? null;
      }
      f?.focus();
    }, 30);
    const onKey = (e: KeyboardEvent) => {
      const ov = ovRef.current;
      if (!ov) return;
      // Only the top modal answers.
      const all = document.querySelectorAll('.mt-portal > .mt-overlay');
      if (all[all.length - 1] !== ov) return;
      if (e.key === 'Escape' || e.key === 'Esc') {
        if (popsOpen()) return;
        e.preventDefault();
        closeRef.current();
        return;
      }
      if (e.key === 'Tab' && !popsOpen()) {
        const f = visibleFocusables(ov);
        if (!f.length) return;
        const first = f[0]!;
        const last = f[f.length - 1]!;
        if (!ov.contains(document.activeElement)) {
          e.preventDefault();
          first.focus();
        } else if (e.shiftKey && document.activeElement === first) {
          e.preventDefault();
          last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => {
      window.clearTimeout(t);
      window.removeEventListener('keydown', onKey);
      openModals--;
      if (!openModals) document.body.classList.remove('mt-lock');
      if (opener && document.body.contains(opener)) {
        try {
          opener.focus();
        } catch {
          // gone
        }
      }
    };
    // Focus is set once, when it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <MtPortal>
      <div
        ref={ovRef}
        className={cn('mt-overlay', drawer && 'mt-overlay--drawer')}
        id={id}
        onMouseDown={(e) => {
          downRef.current = e.target;
        }}
        onClick={(e) => {
          if (
            !staticBackdrop &&
            e.target === e.currentTarget &&
            downRef.current === e.currentTarget
          ) {
            onClose();
          }
        }}
      >
        {drawer ? (
          <aside
            className={cn('mt-drawer', className)}
            role={role}
            aria-modal="true"
            aria-labelledby={labelledBy}
            aria-describedby={describedBy}
          >
            {children}
          </aside>
        ) : (
          <div
            className={cn('mt-modal', className)}
            role={role}
            aria-modal="true"
            aria-labelledby={labelledBy}
            aria-describedby={describedBy}
          >
            {children}
          </div>
        )}
      </div>
    </MtPortal>
  );
}

/** A modal's head: title and the ghost close button. */
export function MtModalHead({
  id,
  title,
  onClose,
}: {
  id: string;
  title: ReactNode;
  onClose: () => void;
}) {
  return (
    <div className="mt-modal__head">
      <h2 id={id}>{title}</h2>
      <button
        type="button"
        className="icon-btn icon-btn--ghost"
        aria-label="Close"
        onClick={onClose}
      >
        <MtIcon name="x" size={18} />
      </button>
    </div>
  );
}
