import { motion, useScroll, useTransform, AnimatePresence } from "framer-motion";
import { Phone, Mail } from "lucide-react";
import { useLanguage } from "@/contexts/LanguageContext";
import { useRef, useEffect, useState, useCallback } from "react";
import isoLogo from "@/assets/iso-white.png";

const HeroSection = () => {
  const { t } = useLanguage();
  const ref = useRef<HTMLElement>(null);
  const videoRef1 = useRef<HTMLVideoElement>(null);
  const videoRef2 = useRef<HTMLVideoElement>(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start start", "end start"] });
  const bgY = useTransform(scrollYProgress, [0, 1], [0, 100]);
  const contentY = useTransform(scrollYProgress, [0, 1], [0, -60]);
  const overlayOpacity = useTransform(scrollYProgress, [0, 0.5], [0.4, 0.85]);

  const [mouse, setMouse] = useState({ x: 0, y: 0 });
  const [activeVideo, setActiveVideo] = useState<1 | 2>(1);

  const handleMouseMove = useCallback((e: MouseEvent) => {
    const x = (e.clientX / window.innerWidth - 0.5) * 2;
    const y = (e.clientY / window.innerHeight - 0.5) * 2;
    setMouse({ x, y });
  }, []);

  useEffect(() => {
    window.addEventListener("mousemove", handleMouseMove);
    return () => window.removeEventListener("mousemove", handleMouseMove);
  }, [handleMouseMove]);

  // Crossfade loop: when one video nears its end, fade to the other
  useEffect(() => {
    const checkLoop = () => {
      const current = activeVideo === 1 ? videoRef1.current : videoRef2.current;
      const next = activeVideo === 1 ? videoRef2.current : videoRef1.current;
      if (current && next && current.duration) {
        const timeLeft = current.duration - current.currentTime;
        if (timeLeft <= 1.5 && timeLeft > 0) {
          next.currentTime = 0;
          next.play().catch(() => {});
          setActiveVideo(activeVideo === 1 ? 2 : 1);
        }
      }
    };
    const interval = setInterval(checkLoop, 100);
    return () => clearInterval(interval);
  }, [activeVideo]);

  return (
    <section id="hero" ref={ref} className="relative min-h-screen flex items-center justify-center overflow-hidden">
      {/* Video Background — dual videos for crossfade loop */}
      <motion.div
        className="absolute inset-[-10%] will-change-transform"
        style={{ y: bgY, x: mouse.x * -8 }}
      >
        <video
          ref={videoRef1}
          autoPlay
          muted
          playsInline
          className="absolute inset-0 w-full h-full object-cover scale-110 transition-opacity duration-[1500ms]"
          style={{
            filter: "saturate(1.1) contrast(1.1) brightness(0.72)",
            opacity: activeVideo === 1 ? 1 : 0,
          }}
        >
          <source src="/video_hero.mp4" type="video/mp4" />
        </video>
        <video
          ref={videoRef2}
          muted
          playsInline
          className="absolute inset-0 w-full h-full object-cover scale-110 transition-opacity duration-[1500ms]"
          style={{
            filter: "saturate(1.1) contrast(1.1) brightness(0.72)",
            opacity: activeVideo === 2 ? 1 : 0,
          }}
        >
          <source src="/video_hero.mp4" type="video/mp4" />
        </video>
      </motion.div>

      {/* Primary gradient overlay — lighter to preserve video reds */}
      <motion.div className="absolute inset-0" style={{ opacity: overlayOpacity }}>
        <div className="absolute inset-0" style={{
          background: "linear-gradient(180deg, hsl(0 0% 0% / 0.25) 0%, hsl(0 0% 0% / 0.4) 40%, hsl(0 0% 3% / 0.85) 100%)",
        }} />
      </motion.div>

      {/* Red ambient glow — stronger */}
      <div className="absolute inset-0 pointer-events-none" style={{
        background: "radial-gradient(ellipse 90% 70% at 50% 35%, hsl(0 100% 50% / 0.1) 0%, hsl(0 100% 40% / 0.04) 40%, transparent 70%)",
      }} />

      {/* Secondary red accent from bottom */}
      <div className="absolute inset-0 pointer-events-none" style={{
        background: "radial-gradient(ellipse 70% 40% at 50% 90%, hsl(0 100% 50% / 0.06) 0%, transparent 70%)",
      }} />

      {/* Cinematic vignette — softer */}
      <div className="absolute inset-0 pointer-events-none" style={{
        background: "radial-gradient(ellipse 75% 65% at 50% 45%, transparent 20%, hsl(0 0% 0% / 0.5) 100%)",
      }} />

      {/* Horizontal light streak — premium anamorphic */}
      <motion.div
        className="absolute inset-0 pointer-events-none"
        animate={{ x: ["-120%", "280%"] }}
        transition={{ duration: 12, repeat: Infinity, repeatDelay: 10, ease: "easeInOut" }}
        style={{
          background: "linear-gradient(105deg, transparent 38%, hsl(0 100% 60% / 0.06) 45%, hsl(0 0% 100% / 0.09) 50%, hsl(0 100% 60% / 0.06) 55%, transparent 62%)",
        }}
      />

      {/* Secondary vertical light streak */}
      <motion.div
        className="absolute inset-0 pointer-events-none"
        animate={{ y: ["-80%", "200%"] }}
        transition={{ duration: 18, repeat: Infinity, repeatDelay: 6, ease: "easeInOut" }}
        style={{
          background: "linear-gradient(180deg, transparent 40%, hsl(0 0% 100% / 0.03) 49%, hsl(0 0% 100% / 0.05) 50%, hsl(0 0% 100% / 0.03) 51%, transparent 60%)",
        }}
      />

      {/* Atmospheric haze — mouse-reactive */}
      <motion.div
        className="absolute pointer-events-none"
        style={{
          width: "70%",
          height: "60%",
          left: "15%",
          top: "15%",
          background: "radial-gradient(circle, hsl(0 100% 50% / 0.05) 0%, hsl(0 100% 40% / 0.02) 40%, transparent 70%)",
          x: mouse.x * 20,
          y: mouse.y * 20,
        }}
      />

      {/* Volumetric light cone from top */}
      <div className="absolute inset-0 pointer-events-none" style={{
        background: "conic-gradient(from 180deg at 50% -10%, transparent 40%, hsl(0 0% 100% / 0.02) 48%, hsl(0 0% 100% / 0.04) 50%, hsl(0 0% 100% / 0.02) 52%, transparent 60%)",
      }} />

      {/* Noise texture */}
      <div className="absolute inset-0 pointer-events-none opacity-[0.025]" style={{
        backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='1'/%3E%3C/svg%3E")`,
        backgroundSize: "128px 128px",
      }} />

      {/* Edge glow lines — top */}
      <div className="absolute top-0 left-0 right-0 h-px pointer-events-none" style={{
        background: "linear-gradient(90deg, transparent 10%, hsl(0 100% 50% / 0.15) 50%, transparent 90%)",
      }} />

      {/* Content */}
      <motion.div style={{ y: contentY }} className="relative z-10 container mx-auto px-6 text-center pt-28 md:pt-32 lg:pt-36">
        {/* Premium Isologo — cinematic emblem */}
        <motion.div
          initial={{ opacity: 0, scale: 0.6, y: 40 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          transition={{ delay: 0.2, duration: 1.4, ease: [0.16, 1, 0.3, 1] }}
          className="mb-10 md:mb-14 relative inline-block"
        >
          {/* Deep outer glow */}
          <motion.div
            className="absolute inset-[-40px] md:inset-[-55px] rounded-full pointer-events-none"
            style={{
              background: "radial-gradient(circle, hsl(0 100% 50% / 0.18) 0%, hsl(0 100% 50% / 0.08) 30%, hsl(0 100% 50% / 0.03) 50%, transparent 70%)",
              x: mouse.x * -10,
              y: mouse.y * -10,
            }}
            animate={{ scale: [1, 1.12, 1], opacity: [0.8, 1, 0.8] }}
            transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
          />
          {/* Secondary halo ring */}
          <motion.div
            className="absolute inset-[-25px] md:inset-[-35px] rounded-full pointer-events-none"
            style={{
              border: "1px solid hsl(0 100% 50% / 0.08)",
              boxShadow: "0 0 40px hsl(0 100% 50% / 0.06), inset 0 0 30px hsl(0 100% 50% / 0.04)",
            }}
            animate={{ scale: [1, 1.06, 1], rotate: [0, 3, 0] }}
            transition={{ duration: 6, repeat: Infinity, ease: "easeInOut" }}
          />
          {/* Logo with enhanced effects — NO overflow-hidden */}
          <div className="relative">
            {/* Light sweep across logo */}
            <motion.div
              className="absolute inset-[-4px] pointer-events-none z-10 rounded-2xl overflow-hidden"
              style={{ clipPath: "inset(0)" }}
            >
              <motion.div
                className="absolute inset-0"
                animate={{ x: ["-200%", "300%"] }}
                transition={{ duration: 3.5, repeat: Infinity, repeatDelay: 6, ease: "easeInOut" }}
                style={{
                  background: "linear-gradient(110deg, transparent 25%, hsl(0 0% 100% / 0.2) 45%, hsl(0 0% 100% / 0.35) 50%, hsl(0 0% 100% / 0.2) 55%, transparent 75%)",
                }}
              />
            </motion.div>
            {/* Reflection / volumetric highlight underneath */}
            <div className="absolute inset-0 pointer-events-none z-0" style={{
              background: "linear-gradient(180deg, transparent 50%, hsl(0 0% 100% / 0.04) 100%)",
              borderRadius: "16px",
            }} />
            <motion.img
              src={isoLogo}
              alt="I Love Printing Corp"
              className="h-20 md:h-28 lg:h-32 w-auto mx-auto relative z-[1]"
              style={{
                filter: "drop-shadow(0 0 40px hsl(0 100% 50% / 0.35)) drop-shadow(0 0 80px hsl(0 100% 50% / 0.15)) drop-shadow(0 6px 24px hsl(0 0% 0% / 0.7))",
                x: mouse.x * 6,
                y: mouse.y * 6,
              }}
              animate={{ y: [0, -8, 0] }}
              transition={{ duration: 6, repeat: Infinity, ease: "easeInOut" }}
            />
          </div>
        </motion.div>

        {/* Eyebrow badge */}
        <motion.div
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.7, duration: 0.8 }}
          className="mb-7"
        >
          <span
            className="inline-block text-[10px] md:text-xs tracking-[0.28em] font-semibold text-foreground/90 border border-foreground/15 px-5 py-2.5 rounded-full backdrop-blur-xl"
            style={{
              background: "linear-gradient(135deg, hsl(0 0% 100% / 0.08), hsl(0 0% 100% / 0.03))",
              fontVariant: "small-caps",
              textShadow: "0 1px 6px hsl(0 0% 0% / 0.7)",
              boxShadow: "0 4px 20px hsl(0 0% 0% / 0.3), inset 0 1px 0 hsl(0 0% 100% / 0.06)",
            }}
          >
            {t("hero.badge")}
          </span>
        </motion.div>

        {/* Headline — two lines, "Solutions" balanced */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.9, duration: 1, ease: [0.16, 1, 0.3, 1] }}
          className="mb-7 max-w-4xl mx-auto"
        >
          <h1
            className="font-display font-semibold leading-[1.15] text-foreground tracking-wide"
            style={{ textShadow: "0 2px 30px hsl(0 100% 50% / 0.15), 0 4px 16px hsl(0 0% 0% / 0.6)" }}
          >
            <span className="block text-xl sm:text-2xl md:text-3xl lg:text-4xl xl:text-[2.6rem]">
              {t("hero.headline1")}
            </span>
            <span
              className="block mt-1 md:mt-2 text-xl sm:text-2xl md:text-3xl lg:text-4xl xl:text-[2.6rem] bg-gradient-to-r from-foreground via-foreground to-primary/80 bg-clip-text"
              style={{
                WebkitTextFillColor: "transparent",
              }}
            >
              {t("hero.headline2")}
            </span>
          </h1>
        </motion.div>

        {/* Subheadline */}
        <motion.p
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 1.1, duration: 0.8 }}
          className="font-body text-sm md:text-base lg:text-lg text-foreground/70 max-w-xl mx-auto mb-10 leading-relaxed font-light"
          style={{ textShadow: "0 1px 10px hsl(0 0% 0% / 0.7)" }}
        >
          {t("hero.subheadline")}
        </motion.p>

        {/* CTAs */}
        <motion.div
          initial={{ opacity: 0, y: 14 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 1.3, duration: 0.7 }}
          className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-8"
        >
          <a
            href="#contact"
            className="cta-button-primary flex items-center gap-2 text-sm"
            style={{ textTransform: "none", letterSpacing: "0.05em", boxShadow: "0 0 30px -6px hsl(0 100% 50% / 0.35), 0 4px 16px hsl(0 0% 0% / 0.4)" }}
          >
            <Mail className="w-4 h-4" />
            {t("hero.cta1")}
          </a>
          <a
            href="tel:+15162721560"
            className="cta-button-secondary flex items-center gap-2 backdrop-blur-sm text-sm"
            style={{ textTransform: "none", letterSpacing: "0.05em" }}
          >
            <Phone className="w-4 h-4" />
            {t("hero.cta2")}
          </a>
        </motion.div>

        {/* Contact info */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 1.5, duration: 0.8 }}
          className="flex flex-col sm:flex-row items-center justify-center gap-4 text-xs text-foreground/50 font-light tracking-wide"
        >
          <a href="tel:+15162721560" className="hover:text-primary transition-colors">
            +1 (516) 272-1560
          </a>
          <span className="hidden sm:block text-border">|</span>
          <a href="mailto:iloveprintingny@gmail.com" className="hover:text-primary transition-colors">
            iloveprintingny@gmail.com
          </a>
        </motion.div>
      </motion.div>

      {/* Scroll indicator */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 2.2, duration: 1 }}
        className="absolute bottom-8 left-1/2 -translate-x-1/2 z-10"
      >
        <motion.div
          animate={{ y: [0, 6, 0] }}
          transition={{ duration: 2.5, repeat: Infinity }}
          className="w-5 h-8 rounded-full border border-muted-foreground/20 flex justify-center pt-2"
        >
          <div className="w-0.5 h-1.5 rounded-full bg-primary/60" />
        </motion.div>
      </motion.div>
    </section>
  );
};

export default HeroSection;
