import { createFileRoute } from "@tanstack/react-router";
import { ArrowUpRight, Instagram, Users, Target, Building, Zap, Cpu, MousePointer2, ExternalLink, Globe, Layers, Power } from "lucide-react";
import { motion, useScroll, useSpring, useTransform, AnimatePresence, useMotionValue } from "framer-motion";
import useSound from "use-sound";
import { useEffect, useState, useRef, useMemo, useCallback } from "react";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Riot Crash | Digital Futurist & Ecosystem Architect" },
      { name: "description", content: "Construindo o futuro através de ecossistemas digitais, I.A. e automação avançada." },
      { property: "og:title", content: "Riot Crash" },
      { property: "og:description", content: "Digital Ecosystems • AI • Future Tech" },
    ],
  }),
  component: Index,
});

function Index() {
  const { scrollYProgress } = useScroll();
  const scaleX = useSpring(scrollYProgress, {
    stiffness: 100,
    damping: 30,
    restDelta: 0.001
  });

  const mouseX = useMotionValue(0);
  const mouseY = useMotionValue(0);
  const [isHovering, setIsHovering] = useState(false);
  const [hoveredBgImage, setHoveredBgImage] = useState<string | null>(null);
  
  // Obscure image URLs to make them harder to find via static analysis or extensions
  const getImageUrl = (id: string) => {
    const images: Record<string, string> = {
      "ultra": "https://i.imgur.com/" + "ih2i0HN.png",
      "cloaker": "https://i.imgur.com/13xt2gg.png",
      "keys": "https://i.imgur.com/" + "9ueyJSk.png",
      "market": "https://i.imgur.com/" + "qaoLPEO.png",
      "insta": "https://i.imgur.com/" + "Jhk8vbo.png",
      "profile": "https://i.imgur.com/" + "JKq7D8U.jpeg"
    };
    return images[id] || "";
  };

  const containerRef = useRef<HTMLDivElement>(null);
  
  const [displayText, setDisplayText] = useState("");
  const fullText = "Múltiplos 8D faturados desde 2019 escalando operações black, white e infraestruturas complexas.";

  useEffect(() => {
    let currentText = "";
    let index = 0;
    const intervalId = setInterval(() => {
      if (index < fullText.length) {
        currentText += fullText[index];
        setDisplayText(currentText);
        index++;
      } else {
        clearInterval(intervalId);
      }
    }, 40); // Velocidade da digitação
    return () => clearInterval(intervalId);
  }, [fullText]);


  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      mouseX.set(e.clientX);
      mouseY.set(e.clientY);
    };

    const handleContextMenu = (e: MouseEvent) => {
      e.preventDefault();
    };

    const handleKeyDown = (e: KeyboardEvent) => {
      // Bloquear F12, Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+U
      if (
        e.key === "F12" ||
        (e.ctrlKey && e.shiftKey && (e.key === "I" || e.key === "J" || e.key === "C")) ||
        (e.ctrlKey && e.key === "u")
      ) {
        e.preventDefault();
        return false;
      }
    };

    const handleDragStart = (e: DragEvent) => {
      e.preventDefault();
    };

    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("contextmenu", handleContextMenu);
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("dragstart", handleDragStart);

    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("contextmenu", handleContextMenu);
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("dragstart", handleDragStart);
    };
  }, [mouseX, mouseY]);

  const particles = useMemo(() => {
    return Array.from({ length: 20 }).map((_, i) => ({
      id: i,
      size: Math.random() * 2 + 1,
      x: Math.random() * 100,
      y: Math.random() * 100,
      duration: Math.random() * 20 + 10,
    }));
  }, []);

  return (
    <div 
      ref={containerRef}
      className="min-h-screen bg-[#050505] text-white flex flex-col items-center px-6 py-12 relative overflow-hidden selection:bg-white selection:text-black cursor-none select-none" 
      style={{ fontFamily: "'Cinzel', serif" }}
      onMouseEnter={() => setIsHovering(true)}
      onMouseLeave={() => setIsHovering(false)}
    >
      {/* Hover Background Image for the whole site */}
      <AnimatePresence>
        {hoveredBgImage && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.8 }}
            className="fixed inset-0 z-0 pointer-events-none"
            style={{
              backgroundImage: `url(${hoveredBgImage})`,
              backgroundSize: hoveredBgImage?.includes("13xt2gg") ? '100% 100%' : 'cover',
              backgroundPosition: 'center',
              filter: 'grayscale(0) brightness(0.6)'

            }}
          >
            <div className="absolute inset-0 bg-black/60" />
          </motion.div>
        )}
      </AnimatePresence>

      {/* Dynamic Cursor */}
      <motion.div
        className="fixed top-0 left-0 w-12 h-12 border border-white/30 rounded-full pointer-events-none z-[100] flex items-center justify-center backdrop-blur-[2px]"
        style={{
          x: mouseX,
          y: mouseY,
          translateX: "-50%",
          translateY: "-50%",
        }}
        animate={{
          scale: isHovering ? 1.8 : 1,
          borderColor: isHovering ? "rgba(255,255,255,0.8)" : "rgba(255,255,255,0.3)",
        }}
        transition={{ type: "spring", damping: 20, stiffness: 250, mass: 0.5 }}
      >
        <motion.div 
          animate={{ scale: isHovering ? 0.5 : 1 }}
          className="w-1.5 h-1.5 bg-white rounded-full shadow-[0_0_10px_rgba(255,255,255,0.8)]" 
        />
      </motion.div>

      {/* Background Particles */}
      <div className="absolute inset-0 pointer-events-none z-0">
        {particles.map((p) => (
          <motion.div
            key={p.id}
            className="absolute bg-white/20 rounded-full blur-[1px]"
            style={{
              width: p.size,
              height: p.size,
              left: `${p.x}%`,
              top: `${p.y}%`,
            }}
            animate={{
              y: [0, -100, 0],
              opacity: [0.1, 0.5, 0.1],
            }}
            transition={{
              duration: p.duration,
              repeat: Infinity,
              ease: "linear",
            }}
          />
        ))}
      </div>

      {/* Cyber Grid Background with perspective */}
      <div className="absolute inset-0 z-0 opacity-[0.05] pointer-events-none" 
        style={{ 
          backgroundImage: `linear-gradient(rgba(255,255,255,0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.1) 1px, transparent 1px)`,
          backgroundSize: '40px 40px',
          perspective: '1000px',
          transform: 'rotateX(20deg) scale(1.2)',
          transformOrigin: 'top'
        }} 
      />

      {/* Interactive Cursor Glow - Optimized */}
      <motion.div
        className="fixed top-0 left-0 w-[600px] h-[600px] bg-blue-500/10 rounded-full blur-[120px] pointer-events-none z-0"
        style={{
          x: mouseX,
          y: mouseY,
          translateX: "-50%",
          translateY: "-50%",
        }}
        animate={{
          opacity: isHovering ? 1 : 0.4
        }}
      />

      {/* Progress Bar */}
      <motion.div
        className="fixed top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-blue-500 via-white to-purple-500 origin-left z-50"
        style={{ scaleX }}
      />

      {/* Profile Section */}
      <motion.div 
        initial={{ opacity: 0, y: 40 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 1.5, ease: [0.16, 1, 0.3, 1] }}
        className="mb-16 flex flex-col items-center relative z-10"
      >
        <div className="relative group mb-12">
          <motion.div 
            whileHover={{ scale: 1.02 }}
            className="w-44 h-60 overflow-hidden rounded-2xl border border-white/20 shadow-[0_0_80px_rgba(255,255,255,0.08)] cursor-none relative z-10 bg-black"
          >
            <img
              src={getImageUrl("profile")}
              alt="Riot Crash"
              className="w-full h-full object-cover grayscale brightness-90 group-hover:grayscale-0 group-hover:brightness-110 transition-all duration-1000 ease-in-out pointer-events-none select-none"
              onError={(e) => {
                e.currentTarget.src = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?q=80&w=300&auto=format&fit=crop";
              }}
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-40" />
          </motion.div>
          
          {/* Animated rings around profile */}
          <motion.div 
            animate={{ rotate: 360 }}
            transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
            className="absolute -inset-4 border border-white/5 rounded-[2.5rem] pointer-events-none"
          />
          <motion.div 
            animate={{ rotate: -360 }}
            transition={{ duration: 25, repeat: Infinity, ease: "linear" }}
            className="absolute -inset-8 border border-white/5 rounded-[3rem] pointer-events-none"
          />
        </div>
        
        <motion.div className="relative">
          <motion.h1 
            initial={{ y: 20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.2, duration: 1 }}
            className="text-6xl md:text-9xl font-black mb-2 text-center tracking-tighter bg-clip-text text-transparent bg-gradient-to-b from-white via-white/90 to-white/10"
          >
            RIOT CRASH
          </motion.h1>
          <motion.div 
            initial={{ width: 0 }}
            animate={{ width: "100%" }}
            transition={{ delay: 1, duration: 1.5 }}
            className="h-[1px] bg-gradient-to-r from-transparent via-white/30 to-transparent mb-6"
          />
        </motion.div>
        

        <motion.p 
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="max-w-xl text-center text-sm md:text-lg text-white/50 font-light leading-relaxed px-6 tracking-wide min-h-[4rem] italic"
        >
          {displayText}
          <motion.span
            animate={{ opacity: [0, 1, 0] }}
            transition={{ duration: 0.8, repeat: Infinity }}
            className="inline-block w-[2px] h-[1em] bg-blue-500 ml-1 align-middle"
          />
        </motion.p>
      </motion.div>

      {/* Links Section */}
      <div className="w-full max-w-3xl space-y-4 mb-20 relative z-10">
        <LinkCard
          icon={<Cpu className="w-5 h-5" />}
          title="GRUPO ULTRA PRIVADO"
          subtitle="GRUPO aaa111 8 digito +"
          href="https://checkout.transacaoprotegida.com/3b05c20e-1a20-4a7f-88ca-0c0a510a9eac"
          color="hover:border-blue-500/40 hover:bg-blue-500/5 shadow-[inset_0_0_20px_rgba(59,130,246,0)] hover:shadow-[inset_0_0_20px_rgba(59,130,246,0.1)]"
          onHoverChange={(isHovered) => setHoveredBgImage(isHovered ? getImageUrl("ultra") : null)}
        />
        <LinkCard
          icon={<Target className="w-5 h-5" />}
          title="Obycloaker"
          subtitle="melhor cloaker e camuflador pra escala ! topo de funil passa longe disso"
          href="https://obycloaker.com/"
          color="hover:border-purple-500/40 hover:bg-purple-500/5 shadow-[inset_0_0_20px_rgba(168,85,247,0)] hover:shadow-[inset_0_0_20px_rgba(168,85,247,0.1)]"
          onHoverChange={(isHovered) => setHoveredBgImage(isHovered ? getImageUrl("cloaker") : null)}

        />
        <LinkCard
          icon={<Zap className="w-5 h-5" />}
          title="ObyKeys"
          subtitle="Fornecedor de Keys Steam !"
          href="https://obykeys.com/"
          color="hover:border-pink-500/40 hover:bg-pink-500/5 shadow-[inset_0_0_20px_rgba(236,72,153,0)] hover:shadow-[inset_0_0_20px_rgba(236,72,153,0.1)]"
          onHoverChange={(isHovered) => setHoveredBgImage(isHovered ? getImageUrl("keys") : null)}
        />
        <LinkCard
          icon={<Globe className="w-5 h-5" />}
          title="Obymarket"
          subtitle="fornecedor de contas full acesso de valorant, league of legends, fortnite"
          href="https://obymarket.com/"
          color="hover:border-green-500/40 hover:bg-green-500/5 shadow-[inset_0_0_20px_rgba(34,197,94,0)] hover:shadow-[inset_0_0_20px_rgba(34,197,94,0.1)]"
          onHoverChange={(isHovered) => setHoveredBgImage(isHovered ? getImageUrl("market") : null)}
        />
        <LinkCard
          icon={<Instagram className="w-5 h-5" />}
          title="Instagram"
          subtitle="@ip_oby"
          href="https://www.instagram.com/ip_oby/"
          color="hover:border-white/30 hover:bg-white/5 shadow-[inset_0_0_20px_rgba(255,255,255,0)] hover:shadow-[inset_0_0_20px_rgba(255,255,255,0.05)]"
          onHoverChange={(isHovered) => setHoveredBgImage(isHovered ? getImageUrl("insta") : null)}

        />
      </div>

      {/* Footer */}
      <footer className="mt-24 relative z-10">
        <motion.div 
          initial={{ opacity: 0 }}
          whileInView={{ opacity: 1 }}
          className="flex flex-col items-center gap-6"
        >
          <div className="flex gap-8">
            <motion.div whileHover={{ scale: 1.2, y: -5 }} className="w-1 h-1 bg-white/20 rounded-full" />
            <motion.div whileHover={{ scale: 1.2, y: -5 }} className="w-1 h-1 bg-white/20 rounded-full" />
            <motion.div whileHover={{ scale: 1.2, y: -5 }} className="w-1 h-1 bg-white/20 rounded-full" />
          </div>
          <p className="text-[9px] tracking-[0.5em] text-white/20 uppercase text-center font-sans">
            © 2026 RIOT CRASH • EXECUTING THE FUTURE
          </p>
        </motion.div>
      </footer>
      {/* Spotify Embed */}
      <motion.div 
        initial={{ opacity: 0, x: 20 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ delay: 1, duration: 1 }}
        className="fixed bottom-6 right-6 z-[60] w-[300px] h-[152px] hidden md:block"
      >
        <iframe 
          style={{ borderRadius: '12px' }} 
          src="https://open.spotify.com/embed/track/3qhlB30KknSejmIvZZLjOD?utm_source=generator&theme=0&autoplay=1" 
          width="100%" 
          height="152" 

          frameBorder="0" 
          allowFullScreen={false} 
          allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" 
          loading="lazy"
        />
      </motion.div>
    </div>
  );
}

function LinkCard({ icon, title, subtitle, href, color, onHoverChange }: { icon: React.ReactNode; title: string; subtitle: string; href: string; color: string; onHoverChange?: (isHovered: boolean) => void }) {
  const [playHover] = useSound("https://assets.mixkit.co/active_storage/sfx/2560/2560-preview.mp3", { volume: 0.15, playbackRate: 2 });
  const [playClick] = useSound("https://assets.mixkit.co/active_storage/sfx/2568/2568-preview.mp3", { volume: 0.2 });

  return (
    <motion.a
      href={href}
      target="_blank"
      rel="noopener noreferrer"
      onMouseEnter={() => {
        playHover();
        onHoverChange?.(true);
      }}
      onMouseLeave={() => onHoverChange?.(false)}
      onClick={() => playClick()}
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      className={`group relative flex items-center justify-between p-6 bg-white/[0.01] border border-white/5 rounded-2xl transition-all duration-500 overflow-hidden cursor-none block ${color} hover:bg-white/[0.04] hover:shadow-[0_0_40px_rgba(255,255,255,0.05)]`}
    >
      {/* Background Animated Gradient Overlay */}
      <motion.div 
        className="absolute inset-0 bg-gradient-to-r from-transparent via-white/[0.03] to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000 ease-in-out" 
      />
      
      {/* Border Glow Effect */}
      <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500">
        <div className="absolute inset-[1px] rounded-2xl border border-white/10" />
      </div>

      <div className="flex items-center gap-6 relative z-10 w-full">
        <motion.div 
          className="w-14 h-14 rounded-xl bg-white/[0.02] border border-white/10 flex items-center justify-center text-white/30 group-hover:text-white group-hover:border-white/30 group-hover:bg-white/5 transition-all duration-500 shadow-inner"
        >
          {icon}
        </motion.div>
        
        <div className="flex flex-col flex-grow">
          <div className="flex items-center gap-2">
            <h2 className="text-xl md:text-2xl font-bold tracking-tight transition-all duration-500 group-hover:translate-x-1">
              {title}
            </h2>
          </div>
          <p className="text-[11px] tracking-[0.2em] text-white/20 uppercase group-hover:text-white/50 transition-all duration-500 font-sans mt-1">
            {subtitle}
          </p>
        </div>

        <div className="relative z-10 flex items-center justify-center">
          <div className="w-11 h-11 rounded-full border border-white/5 flex items-center justify-center group-hover:bg-white group-hover:text-black transition-all duration-500 group-hover:scale-110">
            <ArrowUpRight className="w-5 h-5 transition-transform duration-500 group-hover:rotate-45" />
          </div>
        </div>
      </div>
    </motion.a>
  );
}
