'use client';

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

import { useEffect, useRef, useState, type ComponentType, 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 Camera = niceIcon([["path",{"d":"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"}],["circle",{"cx":"12","cy":"13","r":"3"}]]);
const FileText = niceIcon([["path",{"d":"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}],["path",{"d":"M14 2v4a2 2 0 0 0 2 2h4"}],["path",{"d":"M10 9H8"}],["path",{"d":"M16 13H8"}],["path",{"d":"M16 17H8"}]]);
const Image = niceIcon([["rect",{"width":"18","height":"18","x":"3","y":"3","rx":"2","ry":"2"}],["circle",{"cx":"9","cy":"9","r":"2"}],["path",{"d":"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]]);
const Mic = niceIcon([["path",{"d":"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}],["path",{"d":"M19 10v2a7 7 0 0 1-14 0v-2"}],["line",{"x1":"12","x2":"12","y1":"19","y2":"22"}]]);
const Music = niceIcon([["path",{"d":"M9 18V5l12-2v13"}],["circle",{"cx":"6","cy":"18","r":"3"}],["circle",{"cx":"18","cy":"16","r":"3"}]]);
const Plus = niceIcon([["path",{"d":"M5 12h14"}],["path",{"d":"M12 5v14"}]]);
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 Video = niceIcon([["path",{"d":"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"}],["rect",{"x":"2","y":"6","width":"14","height":"12","rx":"2"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = ".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-10x759f')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-10x759f';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/media/RadialMenu.tsx ─────────────────────────────
export type RadialItem = { label: string; icon: ComponentType<{ className?: string }>; onSelect?: () => void };

export type RadialMenuProps = {
  items: RadialItem[];
  /** 'full' fans items all the way round; 'corner' fans a quarter circle up and to the left. */
  variant?: 'full' | 'corner';
  radius?: number;
  className?: string;
  label?: string;
};

/** A radial circle menu: items fan out around a floating button with a spring. */
export function RadialMenu({ items, variant = 'full', radius = 96, className, label = 'Quick actions' }: RadialMenuProps) {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const [picked, setPicked] = useState<string | null>(null);
  const root = useRef<HTMLDivElement>(null);
  const btns = useRef<Array<HTMLButtonElement | null>>([]);
  const fab = useRef<HTMLButtonElement>(null);

  const n = items.length;
  const angle = (i: number) => {
    if (variant === 'corner') {
      const a0 = 180, a1 = 270; // left → up
      return ((a0 + ((a1 - a0) * i) / Math.max(1, n - 1)) * Math.PI) / 180;
    }
    return ((-90 + (360 * i) / n) * Math.PI) / 180;
  };

  useEffect(() => {
    if (!open) return;
    btns.current[active]?.focus();
  }, [open, active]);

  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]);

  const close = () => {
    setOpen(false);
    fab.current?.focus();
  };

  return (
    <div
      ref={root}
      className={cn('relative inline-grid place-items-center', className)}
      onKeyDown={(e) => {
        if (!open) return;
        if (e.key === 'Escape') {
          e.preventDefault();
          close();
        } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
          e.preventDefault();
          setActive((a) => (a + 1) % n);
        } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
          e.preventDefault();
          setActive((a) => (a - 1 + n) % n);
        } else if (e.key === 'Home') setActive(0);
        else if (e.key === 'End') setActive(n - 1);
      }}
    >
      <div role="menu" aria-label={label} aria-hidden={!open} className="absolute inset-0">
        {items.map((it, i) => {
          const a = angle(i);
          const x = Math.cos(a) * radius;
          const y = Math.sin(a) * radius;
          const Icon = it.icon;
          return (
            <button
              key={it.label}
              ref={(el) => (btns.current[i] = el)}
              role="menuitem"
              tabIndex={open && i === active ? 0 : -1}
              onClick={() => {
                it.onSelect?.();
                setPicked(it.label);
                close();
              }}
              onFocus={() => setActive(i)}
              onMouseEnter={() => setActive(i)}
              className={cn(
                'focus-ring group absolute left-1/2 top-1/2 -ml-6 -mt-6 grid h-12 w-12 place-items-center rounded-full bg-[#121316] text-[#c9cdd3] shadow-[0_0_0_1px_rgba(255,255,255,0.06),0_1px_2px_rgba(0,0,0,0.4),0_8px_24px_-8px_rgba(0,0,0,0.5)] transition-all duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)] motion-reduce:duration-0 hover:bg-[#0ea5e9] hover:text-[#000000] focus-visible:bg-[#0ea5e9] focus-visible:text-[#000000]',
                !open && 'pointer-events-none',
              )}
              style={{
                transform: open ? `translate(${x}px, ${y}px) scale(1)` : 'translate(0,0) scale(0.3)',
                opacity: open ? 1 : 0,
                transitionDelay: `${open ? i * 35 : (n - i) * 20}ms`,
              }}
            >
              <Icon className="h-5 w-5" />
              <span
                className={cn(
                  'pointer-events-none absolute whitespace-nowrap rounded-md bg-[#000000]/90 px-2 py-1 text-[11px] text-[#e5e7eb] opacity-0 transition-opacity',
                  'group-hover:opacity-100 group-focus-visible:opacity-100',
                  y < -10 ? 'bottom-full mb-2' : 'top-full mt-2',
                )}
              >
                {it.label}
              </span>
            </button>
          );
        })}
      </div>
      <button
        ref={fab}
        type="button"
        aria-haspopup="menu"
        aria-expanded={open}
        aria-label={open ? 'Close menu' : label}
        onClick={() => {
          setActive(0);
          setOpen((o) => !o);
        }}
        className="focus-ring relative z-10 grid h-14 w-14 place-items-center rounded-full bg-[#38bdf8] text-[#000000] shadow-[0_0_0_1px_rgba(125,211,252,0.4),0_8px_32px_-8px_rgba(56,189,248,0.6)] transition-transform duration-300 ease-[cubic-bezier(0.34,1.56,0.64,1)] active:scale-90"
      >
        <Plus className={cn('h-6 w-6 transition-transform duration-500 ease-[cubic-bezier(0.34,1.56,0.64,1)]', open && 'rotate-[135deg]')} />
      </button>
      <span className="sr-only" aria-live="polite">
        {picked ? `${picked} selected` : ''}
      </span>
    </div>
  );
}

const CREATE: RadialItem[] = [
  { label: 'Photo', icon: Camera },
  { label: 'Video', icon: Video },
  { label: 'Voice note', icon: Mic },
  { label: 'Document', icon: FileText },
  { label: 'Gallery', icon: Image },
  { label: 'Music', icon: Music },
];
const SHARE: RadialItem[] = [
  { label: 'Share', icon: Share2 },
  { label: 'Photo', icon: Camera },
  { label: 'Note', icon: FileText },
  { label: 'Voice', icon: Mic },
];

export function RadialMenuDemo() {
  const [last, setLast] = useState('Nothing yet');
  const wrap = (list: RadialItem[]) => list.map((it) => ({ ...it, onSelect: () => setLast(it.label) }));
  return (
    <div className="flex w-full flex-col items-center gap-6">
      <div className="grid w-full max-w-2xl gap-4 sm:grid-cols-2">
        <div className="relative grid h-72 place-items-center rounded-2xl bg-[#0b0c0e]/60 shadow-[0_0_0_1px_rgba(255,255,255,0.06)]">
          <RadialMenu items={wrap(CREATE)} label="Create" />
          <span className="absolute left-4 top-3 text-xs text-[#8b9099]">Full circle</span>
        </div>
        <div className="relative h-72 overflow-hidden rounded-2xl bg-[#0b0c0e]/60 shadow-[0_0_0_1px_rgba(255,255,255,0.06)]">
          <span className="absolute left-4 top-3 text-xs text-[#8b9099]">Corner</span>
          <div className="absolute bottom-5 right-5">
            <RadialMenu items={wrap(SHARE)} variant="corner" radius={108} label="Share" />
          </div>
        </div>
      </div>
      <p className="text-xs text-[#8b9099]">
        Last action: <span className="text-[#e5e7eb]">{last}</span> · Open a menu, then use the arrow keys and Esc.
      </p>
    </div>
  );
}
