import { useState, useEffect, useRef } from "react";
import { useLocation } from "wouter";
import { Button } from "@/components/ui/button";
import { ArrowRight, DollarSign, IndianRupee } from "lucide-react";
import heroVideo from "@assets/generated_videos/abstract_finance_visualization_video.mp4";
import StrategySelectorModal from "./StrategySelectorModal";

type HeroSectionProps = {
  onExploreStrategies: () => void;
};

export default function HeroSection({ onExploreStrategies }: HeroSectionProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [isLoaded, setIsLoaded] = useState(false);
  const [scrollY, setScrollY] = useState(0);
  const [isCompactViewport, setIsCompactViewport] = useState(false);
  const [, navigate] = useLocation();

  useEffect(() => {
    setIsLoaded(true);
  }, []);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(max-width: 639px)");
    const updateViewportMode = () => setIsCompactViewport(mediaQuery.matches);
    updateViewportMode();

    if (mediaQuery.addEventListener) {
      mediaQuery.addEventListener("change", updateViewportMode);
      return () => mediaQuery.removeEventListener("change", updateViewportMode);
    }

    mediaQuery.addListener(updateViewportMode);
    return () => mediaQuery.removeListener(updateViewportMode);
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    if (isCompactViewport) {
      setMousePosition({ x: 0, y: 0 });
      return;
    }
    const handleMouseMove = (e: MouseEvent) => {
      if (!containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const x = (e.clientX - rect.left - rect.width / 2) / rect.width;
      const y = (e.clientY - rect.top - rect.height / 2) / rect.height;
      setMousePosition({ x: x * 30, y: y * 30 });
    };

    const container = containerRef.current;
    container?.addEventListener("mousemove", handleMouseMove);
    return () => container?.removeEventListener("mousemove", handleMouseMove);
  }, [isCompactViewport]);

  const parallaxY = isCompactViewport ? scrollY * 0.18 : scrollY * 0.5;
  const videoScale = 1 + scrollY * (isCompactViewport ? 0.00012 : 0.0003);
  const videoOpacity = Math.max((isCompactViewport ? 0.3 : 0.4) - scrollY * 0.0005, 0.15);
  const particleCount = isCompactViewport ? 10 : 25;

  return (
    <section
      ref={containerRef}
      className="relative flex min-h-[100svh] items-center justify-center overflow-hidden px-4 sm:px-0"
      data-testid="section-hero"
      style={{ perspective: "1000px" }}
    >
      <div 
        className="absolute inset-0 z-0"
        style={{
          transform: `translateY(${parallaxY}px) scale(${videoScale})`,
          transformOrigin: "center center",
        }}
      >
        <video
          autoPlay
          loop
          muted
          playsInline
          className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ${
            isLoaded ? "opacity-100" : "opacity-0"
          }`}
          style={{ 
            opacity: videoOpacity,
            filter: "blur(1px) saturate(0.8)",
          }}
        >
          <source src={heroVideo} type="video/mp4" />
        </video>
        <div className="absolute inset-0 bg-gradient-to-b from-background/70 via-background/50 to-background" />
      </div>

      <div
        className="absolute inset-0 transition-transform duration-300 ease-out z-10"
        style={{
          transform: `translate3d(${mousePosition.x * 0.3}px, ${mousePosition.y * 0.3}px, 0) rotateX(${mousePosition.y * 0.02}deg) rotateY(${-mousePosition.x * 0.02}deg)`,
          transformStyle: "preserve-3d",
        }}
      >
        <div 
          className={`absolute left-[12%] top-[18%] h-56 w-56 rounded-full bg-primary/20 blur-3xl transition-all duration-1000 sm:top-1/4 sm:left-1/4 sm:h-96 sm:w-96 ${
            isLoaded ? "opacity-100 scale-100" : "opacity-0 scale-50"
          }`}
          style={{ 
            transform: `translateZ(50px)`,
          }}
        />
        <div 
          className={`absolute bottom-[18%] right-[8%] h-48 w-48 rounded-full bg-chart-2/20 blur-3xl transition-all duration-1000 delay-200 sm:bottom-1/3 sm:right-1/4 sm:h-80 sm:w-80 ${
            isLoaded ? "opacity-100 scale-100" : "opacity-0 scale-50"
          }`}
          style={{ 
            transform: `translateZ(30px)`,
          }}
        />
        <div 
          className={`absolute right-[10%] top-[46%] h-40 w-40 rounded-full bg-chart-3/15 blur-3xl transition-all duration-1000 delay-500 sm:top-1/2 sm:right-1/3 sm:h-64 sm:w-64 ${
            isLoaded ? "opacity-100 scale-100" : "opacity-0 scale-50"
          }`}
          style={{ 
            transform: `translateZ(70px)`,
          }}
        />
      </div>

      <div className="absolute inset-0 overflow-hidden z-10">
        {[...Array(particleCount)].map((_, i) => (
          <div
            key={i}
            className={`absolute rounded-full transition-all duration-700 ${
              isLoaded ? "opacity-60" : "opacity-0"
            }`}
            style={{
              width: `${3 + (i % 4) * 2}px`,
              height: `${3 + (i % 4) * 2}px`,
              left: `${5 + (i * 3.8)}%`,
              top: `${15 + Math.sin(i * 0.7) * 35}%`,
              background: i % 3 === 0 
                ? "hsl(var(--primary))" 
                : i % 3 === 1 
                  ? "hsl(var(--chart-2))" 
                  : "hsl(var(--chart-3))",
              transform: `translate3d(${mousePosition.x * (0.5 + i * 0.08)}px, ${mousePosition.y * (0.5 + i * 0.08)}px, ${i * 5}px)`,
              transitionDelay: `${i * 30}ms`,
              animation: `float-3d ${4 + (i % 4)}s ease-in-out infinite`,
              animationDelay: `${i * 0.15}s`,
            }}
          />
        ))}
      </div>

      <div 
        className="absolute inset-0 z-10 pointer-events-none"
        style={{
          transform: `translate3d(${mousePosition.x * 0.1}px, ${mousePosition.y * 0.1}px, 0)`,
        }}
      >
        <div 
          className={`absolute left-[8%] top-24 h-12 w-12 transition-all duration-1000 sm:top-20 sm:left-[15%] sm:h-20 sm:w-20 ${
            isLoaded ? "opacity-100 rotate-12" : "opacity-0 rotate-0"
          }`}
          style={{
            transform: `rotate(${12 + mousePosition.x * 0.3}deg) translateZ(100px)`,
            animation: "float-rotate 8s ease-in-out infinite",
          }}
          aria-hidden="true"
        >
          <DollarSign className="w-full h-full text-primary/25 drop-shadow-sm" strokeWidth={1.25} />
        </div>
        <div 
          className={`absolute bottom-28 right-[12%] h-10 w-10 transition-all duration-1000 delay-300 sm:bottom-32 sm:right-[20%] sm:h-16 sm:w-16 ${
            isLoaded ? "opacity-100" : "opacity-0"
          }`}
          style={{
            transform: `translateZ(80px)`,
            animation: "pulse-float 6s ease-in-out infinite",
          }}
          aria-hidden="true"
        >
          <IndianRupee className="w-full h-full text-chart-2/25 drop-shadow-sm" strokeWidth={1.25} />
        </div>
        <div 
          className={`absolute right-[10%] top-[28%] h-8 w-8 transition-all duration-1000 delay-500 sm:top-1/3 sm:h-12 sm:w-12 ${
            isLoaded ? "opacity-100 rotate-45" : "opacity-0 rotate-0"
          }`}
          style={{
            transform: `rotate(${45 + mousePosition.y * 0.5}deg) translateZ(60px)`,
            animation: "float-rotate-reverse 10s ease-in-out infinite",
          }}
          aria-hidden="true"
        >
          <DollarSign className="w-full h-full text-chart-3/25 drop-shadow-sm" strokeWidth={1.25} />
        </div>
      </div>

      <div 
        className="relative z-20 mx-auto max-w-4xl px-4 text-center sm:px-6"
        style={{
          transform: `translate3d(${mousePosition.x * 0.15}px, ${mousePosition.y * 0.15}px, 100px)`,
          transformStyle: "preserve-3d",
        }}
      >
        <div
          className={`transition-all duration-1000 delay-300 ${
            isLoaded ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
          }`}
        >
          <h1
            className="mb-6 text-4xl font-bold leading-tight tracking-tight sm:text-5xl md:text-7xl"
            data-testid="text-hero-headline"
            style={{ transform: "translateZ(20px)" }}
          >
            <span className="inline-block animate-fade-in-up" style={{ animationDelay: "0.4s" }}>
              Invest with
            </span>
            <br />
            <span 
              className="text-primary inline-block animate-fade-in-up bg-clip-text"
              style={{ 
                animationDelay: "0.6s",
                textShadow: "0 0 60px hsl(var(--primary) / 0.3)",
              }}
            >
              Clarity
            </span>
          </h1>
        </div>
        
        <p
          className={`mx-auto mb-10 max-w-2xl text-base leading-relaxed text-muted-foreground transition-all duration-1000 delay-700 sm:mb-12 sm:text-lg md:text-2xl ${
            isLoaded ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
          }`}
          data-testid="text-hero-subheadline"
          style={{ transform: "translateZ(10px)" }}
        >
          Simple, disciplined strategies for long-term wealth building.
          No noise. Just steady growth. 
        </p>
        
        <div 
          className={`flex flex-col items-stretch justify-center gap-4 transition-all duration-1000 delay-1000 sm:flex-row sm:items-center ${
            isLoaded ? "opacity-100 translate-y-0" : "opacity-0 translate-y-8"
          }`}
          style={{ transform: "translateZ(30px)" }}
        >
          <Button
            size="lg"
            className="group relative mx-auto w-full max-w-[20rem] overflow-hidden rounded-xl px-6 py-5 text-base shadow-lg shadow-primary/20 sm:max-w-none sm:px-8 sm:py-6 sm:text-lg"
            data-testid="button-explore-strategies"
            onClick={onExploreStrategies}
          >
            <span className="relative z-10 flex items-center">
              Explore Strategies
              <ArrowRight className="ml-2 h-5 w-5 transition-transform group-hover:translate-x-1" />
            </span>
            <div className="absolute inset-0 bg-gradient-to-r from-primary to-chart-1 opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
          </Button>
          <Button
            variant="ghost"
            size="lg"
            className="mx-auto w-full max-w-[20rem] rounded-xl px-6 py-5 text-base text-muted-foreground backdrop-blur-sm sm:max-w-none sm:px-8 sm:py-6 sm:text-lg"
            data-testid="button-learn-more"
            onClick={() => navigate("/learn-more")}
          >
            Learn More Test
          </Button>
        </div>
      </div>

      <div 
        className={`absolute bottom-8 left-1/2 z-20 hidden -translate-x-1/2 transition-all duration-1000 delay-1500 sm:block ${
          isLoaded ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
        }`}
      >
        <div className="w-6 h-10 border-2 border-muted-foreground/30 rounded-full flex justify-center pt-2 backdrop-blur-sm">
          <div className="w-1.5 h-3 bg-muted-foreground/50 rounded-full animate-bounce" />
        </div>
      </div>

      <style>{`
        @keyframes float-3d {
          0%, 100% { transform: translateY(0px) translateZ(0px); }
          50% { transform: translateY(-15px) translateZ(10px); }
        }
        @keyframes fade-in-up {
          from { opacity: 0; transform: translateY(20px) translateZ(0); }
          to { opacity: 1; transform: translateY(0) translateZ(20px); }
        }
        @keyframes float-rotate {
          0%, 100% { transform: rotate(12deg) translateY(0) translateZ(100px); }
          50% { transform: rotate(18deg) translateY(-20px) translateZ(120px); }
        }
        @keyframes float-rotate-reverse {
          0%, 100% { transform: rotate(45deg) translateY(0) translateZ(60px); }
          50% { transform: rotate(35deg) translateY(-15px) translateZ(80px); }
        }
        @keyframes pulse-float {
          0%, 100% { transform: scale(1) translateY(0) translateZ(80px); opacity: 0.6; }
          50% { transform: scale(1.1) translateY(-10px) translateZ(100px); opacity: 0.8; }
        }
        .animate-fade-in-up {
          animation: fade-in-up 0.8s ease-out forwards;
          opacity: 0;
        }
      `}</style>
    </section>
  );
}
