'use client';

// Dropdown Menu — NiceUI (MIT) · https://niceui.dev/c/components/dropdown-menu
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, createElement, type SVGProps } from 'react';

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

// Icons from Lucide (ISC licence, lucide.dev), inlined so there is nothing to install.
type NiceIconProps = SVGProps<SVGSVGElement> & { size?: number | string; absoluteStrokeWidth?: boolean };
type LucideIcon = (props: NiceIconProps) => JSX.Element;
type LucideProps = NiceIconProps;
const niceIcon = (node: Array<[string, Record<string, string>]>): LucideIcon =>
  function Icon({ size = 24, strokeWidth = 2, absoluteStrokeWidth, children, ...rest }: NiceIconProps) {
    const sw = absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth;
    return createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, ...rest }, ...node.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })), children);
  };
const Archive = niceIcon([["rect",{"width":"20","height":"5","x":"2","y":"3","rx":"1"}],["path",{"d":"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}],["path",{"d":"M10 12h4"}]]);
const Check = niceIcon([["path",{"d":"M20 6 9 17l-5-5"}]]);
const ChevronDown = niceIcon([["path",{"d":"m6 9 6 6 6-6"}]]);
const ChevronRight = niceIcon([["path",{"d":"m9 18 6-6-6-6"}]]);
const Copy = niceIcon([["rect",{"width":"14","height":"14","x":"8","y":"8","rx":"2","ry":"2"}],["path",{"d":"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]]);
const Link2 = niceIcon([["path",{"d":"M9 17H7A5 5 0 0 1 7 7h2"}],["path",{"d":"M15 7h2a5 5 0 1 1 0 10h-2"}],["line",{"x1":"8","x2":"16","y1":"12","y2":"12"}]]);
const Mail = niceIcon([["rect",{"width":"20","height":"16","x":"2","y":"4","rx":"2"}],["path",{"d":"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"}]]);
const MessageSquare = niceIcon([["path",{"d":"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}]]);
const Pencil = niceIcon([["path",{"d":"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{"d":"m15 5 4 4"}]]);
const Share2 = niceIcon([["circle",{"cx":"18","cy":"5","r":"3"}],["circle",{"cx":"6","cy":"12","r":"3"}],["circle",{"cx":"18","cy":"19","r":"3"}],["line",{"x1":"8.59","x2":"15.42","y1":"13.51","y2":"17.49"}],["line",{"x1":"15.41","x2":"8.59","y1":"6.51","y2":"10.49"}]]);
const Star = niceIcon([["polygon",{"points":"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"}]]);
const Trash2 = niceIcon([["path",{"d":"M3 6h18"}],["path",{"d":"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}],["path",{"d":"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"}],["line",{"x1":"10","x2":"10","y1":"11","y2":"17"}],["line",{"x1":"14","x2":"14","y1":"11","y2":"17"}]]);
const Users = niceIcon([["path",{"d":"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}],["circle",{"cx":"9","cy":"7","r":"4"}],["path",{"d":"M22 21v-2a4 4 0 0 0-3-3.87"}],["path",{"d":"M16 3.13a4 4 0 0 1 0 7.75"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = "@keyframes fade-up{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\n.animate-fade-up{animation:fade-up 400ms cubic-bezier(0.16,1,0.3,1) both}\n.focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-jlb7qy')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-jlb7qy';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/controls/DropdownMenu.tsx ────────────────────────
export type MenuEntry =
  | { type?: 'item'; label: string; icon?: LucideIcon; shortcut?: string; danger?: boolean; disabled?: boolean; onSelect?: () => void }
  | { type: 'checkbox'; label: string; checked: boolean; onChange: (checked: boolean) => void; shortcut?: string }
  | { type: 'radio'; label: string; checked: boolean; onSelect: () => void }
  | { type: 'separator' }
  | { type: 'label'; label: string }
  | { type: 'sub'; label: string; icon?: LucideIcon; items: MenuEntry[] };

const focusable = (e: MenuEntry) => e.type !== 'separator' && e.type !== 'label' && !(('disabled' in e && e.disabled) ?? false);

function MenuList({
  items,
  onClose,
  onBack,
  focusFirst,
  className,
  label,
}: {
  items: MenuEntry[];
  onClose: (refocus: boolean) => void;
  onBack?: () => void;
  focusFirst: boolean;
  className?: string;
  label: string;
}) {
  const refs = useRef<Array<HTMLButtonElement | null>>([]);
  const [sub, setSub] = useState<number | null>(null);
  const [subFocus, setSubFocus] = useState(false);
  const [subSide, setSubSide] = useState<'right' | 'left' | 'below'>('right');
  const type = useRef({ buf: '', t: 0 });
  const hover = useRef(0);

  const ids = items.map((e, i) => (focusable(e) ? i : -1)).filter((i) => i >= 0);
  useEffect(() => {
    if (focusFirst) refs.current[ids[0]]?.focus();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [focusFirst]);

  const openSub = (i: number, focus: boolean) => {
    const r = refs.current[i]?.getBoundingClientRect();
    if (r) setSubSide(r.right + 220 <= window.innerWidth ? 'right' : r.left - 220 >= 0 ? 'left' : 'below');
    setSub(i);
    setSubFocus(focus);
  };

  const move = (cur: number, d: number) => {
    const at = ids.indexOf(cur);
    const next = ids[(at + d + ids.length) % ids.length];
    refs.current[next]?.focus();
  };

  const activate = (e: MenuEntry, i: number) => {
    if (e.type === 'sub') return openSub(i, true);
    if (e.type === 'checkbox') return e.onChange(!e.checked);
    if (e.type === 'radio') return e.onSelect();
    if (e.type === undefined || e.type === 'item') {
      e.onSelect?.();
      onClose(true);
    }
  };

  const onKey = (ev: ReactKeyboardEvent, i: number) => {
    const e = items[i];
    switch (ev.key) {
      case 'ArrowDown':
        ev.preventDefault();
        move(i, 1);
        break;
      case 'ArrowUp':
        ev.preventDefault();
        move(i, -1);
        break;
      case 'Home':
        ev.preventDefault();
        refs.current[ids[0]]?.focus();
        break;
      case 'End':
        ev.preventDefault();
        refs.current[ids[ids.length - 1]]?.focus();
        break;
      case 'ArrowRight':
        if (e.type === 'sub') {
          ev.preventDefault();
          openSub(i, true);
        }
        break;
      case 'ArrowLeft':
        if (onBack) {
          ev.preventDefault();
          ev.stopPropagation();
          onBack();
        }
        break;
      case 'Escape':
        ev.preventDefault();
        ev.stopPropagation();
        if (onBack) onBack();
        else onClose(true);
        break;
      case 'Tab':
        onClose(false);
        break;
      case 'Enter':
      case ' ':
        ev.preventDefault();
        activate(e, i);
        break;
      default:
        if (ev.key.length === 1 && /\S/.test(ev.key)) {
          // typeahead: jump to the next item starting with the typed letters
          const t = type.current;
          window.clearTimeout(t.t);
          t.buf += ev.key.toLowerCase();
          t.t = window.setTimeout(() => (t.buf = ''), 500);
          const order = [...ids.slice(ids.indexOf(i) + 1), ...ids.slice(0, ids.indexOf(i) + 1)];
          const hit = order.find((k) => (items[k] as { label: string }).label.toLowerCase().startsWith(t.buf));
          if (hit !== undefined) refs.current[hit]?.focus();
        }
    }
  };

  return (
    <div role="menu" aria-label={label} className={cn('dd-pop w-56 rounded-xl border border-white/10 bg-[#0b0c0e]/95 p-1.5 shadow-[0_24px_60px_-20px_rgba(0,0,0,.9)] backdrop-blur-xl', className)}>
      {items.map((e, i) => {
        if (e.type === 'separator') return <div key={i} role="separator" className="my-1.5 h-px bg-white/[.07]" />;
        if (e.type === 'label') return <p key={i} className="px-2.5 pb-1 pt-2 text-[10.5px] font-medium uppercase tracking-[0.14em] text-[#6b7079]">{e.label}</p>;
        const Icon = 'icon' in e ? e.icon : undefined;
        const role = e.type === 'checkbox' ? 'menuitemcheckbox' : e.type === 'radio' ? 'menuitemradio' : 'menuitem';
        const checked = e.type === 'checkbox' || e.type === 'radio' ? e.checked : undefined;
        const danger = (e.type === undefined || e.type === 'item') && e.danger;
        const disabled = (e.type === undefined || e.type === 'item') && e.disabled;
        return (
          <div key={i} className="relative">
            <button
              ref={(el) => (refs.current[i] = el)}
              role={role}
              aria-checked={checked}
              aria-haspopup={e.type === 'sub' ? 'menu' : undefined}
              aria-expanded={e.type === 'sub' ? sub === i : undefined}
              aria-disabled={disabled || undefined}
              tabIndex={-1}
              onClick={() => !disabled && activate(e, i)}
              onKeyDown={(ev) => onKey(ev, i)}
              onPointerEnter={(ev) => {
                if (ev.pointerType !== 'mouse') return;
                refs.current[i]?.focus();
                window.clearTimeout(hover.current);
                if (e.type === 'sub') hover.current = window.setTimeout(() => openSub(i, false), 120);
                else if (sub !== null) hover.current = window.setTimeout(() => setSub(null), 200);
              }}
              className={cn(
                'flex w-full items-center gap-2.5 rounded-lg px-2.5 py-[7px] text-left text-[13px] outline-none transition-colors',
                disabled ? 'cursor-not-allowed text-[#4b5058]' : danger ? 'text-rose-300 focus:bg-rose-500/15 focus:text-rose-200' : 'text-[#c9cdd3] focus:bg-white/[.07] focus:text-[#f3f4f6]',
                sub === i && 'bg-white/[.07] text-[#f3f4f6]',
              )}
            >
              <span className="grid w-4 shrink-0 place-items-center">
                {e.type === 'checkbox' ? (
                  <Check className={cn('h-3.5 w-3.5 text-[#7dd3fc] transition-all', e.checked ? 'scale-100 opacity-100' : 'scale-50 opacity-0')} />
                ) : e.type === 'radio' ? (
                  <span className={cn('h-1.5 w-1.5 rounded-full bg-[#7dd3fc] transition-all', e.checked ? 'scale-100 opacity-100' : 'scale-0 opacity-0')} />
                ) : Icon ? (
                  <Icon className="h-[15px] w-[15px] opacity-70" strokeWidth={1.8} />
                ) : null}
              </span>
              <span className="flex-1 truncate">{e.label}</span>
              {'shortcut' in e && e.shortcut && <kbd className="font-sans text-[11px] tracking-wide text-[#6b7079]">{e.shortcut}</kbd>}
              {e.type === 'sub' && <ChevronRight className="h-3.5 w-3.5 text-[#6b7079]" />}
            </button>
            {e.type === 'sub' && sub === i && (
              <MenuList
                items={e.items}
                label={e.label}
                focusFirst={subFocus}
                onClose={onClose}
                onBack={() => {
                  setSub(null);
                  refs.current[i]?.focus();
                }}
                className={cn('absolute z-10', subSide === 'right' ? 'left-[calc(100%+6px)] top-[-6px]' : subSide === 'left' ? 'right-[calc(100%+6px)] top-[-6px]' : 'left-4 top-[calc(100%+4px)]')}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

export type DropdownMenuProps = {
  /** Content of the trigger button. */
  trigger: ReactNode;
  items: MenuEntry[];
  align?: 'start' | 'end';
  label?: string;
  className?: string;
};

/**
 * An animated React dropdown menu: icons, shortcuts, separators, checkbox and radio
 * items and nested submenus, with full keyboard support (arrows, Home/End,
 * typeahead, Enter/Space, Esc) and outside-click close.
 */
export function DropdownMenu({ trigger, items, align = 'start', label = 'Menu', className }: DropdownMenuProps) {
  const [open, setOpen] = useState(false);
  const [viaKey, setViaKey] = useState(false);
  const root = useRef<HTMLDivElement>(null);
  const btn = useRef<HTMLButtonElement>(null);
  const [flip, setFlip] = useState(false);

  const close = (refocus: boolean) => {
    setOpen(false);
    if (refocus) btn.current?.focus();
  };

  useEffect(() => {
    if (!open) return;
    const down = (e: PointerEvent) => !root.current?.contains(e.target as Node) && setOpen(false);
    window.addEventListener('pointerdown', down);
    return () => window.removeEventListener('pointerdown', down);
  }, [open]);

  // open upward when there is no room below
  useLayoutEffect(() => {
    if (!open || !btn.current) return;
    const r = btn.current.getBoundingClientRect();
    setFlip(window.innerHeight - r.bottom < 320 && r.top > 320);
  }, [open]);

  return (
    <div ref={root} className={cn('relative inline-block', className)}>
      <style>{`@keyframes dd-in{from{opacity:0;transform:translateY(-4px) scale(.97)}to{opacity:1;transform:none}}.dd-pop{animation:dd-in .16s cubic-bezier(.2,.8,.2,1) both}@media (prefers-reduced-motion:reduce){.dd-pop{animation:none}}`}</style>
      <button
        ref={btn}
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={() => {
          setViaKey(false);
          setOpen((o) => !o);
        }}
        onKeyDown={(e) => {
          if (e.key === 'ArrowDown' || ((e.key === 'Enter' || e.key === ' ') && !open)) {
            e.preventDefault();
            setViaKey(true);
            setOpen(true);
          }
        }}
        className={cn('focus-ring inline-flex h-10 items-center gap-2 rounded-xl border border-white/10 bg-[#0b0c0e] px-3.5 text-[13.5px] font-medium text-[#e5e7eb] shadow-[0_0_0_1px_rgba(255,255,255,0.06)] transition-colors hover:bg-[#1c1e22]', open && 'bg-[#1c1e22]')}
      >
        {trigger}
        <ChevronDown className={cn('h-4 w-4 text-[#8b9099] transition-transform duration-300', open && 'rotate-180')} />
      </button>
      {open && (
        <MenuList
          items={items}
          label={label}
          focusFirst={viaKey}
          onClose={close}
          className={cn('absolute z-50', align === 'end' ? 'right-0' : 'left-0', flip ? 'bottom-[calc(100%+6px)] origin-bottom' : 'top-[calc(100%+6px)] origin-top')}
        />
      )}
    </div>
  );
}

export function DropdownMenuDemo() {
  const [log, setLog] = useState('Pick something from the menu');
  const [starred, setStarred] = useState(true);
  const [notify, setNotify] = useState(false);
  const [view, setView] = useState('Comfortable');
  const say = (s: string) => () => setLog(s);
  const items: MenuEntry[] = [
    { type: 'label', label: 'Project' },
    { label: 'Rename', icon: Pencil, shortcut: '⌘R', onSelect: say('Renamed “Q3 launch”') },
    { label: 'Duplicate', icon: Copy, shortcut: '⌘D', onSelect: say('Duplicated the project') },
    {
      type: 'sub',
      label: 'Share',
      icon: Share2,
      items: [
        { label: 'Copy link', icon: Link2, onSelect: say('Link copied') },
        { label: 'Email', icon: Mail, onSelect: say('Opened an email draft') },
        { label: 'Message', icon: MessageSquare, onSelect: say('Sent to #launch') },
        { type: 'separator' },
        { label: 'Invite people…', icon: Users, onSelect: say('Invite dialog opened') },
      ],
    },
    { type: 'separator' },
    { type: 'checkbox', label: 'Starred', checked: starred, onChange: (v) => (setStarred(v), setLog(v ? 'Starred' : 'Unstarred')) },
    { type: 'checkbox', label: 'Notify me', checked: notify, onChange: (v) => (setNotify(v), setLog(v ? 'Notifications on' : 'Notifications off')) },
    { type: 'separator' },
    { type: 'label', label: 'Density' },
    ...['Compact', 'Comfortable', 'Spacious'].map((d) => ({ type: 'radio' as const, label: d, checked: view === d, onSelect: () => (setView(d), setLog(`Density: ${d}`)) })),
    { type: 'separator' },
    { label: 'Archive', icon: Archive, onSelect: say('Archived'), disabled: true },
    { label: 'Delete', icon: Trash2, shortcut: '⌫', danger: true, onSelect: say('Deleted (not really)') },
  ];
  return (
    <div className="flex min-h-[420px] w-full max-w-xl flex-col items-center pt-4">
      <div className="flex w-full items-center justify-between rounded-2xl border border-white/[.07] bg-[#0b0c0e]/50 p-3 pl-4">
        <div className="flex min-w-0 items-center gap-3">
          <span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-[#38bdf8]/15 text-[#7dd3fc]">
            <Star className={cn('h-4 w-4', starred && 'fill-current')} />
          </span>
          <div className="min-w-0">
            <p className="truncate text-[14px] font-medium text-[#f3f4f6]">Q3 launch</p>
            <p className="truncate text-[12px] text-[#6b7079]">{view} · {notify ? 'notifications on' : 'quiet'}</p>
          </div>
        </div>
        <DropdownMenu trigger="Options" items={items} align="end" label="Project options" />
      </div>
      <p key={log} className="mt-6 animate-fade-up text-[13px] text-[#8b9099]" aria-live="polite">
        {log}
      </p>
    </div>
  );
}
