import { useEffect, useState, useRef } from "react";
import { motion, useScroll, useTransform } from "framer-motion";
import { Instagram } from "lucide-react";

const codeLines = [
  "local QBCore = exports['qb-core']:GetCoreObject()",
  "RegisterNetEvent('hs:server:init')",
  "-- Sistema exclusivo HS Cabuloso",
  "function StartSystem(data)",
  "  local player = QBCore.Functions.GetPlayer(source)",
  '  TriggerClientEvent("hs:client:ready", source)',
  "end",
  "-- Performance otimizada ✓",
  "-- Código limpo e escalável ✓",
];

const TerminalTyping = () => {
  const [currentLine, setCurrentLine] = useState(0);
  const [currentChar, setCurrentChar] = useState(0);

  useEffect(() => {
    if (currentLine >= codeLines.length) {
      const timeout = setTimeout(() => {
        setCurrentLine(0);
        setCurrentChar(0);
      }, 2000);
      return () => clearTimeout(timeout);
    }

    if (currentChar < codeLines[currentLine].length) {
      const timeout = setTimeout(() => setCurrentChar((c) => c + 1), 40);
      return () => clearTimeout(timeout);
    } else {
      const timeout = setTimeout(() => {
        setCurrentLine((l) => l + 1);
        setCurrentChar(0);
      }, 400);
      return () => clearTimeout(timeout);
    }
  }, [currentLine, currentChar]);

  return (
    <div className="glass-card rounded-xl p-6 font-mono text-sm border border-cabuloso/30 max-w-2xl mx-auto">
      <div className="flex gap-2 mb-4">
        <div className="w-3 h-3 rounded-full bg-destructive/60" />
        <div className="w-3 h-3 rounded-full bg-primary/60" />
        <div className="w-3 h-3 rounded-full bg-muted-foreground/40" />
      </div>
      <div className="space-y-1 min-h-[240px]">
        {codeLines.slice(0, currentLine + 1).map((line, i) => (
          <div key={i} className="text-cabuloso/80">
            <span className="text-muted-foreground mr-2 select-none">{String(i + 1).padStart(2, "0")}</span>
            {i < currentLine ? line : line.slice(0, currentChar)}
            {i === currentLine && currentLine < codeLines.length && (
              <span className="terminal-cursor text-cabuloso">▌</span>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

const HSCabulosoSection = () => {
  const ref = useRef<HTMLElement>(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start end", "end start"] });

  const terminalY = useTransform(scrollYProgress, [0.1, 0.5], [60, 0]);
  const terminalRotate = useTransform(scrollYProgress, [0.1, 0.5], [3, 0]);
  const glowScale = useTransform(scrollYProgress, [0, 0.5], [0.6, 1.3]);
  const orbY = useTransform(scrollYProgress, [0, 1], [60, -60]);

  return (
    <section ref={ref} id="hscabuloso" className="relative py-32 overflow-hidden">
      <motion.div className="absolute inset-0 bg-radial-cabuloso" style={{ scale: glowScale, opacity: useTransform(scrollYProgress, [0, 0.3, 0.7, 1], [0, 0.8, 0.8, 0]) }} />

      {/* Floating orb */}
      <motion.div
        className="absolute w-80 h-80 rounded-full blur-3xl pointer-events-none"
        style={{ background: "hsl(var(--cabuloso) / 0.05)", top: "15%", left: "-8%", y: orbY }}
      />

      <div className="relative z-10 container mx-auto px-4">
        <motion.div className="text-center mb-16">
          <motion.span
            initial={{ opacity: 0, y: -10 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.5 }}
            className="text-cabuloso font-mono text-sm tracking-widest uppercase inline-block"
          >
            03 — Software
          </motion.span>
          <motion.h2
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.7, delay: 0.1 }}
            className="text-4xl md:text-6xl font-extrabold tracking-tight mt-4 mb-6"
          >
            HS <span className="text-cabuloso">Cabuloso_dev</span>
          </motion.h2>
          <motion.p
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6, delay: 0.2 }}
            className="text-muted-foreground max-w-2xl mx-auto text-lg leading-relaxed"
          >
            Scripts exclusivos, otimizados e altamente funcionais para servidores FiveM.
            Inovação, qualidade de código e entrega rápida.
          </motion.p>
        </motion.div>

        <motion.div style={{ y: terminalY, rotateZ: terminalRotate }}>
          <TerminalTyping />
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.5 }}
          className="flex flex-wrap gap-4 justify-center mt-12"
        >
          <a
            href="https://henrique.gestaopme.xyz"
            target="_blank"
            rel="noopener noreferrer"
            className="bg-cabuloso text-accent-foreground px-6 py-3 rounded-lg font-bold hover:brightness-110 transition"
          >
            Visitar Site
          </a>
          <a
            href="https://instagram.com/lzhenriquesoficial"
            target="_blank"
            rel="noopener noreferrer"
            className="border border-cabuloso/30 text-cabuloso px-6 py-3 rounded-lg font-semibold hover:bg-cabuloso/10 transition flex items-center gap-2"
          >
            <Instagram size={18} /> @lzhenriquesoficial
          </a>
        </motion.div>
      </div>
    </section>
  );
};

export default HSCabulosoSection;
