'use client';

import { useMemo } from 'react';
import { cn } from '@djangocfg/ui-core/lib';
import type { TourSpotlightProps } from '../types';

// CSS for SVG animations (injected once)
const SPOTLIGHT_STYLES = `
  @keyframes tour-spotlight-pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }
  @keyframes tour-spotlight-ring {
    0% { transform: scale(1); opacity: 0.8; }
    100% { transform: scale(1.15); opacity: 0; }
  }
  .tour-spotlight-rect {
    transition: x 300ms ease-out, y 300ms ease-out, width 300ms ease-out, height 300ms ease-out;
  }
  .tour-spotlight-border {
    transition: x 300ms ease-out, y 300ms ease-out, width 300ms ease-out, height 300ms ease-out;
  }
  .tour-spotlight-pulse {
    animation: tour-spotlight-pulse 2s ease-in-out infinite;
  }
`;

/**
 * SVG-based spotlight overlay that highlights target elements.
 * Uses mask technique to create cutouts for targets.
 * Supports animations, backdrop blur, and pulse ring effects.
 */
export function TourSpotlight({
  targets,
  opacity = 0.5,
  blur = 0,
  animated = true,
  pulseRing = false,
  className,
  onClick,
  allowInteraction = false,
}: TourSpotlightProps) {
  // Early return for no targets
  if (targets.length === 0) return null;

  // Prepare flags
  const hasBlur = blur > 0;

  // Prepare target rects with computed values
  const computedTargets = useMemo(() => {
    return targets.map((target, index) => {
      const x = target.rect.x - target.padding;
      const y = target.rect.y - target.padding;
      const width = target.rect.width + target.padding * 2;
      const height = target.rect.height + target.padding * 2;
      const rx = target.radius + 2;
      const centerX = target.rect.x + target.rect.width / 2;
      const centerY = target.rect.y + target.rect.height / 2;

      return {
        key: index,
        x,
        y,
        width,
        height,
        rx,
        ry: rx,
        transformOrigin: `${centerX}px ${centerY}px`,
      };
    });
  }, [targets]);

  // Prepare styles
  const svgClassName = cn('absolute inset-0 h-full w-full', className);
  const svgStyle = { pointerEvents: allowInteraction ? 'none' as const : 'auto' as const };

  const blurStyle = useMemo(() => {
    if (!hasBlur) return undefined;
    return {
      backdropFilter: `blur(${blur}px)`,
      WebkitBackdropFilter: `blur(${blur}px)`,
      mask: 'url(#tour-spotlight-mask-blur)',
      WebkitMask: 'url(#tour-spotlight-mask-blur)',
      pointerEvents: 'none' as const,
    };
  }, [hasBlur, blur]);

  const rectAnimatedClass = animated ? 'tour-spotlight-rect' : undefined;
  const overlayClass = animated ? 'transition-opacity duration-300' : undefined;

  return (
    <>
      {/* Inject styles for animations */}
      <style dangerouslySetInnerHTML={{ __html: SPOTLIGHT_STYLES }} />

      {/* Backdrop blur layer (separate from SVG for better performance) */}
      {hasBlur && (
        <div
          className="absolute inset-0 transition-all duration-300"
          style={blurStyle}
          aria-hidden="true"
        />
      )}

      <svg
        className={svgClassName}
        style={svgStyle}
        onClick={onClick}
        aria-hidden="true"
      >
        <defs>
          <mask id="tour-spotlight-mask">
            {/* White background - visible area */}
            <rect fill="white" width="100%" height="100%" />
            {/* Black cutouts - transparent area for targets */}
            {computedTargets.map((target) => (
              <rect
                key={target.key}
                fill="black"
                className={rectAnimatedClass}
                x={target.x}
                y={target.y}
                width={target.width}
                height={target.height}
                rx={target.rx}
                ry={target.ry}
              />
            ))}
          </mask>

          {/* Separate mask for blur */}
          {hasBlur && (
            <mask id="tour-spotlight-mask-blur">
              <rect fill="white" width="100%" height="100%" />
              {computedTargets.map((target) => (
                <rect
                  key={target.key}
                  fill="black"
                  className={rectAnimatedClass}
                  x={target.x}
                  y={target.y}
                  width={target.width}
                  height={target.height}
                  rx={target.rx}
                  ry={target.ry}
                />
              ))}
            </mask>
          )}
        </defs>

        {/* Overlay with mask */}
        <rect
          fill="black"
          fillOpacity={opacity}
          width="100%"
          height="100%"
          mask="url(#tour-spotlight-mask)"
          className={overlayClass}
        />

        {/* Pulse ring effect */}
        {pulseRing && computedTargets.map((target) => (
          <rect
            key={`pulse-${target.key}`}
            className="fill-none stroke-primary stroke-2"
            style={{
              transformOrigin: target.transformOrigin,
              animation: 'tour-spotlight-ring 1.5s ease-out infinite',
            }}
            x={target.x}
            y={target.y}
            width={target.width}
            height={target.height}
            rx={target.rx}
            ry={target.ry}
          />
        ))}

        {/* Border around targets */}
        {computedTargets.map((target) => (
          <rect
            key={`border-${target.key}`}
            className={cn(
              'fill-none stroke-primary stroke-2',
              animated && 'tour-spotlight-border'
            )}
            x={target.x}
            y={target.y}
            width={target.width}
            height={target.height}
            rx={target.rx}
            ry={target.ry}
          />
        ))}
      </svg>
    </>
  );
}
