"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

interface BorderGlowProps extends React.HTMLAttributes<HTMLDivElement> {
  children: React.ReactNode;
  className?: string; // Appears on the inner content card
  wrapperClassName?: string; // Appears on the outer border glow container
  color?: string;
  borderWidth?: number;
  animatedIntro?: boolean;
}

export function BorderGlow({ 
  children, 
  className, 
  wrapperClassName, 
  color = "#8b5cf6",
  borderWidth = 2,
  animatedIntro = true,
  ...props
}: BorderGlowProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [mousePosition, setMousePosition] = useState({ x: -1000, y: -1000 });
  const [isHovering, setIsHovering] = useState(false);
  const introPlayedRef = useRef(false);

  useEffect(() => {
    let animationFrameId: number;
    let startTime: number;

    const animateIntro = (timestamp: number) => {
      if (!startTime) startTime = timestamp;
      const progress = Math.min((timestamp - startTime) / 2500, 1); // 2.5s perimeter trace
      
      if (containerRef.current && !introPlayedRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        
        let x = 0;
        let y = 0;
        
        // Trace the perimeter: Top -> Right -> Bottom -> Left
        if (progress < 0.25) {
          x = rect.width * (progress / 0.25);
          y = 0;
        } else if (progress < 0.5) {
          x = rect.width;
          y = rect.height * ((progress - 0.25) / 0.25);
        } else if (progress < 0.75) {
          x = rect.width * (1 - (progress - 0.5) / 0.25);
          y = rect.height;
        } else {
          x = 0;
          y = rect.height * (1 - (progress - 0.75) / 0.25);
        }
        
        setMousePosition({ x, y });
      }
      
      if (progress < 1 && !introPlayedRef.current) {
        animationFrameId = requestAnimationFrame(animateIntro);
      } else if (!introPlayedRef.current) {
        setIsHovering(false);
        introPlayedRef.current = true;
      }
    };

    if (animatedIntro) {
      setIsHovering(true);
      animationFrameId = requestAnimationFrame(animateIntro);
    }

    return () => {
      if (animationFrameId) cancelAnimationFrame(animationFrameId);
    };
  }, [animatedIntro]);

  useEffect(() => {
    const handlePointerMove = (e: PointerEvent) => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        // This math is absolute to the screen and client rect, completely safe from RTL weirdness
        setMousePosition({
          x: e.clientX - rect.left,
          y: e.clientY - rect.top,
        });
      }
    };

    const handlePointerEnter = () => {
      introPlayedRef.current = true;
      setIsHovering(true);
    };
    const handlePointerLeave = () => setIsHovering(false);

    const container = containerRef.current;
    if (container) {
      container.addEventListener("pointermove", handlePointerMove);
      container.addEventListener("pointerenter", handlePointerEnter);
      container.addEventListener("pointerleave", handlePointerLeave);
    }

    return () => {
      if (container) {
        container.removeEventListener("pointermove", handlePointerMove);
        container.removeEventListener("pointerenter", handlePointerEnter);
        container.removeEventListener("pointerleave", handlePointerLeave);
      }
    };
  }, []);

  return (
    <div
      ref={containerRef}
      className={cn("relative isolate rounded-3xl", wrapperClassName)}
      style={{ padding: `${borderWidth}px` }}
      {...props}
    >
      {/* Outer Ambient Glow (Spills out) */}
      <div 
        className={cn(
          "absolute inset-0 z-0 transition-opacity duration-500 ease-out pointer-events-none blur-xl",
          isHovering ? "opacity-60" : "opacity-0"
        )}
        style={{
          background: `radial-gradient(350px circle at ${mousePosition.x}px ${mousePosition.y}px, ${color}, transparent 50%)`
        }}
      />

      {/* Crisp 2px Inner Glow (Restricted to rounded border) */}
      <div className="absolute inset-0 overflow-hidden rounded-[inherit] pointer-events-none z-0">
        <div 
          className={cn(
            "absolute inset-0 transition-opacity duration-300 ease-out",
            isHovering ? "opacity-100" : "opacity-0"
          )}
          style={{
            background: `radial-gradient(350px circle at ${mousePosition.x}px ${mousePosition.y}px, ${color}, transparent 40%)`
          }}
        />
      </div>
      
      {/* Internal Wrapper (Covers center to reveal only the glowing border) */}
      <div className={cn("relative z-10 w-full h-full rounded-[calc(1.5rem-2px)] bg-background", className)}>
        {children}
      </div>
    </div>
  );
}
