import { useRef, useCallback, useEffect } from "react";
import logoPixel from "@/assets/logo-pixel.png";
import { Instagram, ArrowDown } from "lucide-react";
import { motion } from "framer-motion";
import { useLang } from "@/contexts/LangContext";
import { useSiteSetting } from "@/hooks/useSiteSettings";
import LangToggle from "./LangToggle";
import Grid3DParallax from "./Grid3DParallax";
import CTALink from "./CTALink";


const HeroSection = () => {
  const { t } = useLang();
  const sectionRef = useRef<HTMLElement>(null);
  const orb1Ref = useRef<HTMLDivElement>(null);
  const orb2Ref = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const targetMouse = useRef({ x: 0, y: 0 });
  const smoothMouse = useRef({ x: 0, y: 0 });
  const rafId = useRef<number>(0);

  const handleMouseMove = useCallback((e: React.MouseEvent<HTMLElement>) => {
    const rect = sectionRef.current?.getBoundingClientRect();
    if (!rect) return;
    targetMouse.current = {
      x: ((e.clientX - rect.left) / rect.width - 0.5) * 2,
      y: ((e.clientY - rect.top) / rect.height - 0.5) * 2,
    };
  }, []);

  // Smooth lerp animation loop — writes to DOM directly to avoid React re-renders.
  useEffect(() => {
    const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
    const animate = () => {
      smoothMouse.current.x = lerp(smoothMouse.current.x, targetMouse.current.x, 0.04);
      smoothMouse.current.y = lerp(smoothMouse.current.y, targetMouse.current.y, 0.04);
      const { x, y } = smoothMouse.current;
      if (orb1Ref.current) {
        orb1Ref.current.style.transform = `translate3d(${x * 40}px, ${y * 30}px, 0)`;
      }
      if (orb2Ref.current) {
        orb2Ref.current.style.transform = `translate3d(${x * -25}px, ${y * -20}px, 0)`;
      }
      if (contentRef.current) {
        contentRef.current.style.transform = `translate3d(${x * -5}px, ${y * -4}px, 0)`;
      }
      rafId.current = requestAnimationFrame(animate);
    };
    rafId.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(rafId.current);
  }, []);

  const opacitySetting = useSiteSetting("hero_overlay_opacity");
  const overlayOpacity = opacitySetting ? parseInt(opacitySetting) / 100 : 0.85;

  return (
    <section
      ref={sectionRef}
      onMouseMove={handleMouseMove}
      className="relative min-h-[100svh] flex items-center justify-center overflow-hidden py-24 md:py-20"
    >
      {/* Navbar */}
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6 }}
        className="absolute top-0 left-0 right-0 z-20 px-6 py-5"
      >
        <div className="max-w-5xl mx-auto flex items-center justify-between">
          <img src={logoPixel} alt="Pixel Lab" className="h-8 md:h-12 w-auto" fetchPriority="high" decoding="async" />
          <div className="flex items-center gap-3">
            <LangToggle />
            <CTALink
              trackId="hero-contact-btn"
              trackLabel="Get a Quote"
              className="bg-primary text-primary-foreground font-bold text-xs md:text-sm px-4 md:px-5 py-2 md:py-2.5 rounded-lg hover:brightness-110 transition-all"
            >
              {t("Get a Quote", "Fale Conosco")}
            </CTALink>
          </div>
        </div>
      </motion.div>

      {/* Interactive 3D perspective grid — reacts to mouse + click */}
      <Grid3DParallax />

      {/* Ambient glow orbs — smooth mouse parallax (DOM-driven) */}
      <div
        ref={orb1Ref}
        className="absolute top-1/4 left-1/4 w-[300px] h-[300px] md:w-[500px] md:h-[500px] rounded-full bg-primary/6 blur-[120px] md:blur-[200px] pointer-events-none z-0 will-change-transform"
      />
      <div
        ref={orb2Ref}
        className="absolute bottom-1/3 right-1/4 w-[200px] h-[200px] md:w-[400px] md:h-[400px] rounded-full bg-accent/5 blur-[100px] md:blur-[180px] pointer-events-none z-0 will-change-transform"
      />

      {/* Content — smooth subtle parallax (DOM-driven) */}
      <div
        ref={contentRef}
        className="relative z-10 max-w-5xl mx-auto text-center section-padding will-change-transform"
      >
        {/* Lab badge */}
        <motion.div
          initial={{ opacity: 0, scale: 0.8 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="mb-6"
        >
          <span className="inline-flex items-center gap-2 text-primary text-xs font-semibold tracking-widest uppercase px-4 py-1.5 rounded-full border border-primary/30 bg-primary/5">
            <motion.span
              animate={{ opacity: [0.5, 1, 0.5] }}
              transition={{ duration: 2, repeat: Infinity }}
              className="w-2 h-2 rounded-full bg-primary"
            />
            {t("Digital Lab • AI-Powered Solutions", "Laboratório Digital • Soluções com IA")}
          </span>
        </motion.div>

        {/* Headline — bold cinematic manifesto */}
        <div className="mb-8">
          <motion.h1
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.8 }}
            className="font-heading text-[4.5rem] xs:text-[5rem] sm:text-7xl md:text-8xl lg:text-[8.5rem] leading-[0.9] tracking-[-0.045em]"
          >
            <motion.span
              initial={{ opacity: 0, y: 60, filter: "blur(12px)" }}
              animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
              transition={{ duration: 1, delay: 0.2, ease: [0.16, 1, 0.3, 1] }}
              className="block font-black text-foreground"
            >
              {t("Built different.", "Feito diferente.")}
            </motion.span>
            <motion.span
              initial={{ opacity: 0, y: 60, filter: "blur(12px)" }}
              animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
              transition={{ duration: 1, delay: 0.45, ease: [0.16, 1, 0.3, 1] }}
              className="block font-black italic"
              style={{
                backgroundImage:
                  "linear-gradient(110deg, hsl(var(--primary)) 0%, hsl(var(--foreground)) 35%, hsl(var(--primary)) 70%, hsl(var(--foreground)) 100%)",
                backgroundSize: "250% auto",
                WebkitBackgroundClip: "text",
                backgroundClip: "text",
                color: "transparent",
                animation: "shimmerSweep 6s linear infinite",
              }}
            >
              {t("Built faster.", "Feito mais rápido.")}
            </motion.span>
          </motion.h1>
        </div>

        <motion.p
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.7, delay: 0.85 }}
          className="text-muted-foreground text-lg md:text-2xl max-w-2xl mx-auto mb-10 leading-relaxed font-light"
        >
          {t(
            "Websites, brands and AI automation, shipped while others schedule meetings.",
            "Sites, marcas e automação com IA, entregues enquanto os outros marcam reunião."
          )}
        </motion.p>


        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.9 }}
          className="flex flex-col items-center gap-6"
        >
          <div className="flex flex-col sm:flex-row items-center gap-3 sm:gap-4">
            <CTALink
              trackId="hero-main-cta"
              trackLabel="Get a Custom Quote"
              className="relative inline-flex items-center gap-3 bg-primary text-primary-foreground font-bold text-base md:text-lg px-8 md:px-10 py-4 md:py-5 rounded-xl transition-all group hover:brightness-110"
            >
              <span className="relative z-10">{t("Get a Custom Quote", "Receber Orçamento")}</span>
              <span aria-hidden className="relative z-10 transition-transform group-hover:translate-x-1">→</span>
            </CTALink>
          </div>

          {/* Trust strip — pure conversion focus for US visitors */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 1.1, duration: 0.6 }}
            className="flex flex-wrap justify-center items-center gap-x-6 gap-y-2 text-xs md:text-sm text-muted-foreground/70"
          >
            <span className="inline-flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 rounded-full bg-primary" />
              {t("Live in days, not months", "No ar em dias, não meses")}
            </span>
            <span className="hidden sm:inline text-border">•</span>
            <span className="inline-flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 rounded-full bg-primary" />
              {t("US-based support", "Suporte nos EUA")}
            </span>
            <span className="hidden sm:inline text-border">•</span>
            <span className="inline-flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 rounded-full bg-primary" />
              {t("No long-term contracts", "Sem contratos longos")}
            </span>
          </motion.div>

          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 1.4, duration: 0.6 }}
            className="flex items-center gap-5 text-muted-foreground/50"
          >
            <a
              href="https://www.instagram.com/pixellabus"
              target="_blank"
              rel="noopener noreferrer"
              className="hover:text-primary transition-colors"
              aria-label="Instagram"
            >
              <Instagram className="w-5 h-5" />
            </a>
          </motion.div>

          {/* Scroll indicator — inline on mobile (below Instagram), fixed bottom on desktop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 2, duration: 0.8 }}
            className="md:hidden mt-2"
          >
            <motion.div
              animate={{ y: [0, 6, 0] }}
              transition={{ repeat: Infinity, duration: 2, ease: "easeInOut" }}
              className="flex flex-col items-center gap-1.5 text-muted-foreground/40"
            >
              <span className="text-[10px] uppercase tracking-[0.3em]">Scroll</span>
              <ArrowDown className="w-4 h-4" />
            </motion.div>
          </motion.div>
        </motion.div>

      </div>

      {/* Scroll indicator — desktop only, pinned to section bottom */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 2, duration: 0.8 }}
        className="hidden md:block absolute bottom-6 left-1/2 -translate-x-1/2 z-10 pointer-events-none"
      >
        <motion.div
          animate={{ y: [0, 8, 0] }}
          transition={{ repeat: Infinity, duration: 2, ease: "easeInOut" }}
          className="flex flex-col items-center gap-2 text-muted-foreground/30"
        >
          <span className="text-[10px] uppercase tracking-[0.3em]">Scroll</span>
          <ArrowDown className="w-4 h-4" />
        </motion.div>
      </motion.div>
    </section>
  );
};

export default HeroSection;
