import { useEffect, useMemo, useState } from 'react';
import { iconKindForTool, type ToolIconKind } from '../../lib/pets/toolIconMap';

function ToolIcon({ kind }: { kind: ToolIconKind }) {
  if (kind === 'search') {
    return <path d="M10.5 17a6.5 6.5 0 1 1 4.6-1.9L20 20" />;
  }
  if (kind === 'terminal') {
    return <path d="m5 7 4 4-4 4M11 17h8" />;
  }
  if (kind === 'file') {
    return <path d="M7 3h7l4 4v14H7zM14 3v5h5" />;
  }
  if (kind === 'edit') {
    return <path d="M4 20h4l11-11a2.8 2.8 0 0 0-4-4L4 16zM13 6l4 4" />;
  }
  if (kind === 'browser') {
    return <path d="M4 6h16v12H4zM4 9h16M7 7.5h.1M10 7.5h.1" />;
  }
  if (kind === 'issue') {
    return <path d="M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v5M12 16h.1" />;
  }
  if (kind === 'plug') {
    return <path d="M9 7V3M15 7V3M7 7h10v4a5 5 0 0 1-10 0zM12 16v5" />;
  }
  return <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" />;
}

// 4-point star particle path centered at (12, 12), radius ~8
const STAR_PATH = 'M12 3 L13.6 10.4 L21 12 L13.6 13.6 L12 21 L10.4 13.6 L3 12 L10.4 10.4 Z';

const PARTICLE_BASE: Array<{ size: number; delay: string; rotate: number; x: number; y: number }> = [
  { size: 10, delay: '0ms',   rotate: 0,   x: -6,  y: 0 },
  { size: 8,  delay: '40ms',  rotate: 25,  x: 8,   y: -2 },
  { size: 9,  delay: '90ms',  rotate: -20, x: -10, y: 2 },
  { size: 7,  delay: '150ms', rotate: 15,  x: 5,   y: 4 },
  { size: 11, delay: '210ms', rotate: 10,  x: 0,   y: -4 },
  { size: 9,  delay: '270ms', rotate: -10, x: 3,   y: 6 },
];

// Projection angle range: [85°, 95°] from horizontal — near-vertical with slight lean.
// cos(85°) ≈ 0.087 (rightward), cos(95°) ≈ -0.087 (leftward).
function randomLaunchVx(): number {
  const angleDeg = 85 + Math.random() * 10;
  return Math.cos((angleDeg * Math.PI) / 180);
}

export function ToolSpark({
  toolName,
  activityKey,
  enabled,
  reducedMotion,
}: {
  toolName: string | null;
  activityKey: string | null;
  enabled: boolean;
  reducedMotion: boolean;
}) {
  const [visibleTool, setVisibleTool] = useState<string | null>(null);
  const [animationToken, setAnimationToken] = useState(0);

  useEffect(() => {
    if (!enabled || !toolName) return;
    setVisibleTool(toolName);
    setAnimationToken(t => t + 1);
    // Bubble: 3000ms animation. Particles: 3000ms animation + up to 270ms
    // staggered delay. Hold ~30ms past the latest particle's fade-out so we
    // don't snap-cut the last one.
    const timer = window.setTimeout(() => setVisibleTool(null), 3300);
    return () => window.clearTimeout(timer);
  }, [enabled, toolName, activityKey]);

  const launchVelocities = useMemo(
    () => PARTICLE_BASE.map(() => randomLaunchVx()),
    // Re-randomize on each emission so successive sparkles don't look identical
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [animationToken],
  );

  if (!enabled || !visibleTool) return null;

  const kind = iconKindForTool(visibleTool);
  return (
    <div className="tool-spark-burst" key={animationToken} aria-hidden="true">
      <div className={`tool-spark-bubble ${reducedMotion ? 'tool-spark-reduced' : ''}`}>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <ToolIcon kind={kind} />
        </svg>
      </div>
      {!reducedMotion && PARTICLE_BASE.map((p, i) => (
        <span
          key={i}
          className="tool-spark-particle"
          style={{
            left: `calc(50% + ${p.x}px)`,
            top: `calc(50% + ${p.y}px)`,
            width: p.size,
            height: p.size,
            animationDelay: p.delay,
            ['--p-rot' as string]: `${p.rotate}deg`,
            ['--p-vx' as string]: (launchVelocities[i] ?? 0).toFixed(3),
          }}
        >
          <svg viewBox="0 0 24 24"><path d={STAR_PATH} /></svg>
        </span>
      ))}
    </div>
  );
}
