import { splitProps, mergeProps, onMount, onCleanup, type Component } from 'solid-js';
import clsx from 'clsx';

interface DotGridProps {
  visible?: boolean;
  class?: string;
}

/**
 * Hexagonal dot-grid SVG overlay with dampened mouse parallax (WIN-04).
 * Z-index 0: behind panels and content.
 * pointer-events: none so it doesn't block interaction.
 * The grid "lags behind" the mouse with smooth dampened motion.
 */
export const DotGrid: Component<DotGridProps> = (rawProps) => {
  const props = mergeProps({ visible: true }, rawProps);
  const [local] = splitProps(props, ['visible', 'class']);

  let svgRef: SVGSVGElement | undefined;
  let targetX = 0;
  let targetY = 0;
  let currentX = 0;
  let currentY = 0;
  let rafId: number;

  const SENSITIVITY = 0.04; // 2x original for more movement
  const DAMPING = 0.06; // Lower = more lag behind mouse

  const handleMouseMove = (e: MouseEvent) => {
    const centerX = window.innerWidth / 2;
    const centerY = window.innerHeight / 2;
    targetX = (e.clientX - centerX) * SENSITIVITY;
    targetY = (e.clientY - centerY) * SENSITIVITY;
  };

  const animate = () => {
    currentX += (targetX - currentX) * DAMPING;
    currentY += (targetY - currentY) * DAMPING;
    if (svgRef) {
      svgRef.style.transform = `translate(${currentX}px, ${currentY}px)`;
    }
    rafId = requestAnimationFrame(animate);
  };

  onMount(() => {
    window.addEventListener('mousemove', handleMouseMove);
    rafId = requestAnimationFrame(animate);
  });

  onCleanup(() => {
    window.removeEventListener('mousemove', handleMouseMove);
    cancelAnimationFrame(rafId);
  });

  return (
    <svg
      ref={svgRef}
      class={clsx('hh-dotgrid-overlay', local.class)}
      width="100%"
      height="100%"
      style={{
        position: 'absolute',
        inset: '0',
        'pointer-events': 'none',
        'z-index': '0',
        'will-change': 'transform',
        opacity: local.visible ? '1' : '0',
        transition: 'opacity var(--hh-transition-slow)',
        color: 'var(--hh-color-primary)',
      }}
    >
      <defs>
        <pattern id="hex-dots" width="40" height="34.64" patternUnits="userSpaceOnUse">
          {/* Row 1 — wider spacing, larger dots */}
          <circle cx="10" cy="8.66" r="1.5" fill="currentColor" opacity="0.13" />
          <circle cx="30" cy="8.66" r="1.5" fill="currentColor" opacity="0.13" />
          {/* Row 2 (offset for hexagonal) */}
          <circle cx="0" cy="25.98" r="1.5" fill="currentColor" opacity="0.13" />
          <circle cx="20" cy="25.98" r="1.5" fill="currentColor" opacity="0.13" />
          <circle cx="40" cy="25.98" r="1.5" fill="currentColor" opacity="0.13" />
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#hex-dots)" />
    </svg>
  );
};
