'use client';

/**
 * The design's (settings-properties.php) small pieces for Settings > Properties: stroke icons,
 * popovers under a button (lists and menus) and dialogs, with its `pp-*` classes.
 */
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { cn } from '@/lib/utils/cn';
import { shownItems, type ListItem } from './list-items';

export type { ListItem };

/* ------------------------------------------------------------------ icons */

const PATHS: Record<string, string> = {
  caret: '<path d="m6 9 6 6 6-6"/>',
  down: '<path d="M12 5v14M19 12l-7 7-7-7"/>',
  up: '<path d="M12 19V5M5 12l7-7 7 7"/>',
  sort: '<path d="M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4"/>',
  search: '<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>',
  x: '<path d="M18 6 6 18M6 6l12 12"/>',
  chevL: '<path d="m15 18-6-6 6-6"/>',
  chevR: '<path d="m9 18 6-6-6-6"/>',
  lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
  agent: '<path d="M12 3l2.2 6.8L21 12l-6.8 2.2L12 21l-2.2-6.8L3 12l6.8-2.2z"/>',
};

/** The design's stroke icons (`pp-i`). */
export function Ico({ name, className }: { name: string; className?: string }) {
  return (
    <svg
      className={cn('pp-i', className)}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      dangerouslySetInnerHTML={{ __html: PATHS[name] ?? '' }}
    />
  );
}

/* --------------------------------------------------------------- popovers */

/** A floating panel under its anchor (`pp-pop`); closes on a click outside or Escape. */
export function Pop({
  anchor,
  width,
  align,
  className,
  onClose,
  children,
}: {
  anchor: HTMLElement;
  width?: number;
  align?: 'right';
  className?: string;
  onClose: () => void;
  children: ReactNode;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<{ top: number; left: number; width: number } | null>(null);

  const place = useCallback(() => {
    const r = anchor.getBoundingClientRect();
    const w = Math.min(Math.max(width ?? 0, r.width), window.innerWidth - 16);
    let left = align === 'right' ? r.right - w : r.left;
    left = Math.max(8, Math.min(left, window.innerWidth - w - 8));
    const h = ref.current?.offsetHeight ?? 0;
    const below = window.innerHeight - r.bottom - 12;
    const top = below < h && r.top - 12 > below ? Math.max(8, r.top - h - 6) : r.bottom + 6;
    setPos({ top: Math.round(top), left: Math.round(left), width: Math.round(w) });
  }, [anchor, width, align]);

  useLayoutEffect(() => {
    place();
    const raf = requestAnimationFrame(place);
    window.addEventListener('resize', place);
    window.addEventListener('scroll', place, true);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', place);
      window.removeEventListener('scroll', place, true);
    };
  }, [place]);

  useEffect(() => {
    anchor.setAttribute('aria-expanded', 'true');
    const onDown = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!ref.current?.contains(t) && !anchor.contains(t)) onClose();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        onClose();
        anchor.focus();
      }
    };
    document.addEventListener('mousedown', onDown, true);
    document.addEventListener('keydown', onKey, true);
    return () => {
      anchor.setAttribute('aria-expanded', 'false');
      document.removeEventListener('mousedown', onDown, true);
      document.removeEventListener('keydown', onKey, true);
    };
  }, [anchor, onClose]);

  return createPortal(
    <div
      ref={ref}
      className={cn('pp-pop', className)}
      style={pos ? { top: pos.top, left: pos.left, width: pos.width } : { visibility: 'hidden' }}
    >
      {children}
    </div>,
    document.body,
  );
}

/** A searchable option list (`pp-pop--list`). */
export function ListPop({
  anchor,
  items,
  current,
  onPick,
  onClose,
  search = true,
  width = 280,
}: {
  anchor: HTMLElement;
  items: ListItem[];
  current: string;
  onPick: (value: string) => void;
  onClose: () => void;
  search?: boolean;
  width?: number;
}) {
  const [q, setQ] = useState('');
  const shown = shownItems(items, q);
  return (
    <Pop anchor={anchor} width={width} className="pp-pop--list" onClose={onClose}>
      {search && (
        <label className="pp-search pp-search--pop">
          <input
            type="search"
            placeholder="Search"
            aria-label="Search"
            autoFocus
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <Ico name="search" />
        </label>
      )}
      <div className="pp-optlist" role="listbox">
        {shown.length ? (
          shown.map((it) =>
            it.heading ? (
              <div key={it.value} className="pp-opt-head" role="presentation">
                {it.label}
              </div>
            ) : (
              <button
                key={it.value}
                type="button"
                className={cn(
                  'pp-opt',
                  it.value === current && 'is-on',
                  it.indent && 'pp-opt--indent',
                )}
                role="option"
                aria-selected={it.value === current}
                onClick={() => {
                  onClose();
                  onPick(it.value);
                }}
              >
                <span>{it.label}</span>
                {it.desc && <small>{it.desc}</small>}
              </button>
            ),
          )
        ) : (
          <div className="pp-empty-s">No results</div>
        )}
      </div>
    </Pop>
  );
}

export interface MenuItem {
  label: string;
  run: () => void;
  danger?: boolean;
  disabled?: boolean;
  title?: string;
}

/** A row's "More" menu (`pp-pop--menu`). */
export function MenuPop({
  anchor,
  items,
  onClose,
}: {
  anchor: HTMLElement;
  items: MenuItem[];
  onClose: () => void;
}) {
  return (
    <Pop anchor={anchor} width={240} className="pp-pop--menu" onClose={onClose}>
      <div className="pp-menu" role="menu">
        {items.map((it) => (
          <button
            key={it.label}
            type="button"
            className={cn('pp-menu__item', it.danger && 'is-danger')}
            role="menuitem"
            disabled={it.disabled}
            title={it.title}
            onClick={() => {
              onClose();
              it.run();
            }}
          >
            {it.label}
          </button>
        ))}
      </div>
    </Pop>
  );
}

/** The design's dialog (`pp-modal`): the first button is the main one. */
export function PpModal({
  title,
  children,
  okLabel,
  okDisabled,
  danger,
  onOk,
  onClose,
}: {
  title: string;
  children: ReactNode;
  okLabel: string;
  okDisabled?: boolean;
  danger?: boolean;
  /** False keeps the dialog open. */
  onOk: () => boolean | void | Promise<boolean | void>;
  onClose: () => void;
}) {
  const [busy, setBusy] = useState(false);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  return createPortal(
    <div
      className="pp-modal-ov"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="pp-modal" role="dialog" aria-modal="true" aria-labelledby="ppMT">
        <header className="pp-modal__head">
          <h2 id="ppMT">{title}</h2>
          <button type="button" className="pp-x" aria-label="Close" onClick={onClose}>
            <Ico name="x" />
          </button>
        </header>
        <div className="pp-modal__body">{children}</div>
        <footer className="pp-modal__foot">
          <button
            type="button"
            className={cn('pp-btn', danger ? 'pp-btn--danger' : 'pp-btn--primary')}
            disabled={busy || okDisabled}
            onClick={async () => {
              setBusy(true);
              try {
                if ((await onOk()) !== false) onClose();
              } finally {
                setBusy(false);
              }
            }}
          >
            {okLabel}
          </button>
          <button type="button" className="pp-btn pp-btn--outline" onClick={onClose}>
            Cancel
          </button>
        </footer>
      </div>
    </div>,
    document.body,
  );
}
