'use client';

// Icon Cloud — NiceUI (MIT) · https://niceui.dev/c/effects/icon-cloud
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useEffect, useMemo, 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 Bell = niceIcon([["path",{"d":"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}],["path",{"d":"M10.3 21a1.94 1.94 0 0 0 3.4 0"}]]);
const Bot = niceIcon([["path",{"d":"M12 8V4H8"}],["rect",{"width":"16","height":"12","x":"4","y":"8","rx":"2"}],["path",{"d":"M2 14h2"}],["path",{"d":"M20 14h2"}],["path",{"d":"M15 13v2"}],["path",{"d":"M9 13v2"}]]);
const Box = niceIcon([["path",{"d":"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"}],["path",{"d":"m3.3 7 8.7 5 8.7-5"}],["path",{"d":"M12 22V12"}]]);
const Brush = niceIcon([["path",{"d":"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"}],["path",{"d":"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z"}]]);
const Calendar = niceIcon([["path",{"d":"M8 2v4"}],["path",{"d":"M16 2v4"}],["rect",{"width":"18","height":"18","x":"3","y":"4","rx":"2"}],["path",{"d":"M3 10h18"}]]);
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 Cloud = niceIcon([["path",{"d":"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"}]]);
const Code2 = niceIcon([["path",{"d":"m18 16 4-4-4-4"}],["path",{"d":"m6 8-4 4 4 4"}],["path",{"d":"m14.5 4-5 16"}]]);
const Compass = niceIcon([["path",{"d":"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z"}],["circle",{"cx":"12","cy":"12","r":"10"}]]);
const Cpu = niceIcon([["rect",{"width":"16","height":"16","x":"4","y":"4","rx":"2"}],["rect",{"width":"6","height":"6","x":"9","y":"9","rx":"1"}],["path",{"d":"M15 2v2"}],["path",{"d":"M15 20v2"}],["path",{"d":"M2 15h2"}],["path",{"d":"M2 9h2"}],["path",{"d":"M20 15h2"}],["path",{"d":"M20 9h2"}],["path",{"d":"M9 2v2"}],["path",{"d":"M9 20v2"}]]);
const Database = niceIcon([["ellipse",{"cx":"12","cy":"5","rx":"9","ry":"3"}],["path",{"d":"M3 5V19A9 3 0 0 0 21 19V5"}],["path",{"d":"M3 12A9 3 0 0 0 21 12"}]]);
const Feather = niceIcon([["path",{"d":"M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z"}],["path",{"d":"M16 8 2 22"}],["path",{"d":"M17.5 15H9"}]]);
const Flame = niceIcon([["path",{"d":"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"}]]);
const Gauge = niceIcon([["path",{"d":"m12 14 4-4"}],["path",{"d":"M3.34 19a10 10 0 1 1 17.32 0"}]]);
const Globe = niceIcon([["circle",{"cx":"12","cy":"12","r":"10"}],["path",{"d":"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{"d":"M2 12h20"}]]);
const Heart = niceIcon([["path",{"d":"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"}]]);
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 Key = niceIcon([["path",{"d":"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{"d":"m21 2-9.6 9.6"}],["circle",{"cx":"7.5","cy":"15.5","r":"5.5"}]]);
const Layers = niceIcon([["path",{"d":"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"}],["path",{"d":"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"}],["path",{"d":"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"}]]);
const Leaf = niceIcon([["path",{"d":"M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z"}],["path",{"d":"M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"}]]);
const Lock = niceIcon([["rect",{"width":"18","height":"11","x":"3","y":"11","rx":"2","ry":"2"}],["path",{"d":"M7 11V7a5 5 0 0 1 10 0v4"}]]);
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 Map = niceIcon([["path",{"d":"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z"}],["path",{"d":"M15 5.764v15"}],["path",{"d":"M9 3.236v15"}]]);
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 Moon = niceIcon([["path",{"d":"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"}]]);
const Music = niceIcon([["path",{"d":"M9 18V5l12-2v13"}],["circle",{"cx":"6","cy":"18","r":"3"}],["circle",{"cx":"18","cy":"16","r":"3"}]]);
const Palette = niceIcon([["circle",{"cx":"13.5","cy":"6.5","r":".5","fill":"currentColor"}],["circle",{"cx":"17.5","cy":"10.5","r":".5","fill":"currentColor"}],["circle",{"cx":"8.5","cy":"7.5","r":".5","fill":"currentColor"}],["circle",{"cx":"6.5","cy":"12.5","r":".5","fill":"currentColor"}],["path",{"d":"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"}]]);
const Rocket = niceIcon([["path",{"d":"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}],["path",{"d":"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}],["path",{"d":"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}],["path",{"d":"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"}]]);
const Search = niceIcon([["circle",{"cx":"11","cy":"11","r":"8"}],["path",{"d":"m21 21-4.3-4.3"}]]);
const Shield = niceIcon([["path",{"d":"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]]);
const Sparkles = niceIcon([["path",{"d":"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}],["path",{"d":"M20 3v4"}],["path",{"d":"M22 5h-4"}],["path",{"d":"M4 17v2"}],["path",{"d":"M5 18H3"}]]);
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 Sun = niceIcon([["circle",{"cx":"12","cy":"12","r":"4"}],["path",{"d":"M12 2v2"}],["path",{"d":"M12 20v2"}],["path",{"d":"m4.93 4.93 1.41 1.41"}],["path",{"d":"m17.66 17.66 1.41 1.41"}],["path",{"d":"M2 12h2"}],["path",{"d":"M20 12h2"}],["path",{"d":"m6.34 17.66-1.41 1.41"}],["path",{"d":"m19.07 4.93-1.41 1.41"}]]);
const Terminal = niceIcon([["polyline",{"points":"4 17 10 11 4 5"}],["line",{"x1":"12","x2":"20","y1":"19","y2":"19"}]]);
const Wand2 = niceIcon([["path",{"d":"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72"}],["path",{"d":"m14 7 3 3"}],["path",{"d":"M5 6v4"}],["path",{"d":"M19 14v4"}],["path",{"d":"M10 2v2"}],["path",{"d":"M7 8H3"}],["path",{"d":"M21 16h-4"}],["path",{"d":"M11 3H9"}]]);
const Zap = niceIcon([["path",{"d":"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]]);

// 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/effects/pointer/IconCloud.tsx ────────────────────
const ICONS: ComponentType<LucideProps>[] = [Bell, Bot, Box, Brush, Calendar, Camera, Cloud, Code2, Compass, Cpu, Database, Feather, Flame, Gauge, Globe, Heart, Image, Key, Layers, Leaf, Lock, Mail, Map, Mic, Moon, Music, Palette, Rocket, Search, Shield, Sparkles, Star, Sun, Terminal, Wand2, Zap];

export type IconCloudProps = {
  /** Icons or text tags to place on the sphere. Defaults to generic line icons. */
  items?: Array<ComponentType<LucideProps> | string>;
  /** Sphere size in px. */
  size?: number;
  /** Idle spin speed (radians per second). */
  speed?: number;
  className?: string;
};

/**
 * An interactive 3D icon cloud: items spread evenly on a sphere that spins on
 * its own, can be dragged in any direction, and highlights the item you hover.
 */
export function IconCloud({ items = ICONS, size = 320, speed = 0.35, className }: IconCloudProps) {
  const root = useRef<HTMLDivElement>(null);
  const nodes = useRef<Array<HTMLElement | null>>([]);
  const [hot, setHot] = useState<number | null>(null);
  const pts = useMemo(() => {
    const n = items.length;
    const ga = Math.PI * (3 - Math.sqrt(5));
    return items.map((_, i) => {
      const y = 1 - (i / (n - 1)) * 2;
      const r = Math.sqrt(1 - y * y);
      return { x: Math.cos(ga * i) * r, y, z: Math.sin(ga * i) * r };
    });
  }, [items]);

  useEffect(() => {
    const el = root.current;
    if (!el) return;
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    let ax = 0.3;
    let ay = 0;
    let vx = 0;
    let vy = speed / 60;
    let drag: { x: number; y: number } | null = null;
    let raf = 0;
    let visible = true;
    const R = size * 0.4;

    const down = (e: PointerEvent) => {
      drag = { x: e.clientX, y: e.clientY };
      el.setPointerCapture(e.pointerId);
    };
    const move = (e: PointerEvent) => {
      if (!drag) return;
      vy = (e.clientX - drag.x) * 0.004;
      vx = -(e.clientY - drag.y) * 0.004;
      drag = { x: e.clientX, y: e.clientY };
    };
    const up = () => (drag = null);
    const key = (e: KeyboardEvent) => {
      const k: Record<string, [number, number]> = { ArrowLeft: [0, -0.06], ArrowRight: [0, 0.06], ArrowUp: [0.06, 0], ArrowDown: [-0.06, 0] };
      if (k[e.key]) {
        e.preventDefault();
        vx = k[e.key][0];
        vy = k[e.key][1];
      }
    };
    el.addEventListener('pointerdown', down);
    el.addEventListener('pointermove', move);
    el.addEventListener('pointerup', up);
    el.addEventListener('pointercancel', up);
    el.addEventListener('keydown', key);
    const io = new IntersectionObserver(([e]) => {
      visible = e.isIntersecting;
      if (visible && !raf) raf = requestAnimationFrame(tick);
    });
    io.observe(el);

    function tick() {
      raf = 0;
      if (!visible) return;
      if (!drag) {
        vx += (0 - vx) * 0.03;
        vy += ((reduced ? 0 : speed / 60) - vy) * 0.03;
      }
      ax += vx;
      ay += vy;
      const cx = Math.cos(ax);
      const sx = Math.sin(ax);
      const cy = Math.cos(ay);
      const sy = Math.sin(ay);
      pts.forEach((p, i) => {
        const n = nodes.current[i];
        if (!n) return;
        const x1 = p.x * cy + p.z * sy;
        const z1 = -p.x * sy + p.z * cy;
        const y2 = p.y * cx - z1 * sx;
        const z2 = p.y * sx + z1 * cx;
        const depth = (z2 + 1) / 2;
        const s = 0.55 + depth * 0.6;
        n.style.transform = `translate(-50%, -50%) translate3d(${x1 * R}px, ${y2 * R}px, 0) scale(${s})`;
        n.style.opacity = String(0.18 + depth * 0.82);
        n.style.zIndex = String(Math.round(depth * 100));
        n.style.filter = depth < 0.35 ? `blur(${(0.35 - depth) * 4}px)` : 'none';
      });
      raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(raf);
      io.disconnect();
      el.removeEventListener('pointerdown', down);
      el.removeEventListener('pointermove', move);
      el.removeEventListener('pointerup', up);
      el.removeEventListener('pointercancel', up);
      el.removeEventListener('keydown', key);
    };
  }, [pts, size, speed]);

  return (
    <div
      ref={root}
      tabIndex={0}
      role="img"
      aria-label="Rotating cloud of icons. Drag or use the arrow keys to spin it."
      className={cn('focus-ring relative cursor-grab touch-none select-none rounded-full active:cursor-grabbing', className)}
      style={{ width: size, height: size }}
    >
      <div aria-hidden className="absolute inset-[12%] rounded-full bg-[#0ea5e9]/10 blur-3xl" />
      {items.map((Item, i) => (
        <span
          key={i}
          ref={(el) => (nodes.current[i] = el)}
          onPointerEnter={() => setHot(i)}
          onPointerLeave={() => setHot(null)}
          className={cn(
            'absolute left-1/2 top-1/2 grid place-items-center rounded-xl border transition-colors duration-200 will-change-transform',
            typeof Item === 'string' ? 'h-8 px-3 text-xs font-medium' : 'h-10 w-10',
            hot === i ? 'border-[#7dd3fc]/60 bg-[#7dd3fc]/15 text-[#e0f2fe] shadow-[0_0_24px_rgba(125,211,252,0.45)]' : 'border-white/10 bg-[#0b0c0e]/80 text-[#a3a8b0]',
          )}
        >
          {typeof Item === 'string' ? Item : <Item className="h-[18px] w-[18px]" strokeWidth={1.6} />}
        </span>
      ))}
    </div>
  );
}

const TAGS = ['React', 'Tailwind', 'Motion', 'TypeScript', 'Canvas', 'SVG', 'A11y', 'Dark mode', 'Hooks', 'Tokens', 'CSS', 'Vite', 'Charts', 'Forms', 'Agents', 'MCP', 'Shaders', 'Layout'];

export function IconCloudDemo() {
  const [mode, setMode] = useState<'icons' | 'tags'>('icons');
  return (
    <div className="flex flex-col items-center gap-4">
      <div className="flex gap-1 rounded-xl bg-[#0b0c0e] p-1 text-xs 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)]">
        {(['icons', 'tags'] as const).map((m) => (
          <button key={m} onClick={() => setMode(m)} aria-pressed={mode === m} className={cn('focus-ring rounded-lg px-3 py-1.5 capitalize transition-colors', mode === m ? 'bg-[#1c1e22] text-[#f3f4f6]' : 'text-[#8b9099] hover:text-[#c9cdd3]')}>
            {m}
          </button>
        ))}
      </div>
      <IconCloud key={mode} items={mode === 'icons' ? ICONS : TAGS} size={300} />
      <p className="text-xs text-[#6b7079]">Drag to spin · hover an item · arrow keys when focused</p>
    </div>
  );
}
