import { useEffect, useRef } from "react";
import { motion, useAnimation, useInView } from "framer-motion";

interface FloatingPathProps {
  d: string;
  delay?: number;
  duration?: number;
  strokeWidth?: number;
  opacity?: number;
  color?: string;
}

const FloatingPath = ({
  d,
  delay = 0,
  duration = 20,
  strokeWidth = 0.6,
  opacity = 0.12,
  color = "hsl(0 0% 100%)",
}: FloatingPathProps) => (
  <motion.path
    d={d}
    fill="none"
    stroke={color}
    strokeWidth={strokeWidth}
    strokeLinecap="round"
    initial={{ pathLength: 0, opacity: 0 }}
    animate={{
      pathLength: [0, 1, 1, 0],
      opacity: [0, opacity, opacity, 0],
    }}
    transition={{
      duration,
      delay,
      repeat: Infinity,
      ease: "easeInOut",
      times: [0, 0.4, 0.6, 1],
    }}
  />
);

const paths = [
  // Large sweeping curves
  "M-100,300 C200,100 400,500 700,200 S1100,400 1400,250 S1700,100 2000,350",
  "M-50,500 C150,300 350,700 600,350 S900,600 1200,300 S1500,500 1800,250",
  "M2000,400 C1700,200 1400,600 1100,300 S800,500 500,200 S200,400 -100,250",
  "M-100,200 C100,400 300,100 550,350 S850,150 1100,400 S1400,200 1700,450",
  "M2000,550 C1800,300 1500,500 1200,250 S900,450 600,200 S300,400 0,300",
  // Mid-range flowing lines
  "M-50,450 C200,250 450,550 700,300 S1000,500 1300,250",
  "M2000,350 C1700,500 1400,200 1100,450 S800,250 500,400",
  "M-100,150 C150,350 400,100 650,400 S950,200 1250,450 S1550,300 1850,500",
  // Subtle accent paths
  "M300,600 C500,400 700,550 900,350 S1100,500 1300,300 S1500,450 1700,250",
  "M-50,350 C200,500 450,200 700,450 S950,300 1200,500",
];

export function BackgroundPaths() {
  const ref = useRef<HTMLDivElement>(null);
  const isInView = useInView(ref, { once: false, amount: 0.2 });
  const controls = useAnimation();

  useEffect(() => {
    if (isInView) {
      controls.start("visible");
    }
  }, [isInView, controls]);

  return (
    <div ref={ref} className="absolute inset-0 overflow-hidden pointer-events-none">
      {/* SVG Path Canvas */}
      <svg
        className="absolute inset-0 w-full h-full"
        viewBox="0 0 1920 800"
        preserveAspectRatio="xMidYMid slice"
        xmlns="http://www.w3.org/2000/svg"
      >
        {paths.map((d, i) => (
          <FloatingPath
            key={i}
            d={d}
            delay={i * 1.8}
            duration={18 + i * 2.5}
            strokeWidth={0.4 + (i % 3) * 0.3}
            opacity={0.06 + (i % 4) * 0.025}
            color={
              i % 5 === 0
                ? "hsl(0 80% 55% / 0.4)"
                : "hsl(0 0% 100%)"
            }
          />
        ))}
      </svg>

      {/* Radial glow behind center */}
      <div
        className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[900px] h-[600px]"
        style={{
          background:
            "radial-gradient(ellipse, hsl(0 100% 50% / 0.05) 0%, hsl(0 100% 40% / 0.02) 40%, transparent 70%)",
        }}
      />
    </div>
  );
}
