import React, { useEffect, useRef, useState, useMemo, useId } from "react";
import { createRoot } from "react-dom/client";
import {
  motion,
  AnimatePresence,
  useMotionValue,
  useSpring,
  useTransform,
  useScroll,
  useInView,
  animate,
} from "framer-motion";
import Lenis from "lenis";

const whatsappLink = (message = "Me interesa posicionar mi marca") =>
  `https://wa.me/573153593552?text=${encodeURIComponent(message)}`;
const WHATSAPP_LINK = whatsappLink();

/* ======================================================================
   GLOBAL HOOKS
   ====================================================================== */

function useLenis() {
  useEffect(() => {
    const lenis = new Lenis({ lerp: 0.1, wheelMultiplier: 1, smoothWheel: true });
    let rafId;
    function raf(time) {
      lenis.raf(time);
      rafId = requestAnimationFrame(raf);
    }
    rafId = requestAnimationFrame(raf);
    return () => {
      cancelAnimationFrame(rafId);
      lenis.destroy();
    };
  }, []);
}

function useMouse() {
  const x = useMotionValue(-200);
  const y = useMotionValue(-200);
  useEffect(() => {
    function handle(e) {
      x.set(e.clientX);
      y.set(e.clientY);
    }
    window.addEventListener("mousemove", handle);
    return () => window.removeEventListener("mousemove", handle);
  }, [x, y]);
  return { x, y };
}

/* ======================================================================
   CURSOR + PROGRESS + GRAIN
   ====================================================================== */

function CustomCursor({ mouse }) {
  const [hovering, setHovering] = useState(false);
  const dotX = useSpring(mouse.x, { damping: 40, stiffness: 900 });
  const dotY = useSpring(mouse.y, { damping: 40, stiffness: 900 });
  const ringX = useSpring(mouse.x, { damping: 30, stiffness: 200 });
  const ringY = useSpring(mouse.y, { damping: 30, stiffness: 200 });

  useEffect(() => {
    function over(e) {
      if (e.target.closest("[data-cursor]")) setHovering(true);
    }
    function out(e) {
      if (e.target.closest("[data-cursor]")) setHovering(false);
    }
    document.addEventListener("mouseover", over);
    document.addEventListener("mouseout", out);
    return () => {
      document.removeEventListener("mouseover", over);
      document.removeEventListener("mouseout", out);
    };
  }, []);

  return (
    <>
      <motion.div className="cursor-dot" style={{ left: dotX, top: dotY }} />
      <motion.div
        className="cursor-ring"
        animate={{ width: hovering ? 64 : 36, height: hovering ? 64 : 36, opacity: hovering ? 0.6 : 1 }}
        transition={{ duration: 0.25 }}
        style={{ left: ringX, top: ringY }}
      />
    </>
  );
}

function ScrollProgressBar() {
  const { scrollYProgress } = useScroll();
  return (
    <motion.div
      className="fixed top-0 left-0 right-0 h-[3px] bg-gradient-to-r from-violet-600 via-coral-500 to-violet-600 origin-left z-50"
      style={{ scaleX: scrollYProgress }}
    />
  );
}

/* ======================================================================
   REUSABLE PRIMITIVES
   ====================================================================== */

const easeOut = [0.16, 1, 0.3, 1];

function Reveal({ children, className = "", delay = 0, y = 36, once = true }) {
  return (
    <motion.div
      className={className}
      initial={{ opacity: 0, y, filter: "blur(6px)" }}
      whileInView={{ opacity: 1, y: 0, filter: "blur(0px)" }}
      viewport={{ once, amount: 0.25 }}
      transition={{ duration: 0.8, delay, ease: easeOut }}
    >
      {children}
    </motion.div>
  );
}

function Stagger({ children, className = "", stagger = 0.08 }) {
  return (
    <motion.div
      className={className}
      initial="hidden"
      whileInView="show"
      viewport={{ once: true, amount: 0.2 }}
      variants={{ hidden: {}, show: { transition: { staggerChildren: stagger } } }}
    >
      {children}
    </motion.div>
  );
}

function StaggerItem({ children, className = "" }) {
  return (
    <motion.div
      className={className}
      variants={{
        hidden: { opacity: 0, y: 28, filter: "blur(4px)" },
        show: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: 0.65, ease: easeOut } },
      }}
    >
      {children}
    </motion.div>
  );
}

function CountUp({ to, prefix = "", suffix = "", decimals = 0 }) {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, amount: 0.6 });
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!inView) return;
    const controls = animate(0, to, {
      duration: 1.6,
      ease: easeOut,
      onUpdate: (v) => setVal(v),
    });
    return () => controls.stop();
  }, [inView, to]);
  return (
    <span ref={ref}>
      {prefix}
      {val.toFixed(decimals)}
      {suffix}
    </span>
  );
}

function MagneticButton({ children, className = "", onClick, as = "button", ...rest }) {
  const ref = useRef(null);
  const x = useSpring(0, { stiffness: 200, damping: 15, mass: 0.4 });
  const y = useSpring(0, { stiffness: 200, damping: 15, mass: 0.4 });

  function handleMove(e) {
    const rect = ref.current.getBoundingClientRect();
    const relX = e.clientX - (rect.left + rect.width / 2);
    const relY = e.clientY - (rect.top + rect.height / 2);
    x.set(relX * 0.3);
    y.set(relY * 0.3);
  }
  function handleLeave() {
    x.set(0);
    y.set(0);
  }
  const Comp = motion[as];
  return (
    <Comp
      ref={ref}
      data-cursor="hover"
      onMouseMove={handleMove}
      onMouseLeave={handleLeave}
      onClick={onClick}
      style={{ x, y }}
      className={className}
      {...rest}
    >
      {children}
    </Comp>
  );
}

function TiltCard({ children, className = "" }) {
  const ref = useRef(null);
  const rx = useSpring(0, { stiffness: 150, damping: 18 });
  const ry = useSpring(0, { stiffness: 150, damping: 18 });
  const scale = useSpring(1, { stiffness: 150, damping: 18 });

  function handleMove(e) {
    const rect = ref.current.getBoundingClientRect();
    const px = (e.clientX - rect.left) / rect.width - 0.5;
    const py = (e.clientY - rect.top) / rect.height - 0.5;
    ry.set(px * 14);
    rx.set(-py * 14);
  }
  function reset() {
    rx.set(0);
    ry.set(0);
    scale.set(1);
  }
  return (
    <motion.div
      ref={ref}
      className={className}
      onMouseMove={handleMove}
      onMouseEnter={() => scale.set(1.03)}
      onMouseLeave={reset}
      style={{ rotateX: rx, rotateY: ry, scale, transformPerspective: 900 }}
    >
      {children}
    </motion.div>
  );
}

function Eyebrow({ children, dark = false }) {
  return (
    <div
      className={`inline-flex items-center gap-2 text-xs font-semibold tracking-widest uppercase mb-4 ${
        dark ? "text-white/60" : "text-violet-600"
      }`}
    >
      <span className={`h-1.5 w-1.5 rounded-full ${dark ? "bg-mint-400" : "bg-violet-600"}`} />
      {children}
    </div>
  );
}

/* ======================================================================
   NAVBAR
   ====================================================================== */

function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    function onScroll() {
      setScrolled(window.scrollY > 20);
    }
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <motion.header
      initial={{ y: -80, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ duration: 0.7, ease: easeOut }}
      className={`fixed top-0 left-0 right-0 z-40 transition-all duration-300 ${
        scrolled ? "bg-paper/80 backdrop-blur-md border-b border-black/5 py-3" : "py-6"
      }`}
    >
      <div className="max-w-7xl mx-auto px-6 flex items-center justify-between">
        <a href="#top" data-cursor="hover" className="flex items-center gap-2 font-display font-bold text-lg">
          <LogoMark />
          <span className="logo-text">Infinity Pixel</span>
        </a>
        <nav className="hidden md:flex items-center gap-8 text-sm font-medium text-ink/70">
          {["Servicios", "Casos de Éxito", "Precios", "Recursos"].map((item) => (
            <a key={item} href={`#${slugify(item)}`} data-cursor="hover" className="hover:text-ink transition-colors">
              {item}
            </a>
          ))}
        </nav>
        <MagneticButton
          as="a"
          href={WHATSAPP_LINK}
          target="_blank"
          rel="noopener noreferrer"
          className="rounded-full bg-ink text-white text-sm font-semibold px-5 py-2.5 hover:bg-violet-700 transition-colors"
        >
          Empezar Gratis
        </MagneticButton>
      </div>
    </motion.header>
  );
}

function slugify(s) {
  return s
    .toLowerCase()
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/\s+/g, "-");
}

function LogoMark({ size = 26, loop = false }) {
  const gid = useId();
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <defs>
        <linearGradient id={`logo-grad-${gid}`} x1="2" y1="8" x2="22" y2="16" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#14e0c4" />
          <stop offset="100%" stopColor="#0b4fc4" />
        </linearGradient>
      </defs>
      <motion.path
        d="M18.178 8c5.096 0 5.096 8 0 8-5.095 0-6.808-8-12.356-8-4.95 0-4.95 8 0 8 5.548 0 7.26-8 12.356-8Z"
        stroke={`url(#logo-grad-${gid})`}
        strokeWidth="2.1"
        strokeLinecap="round"
        strokeLinejoin="round"
        initial={{ pathLength: 0 }}
        animate={{ pathLength: 1 }}
        transition={
          loop
            ? { duration: 2.4, repeat: Infinity, repeatType: "loop", repeatDelay: 0.6, ease: "easeInOut" }
            : { duration: 1.4, ease: "easeInOut" }
        }
      />
    </svg>
  );
}

/* ======================================================================
   TICKER
   ====================================================================== */

const TICKER_ITEMS = [
  { icon: "🥖", label: "Bakers Manizales", tag: "3.6K seguidores" },
  { icon: "🏢", label: "Raíces Inmobiliaria", tag: "697 seguidores" },
  { icon: "🌾", label: "Origen Caldas", tag: "2.3K seguidores" },
  { icon: "💧", label: "PureWater", tag: "221 seguidores" },
  { icon: "🍬", label: "Casa'o", tag: "3.6K seguidores" },
  { icon: "📈", label: "El Darling Academy", tag: "4.9K seguidores" },
];

function Ticker() {
  const items = [...TICKER_ITEMS, ...TICKER_ITEMS];
  return (
    <div className="border-y border-black/5 bg-white overflow-hidden">
      <div className="marquee-track py-3">
        {items.map((item, i) => (
          <div key={i} className="flex items-center gap-2 px-6 text-sm whitespace-nowrap">
            <span>{item.icon}</span>
            <span className="font-medium text-ink/70">{item.label}</span>
            <span className="text-violet-600 font-semibold">{item.tag}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ======================================================================
   HERO
   ====================================================================== */

function Hero({ mouse }) {
  const blob1x = useTransform(mouse.x, [0, window.innerWidth], [-40, 40]);
  const blob1y = useTransform(mouse.y, [0, window.innerHeight], [-30, 30]);
  const blob2x = useTransform(mouse.x, [0, window.innerWidth], [30, -30]);
  const blob2y = useTransform(mouse.y, [0, window.innerHeight], [20, -20]);
  const blob1xs = useSpring(blob1x, { damping: 25, stiffness: 60 });
  const blob1ys = useSpring(blob1y, { damping: 25, stiffness: 60 });
  const blob2xs = useSpring(blob2x, { damping: 25, stiffness: 60 });
  const blob2ys = useSpring(blob2y, { damping: 25, stiffness: 60 });

  const words = "Contenido que".split(" ");
  const words2 = "Posiciona tu Marca.".split(" ");

  return (
    <section id="top" className="relative pt-40 pb-20 overflow-hidden">
      <div className="absolute inset-0 -z-10 bg-gradient-to-b from-violet-50 via-paper to-paper" />
      <motion.div
        style={{ x: blob1xs, y: blob1ys }}
        className="absolute -top-20 left-[8%] w-[420px] h-[420px] rounded-full bg-violet-300/40 blur-[100px] -z-10"
      />
      <motion.div
        style={{ x: blob2xs, y: blob2ys }}
        className="absolute top-10 right-[10%] w-[380px] h-[380px] rounded-full bg-coral-400/30 blur-[100px] -z-10"
      />
      <motion.div
        animate={{ scale: [1, 1.06, 1], opacity: [0.25, 0.4, 0.25] }}
        transition={{ duration: 5, repeat: Infinity, ease: "easeInOut" }}
        className="absolute top-24 right-[18%] w-24 h-24 -z-10 hidden md:block"
      >
        <LogoMark size={96} loop />
      </motion.div>

      <div className="max-w-5xl mx-auto px-6 text-center">
        <Reveal delay={0}>
          <Eyebrow>Agencia de Contenido para Redes Sociales</Eyebrow>
        </Reveal>

        <h1 className="font-display text-5xl md:text-7xl font-bold leading-[1.05] tracking-tight">
          <span className="block overflow-hidden">
            {words.map((w, i) => (
              <motion.span
                key={i}
                className="inline-block mr-4"
                initial={{ y: "110%" }}
                animate={{ y: 0 }}
                transition={{ duration: 0.8, delay: 0.15 + i * 0.08, ease: easeOut }}
              >
                {w}
              </motion.span>
            ))}
          </span>
          <span className="block overflow-hidden grad-text">
            {words2.map((w, i) => (
              <motion.span
                key={i}
                className="inline-block mr-4"
                initial={{ y: "110%" }}
                animate={{ y: 0 }}
                transition={{ duration: 0.8, delay: 0.4 + i * 0.08, ease: easeOut }}
              >
                {w}
              </motion.span>
            ))}
          </span>
        </h1>

        <Reveal delay={0.6}>
          <p className="mt-6 text-lg text-ink/60 max-w-2xl mx-auto">
            Estrategia, diseño y producción de contenido para que tu negocio local tenga la presencia que merece en
            redes sociales.
          </p>
        </Reveal>

        <Reveal delay={0.7} className="mt-8 flex flex-col sm:flex-row items-center justify-center gap-4">
          <MagneticButton
            as="a"
            href={WHATSAPP_LINK}
            target="_blank"
            rel="noopener noreferrer"
            className="rounded-full bg-ink text-white text-sm font-semibold px-7 py-3.5 hover:bg-violet-700 transition-colors"
          >
            Solicita tu Auditoría Gratis →
          </MagneticButton>
          <a
            href="#casos-de-exito"
            data-cursor="hover"
            className="text-sm font-semibold text-ink/70 hover:text-ink transition-colors"
          >
            Ver casos de éxito
          </a>
        </Reveal>

        <Reveal delay={0.85} className="mt-10 flex items-center justify-center gap-3 text-sm text-ink/50">
          <div className="flex -space-x-3">
            {["🍕", "💇‍♀️", "🦷", "👗"].map((e, i) => (
              <div key={i} className="w-9 h-9 rounded-full bg-white border border-black/5 shadow-sm flex items-center justify-center">
                {e}
              </div>
            ))}
          </div>
          <span>Negocios de Manizales que ya confían en Infinity Pixel</span>
        </Reveal>
      </div>
    </section>
  );
}

/* ======================================================================
   AGENTS SECTION (24/7 team + pipeline)
   ====================================================================== */

const AGENT_TABS = ["Vídeo", "Copy", "Diseño", "SEO"];
const AGENT_TAB_COPY = {
  Vídeo: "Guiones, edición y renderizado automático de reels y shorts listos para publicar.",
  Copy: "Anuncios, descripciones de producto y posts con el tono de tu marca.",
  Diseño: "Piezas gráficas, banners y branding coherente en cada publicación.",
  SEO: "Fichas de Google Business y contenido optimizado para aparecer en búsquedas locales.",
};

function AgentsSection() {
  const [tab, setTab] = useState(AGENT_TABS[0]);
  const pipeline = usePipelineMock();

  return (
    <section id="servicios" className="py-28">
      <div className="max-w-7xl mx-auto px-6">
        <div className="text-center max-w-2xl mx-auto">
          <Reveal>
            <Eyebrow>Nuestro Equipo</Eyebrow>
          </Reveal>
          <Reveal delay={0.1}>
            <h2 className="font-display text-4xl md:text-5xl font-bold tracking-tight">
              Un Equipo Dedicado a <br /> Posicionar tu Marca.
            </h2>
          </Reveal>
          <Reveal delay={0.2}>
            <p className="mt-5 text-ink/60">
              Especialistas en estrategia, producción y redes que trabajan tu contenido cada semana, sin pausas ni
              festivos.
            </p>
          </Reveal>
        </div>

        <Reveal delay={0.25} className="mt-10 flex justify-center">
          <div className="inline-flex bg-white border border-black/5 rounded-full p-1 shadow-sm relative">
            {AGENT_TABS.map((t) => (
              <button
                key={t}
                data-cursor="hover"
                onClick={() => setTab(t)}
                className="relative px-5 py-2 text-sm font-medium rounded-full z-10"
              >
                {tab === t && (
                  <motion.span
                    layoutId="agent-tab-bg"
                    className="absolute inset-0 bg-ink rounded-full -z-10"
                    transition={{ type: "spring", stiffness: 350, damping: 30 }}
                  />
                )}
                <span className={tab === t ? "text-white" : "text-ink/60"}>{t}</span>
              </button>
            ))}
          </div>
        </Reveal>

        <Reveal delay={0.3} className="mt-4 text-center text-sm text-ink/50 max-w-md mx-auto">
          <AnimatePresence mode="wait">
            <motion.p
              key={tab}
              initial={{ opacity: 0, y: 6 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -6 }}
              transition={{ duration: 0.3 }}
            >
              {AGENT_TAB_COPY[tab]}
            </motion.p>
          </AnimatePresence>
        </Reveal>

        <div className="mt-20 grid md:grid-cols-2 gap-16 items-center">
          <div>
            <Reveal>
              <Eyebrow>Producción</Eyebrow>
            </Reveal>
            <Reveal delay={0.1}>
              <h3 className="font-display text-3xl md:text-4xl font-bold tracking-tight">
                Contenido Listo en Minutos, no en Semanas.
              </h3>
            </Reveal>
            <Reveal delay={0.2}>
              <p className="mt-5 text-ink/60">
                Nuestro equipo analiza tu negocio, produce piezas de alto impacto y las deja listas para publicar en
                cualquier canal, sin depender de agencias lentas ni de que tú tengas que aprender a hacerlo.
              </p>
            </Reveal>
            <Reveal delay={0.3}>
              <a href="#precios" data-cursor="hover" className="inline-flex items-center gap-1 mt-6 font-semibold text-violet-600">
                Ver planes <span aria-hidden>→</span>
              </a>
            </Reveal>
            <Stagger className="flex flex-wrap gap-3 mt-8">
              {["Instagram", "TikTok", "Google", "WhatsApp"].map((b) => (
                <StaggerItem key={b}>
                  <span className="text-xs font-medium bg-white border border-black/10 rounded-full px-3 py-1.5 text-ink/60">
                    {b}
                  </span>
                </StaggerItem>
              ))}
            </Stagger>
          </div>

          <Reveal delay={0.15} y={50}>
            <div className="bg-white rounded-2xl border border-black/5 shadow-xl shadow-violet-900/5 p-6">
              {pipeline.map((row, i) => (
                <div
                  key={row.label}
                  className={`flex items-center justify-between py-4 ${i !== pipeline.length - 1 ? "border-b border-black/5" : ""}`}
                >
                  <div>
                    <p className="text-sm font-semibold">{row.label}</p>
                    <p className="text-xs text-ink/40">{row.sub}</p>
                  </div>
                  <StatusPill status={row.status} />
                </div>
              ))}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function usePipelineMock() {
  const stages = [
    { label: "Brief del negocio", sub: "Datos y objetivos recogidos" },
    { label: "Producción de contenido", sub: "Vídeo, copy y diseño" },
    { label: "Publicación", sub: "Programado en tus redes" },
  ];
  const statuses = ["Completado", "En proceso", "En cola"];
  const [offset, setOffset] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setOffset((o) => (o + 1) % statuses.length), 2600);
    return () => clearInterval(id);
  }, []);
  return stages.map((s, i) => ({ ...s, status: statuses[(i + offset) % statuses.length] }));
}

function StatusPill({ status }) {
  const styles = {
    Completado: "bg-mint-400/15 text-mint-500",
    "En proceso": "bg-violet-100 text-violet-600",
    "En cola": "bg-black/5 text-ink/40",
  };
  return (
    <AnimatePresence mode="wait">
      <motion.span
        key={status}
        initial={{ opacity: 0, y: -4 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: 4 }}
        transition={{ duration: 0.25 }}
        className={`text-xs font-semibold px-3 py-1 rounded-full ${styles[status]}`}
      >
        {status}
      </motion.span>
    </AnimatePresence>
  );
}

/* ======================================================================
   CASOS DE ÉXITO — video gallery
   ====================================================================== */

const CASE_VIDEOS = [
  { src: "videos/tardea-dron.mp4", poster: "posters/tardea-dron.jpg" },
  { src: "videos/casao-montadito.mp4", poster: "posters/casao-montadito.jpg" },
  { src: "videos/anas-topara.mp4", poster: "posters/anas-topara.jpg" },
  { src: "videos/fastfoodbrasil-burger.mp4", poster: "posters/fastfoodbrasil-burger.jpg" },
  { src: "videos/bakers-tarta-manzana.mp4", poster: "posters/bakers-tarta-manzana.jpg" },
  { src: "videos/divebynature-gorgona.mp4", poster: "posters/divebynature-gorgona.jpg" },
  { src: "videos/casao-receta.mp4", poster: "posters/casao-receta.jpg" },
  { src: "videos/tardea-michael.mp4", poster: "posters/tardea-michael.jpg" },
  { src: "videos/burgerclub-philly.mp4", poster: "posters/burgerclub-philly.jpg" },
  { src: "videos/anas-giraldo.mp4", poster: "posters/anas-giraldo.jpg" },
  { src: "videos/osmo-nano.mp4", poster: "posters/osmo-nano.jpg" },
  { src: "videos/casao-recinto.mp4", poster: "posters/casao-recinto.jpg" },
  { src: "videos/tardea-foto-jero.mp4", poster: "posters/tardea-foto-jero.jpg" },
  { src: "videos/bakers-24-48-horas.mp4", poster: "posters/bakers-24-48-horas.jpg" },
  { src: "videos/anas-bustamante.mp4", poster: "posters/anas-bustamante.jpg" },
  { src: "videos/casa-paseo-bosque.mp4", poster: "posters/casa-paseo-bosque.jpg" },
  { src: "videos/tardea-pov-botella.mp4", poster: "posters/tardea-pov-botella.jpg" },
  { src: "videos/bakers-desayunos.mp4", poster: "posters/bakers-desayunos.jpg" },
];

const AUTOSCROLL_SPEED = 0.6;

function BeforeAfterSection() {
  const videoRefs = useRef([]);
  const scrollRef = useRef(null);
  const hoveringRef = useRef(false);
  const activeIndexRef = useRef(null);
  const dirRef = useRef(1);
  const [activeIndex, setActiveIndex] = useState(null);

  useEffect(() => {
    activeIndexRef.current = activeIndex;
  }, [activeIndex]);

  useEffect(() => {
    const id = setInterval(() => {
      const el = scrollRef.current;
      if (!el || hoveringRef.current || activeIndexRef.current !== null) return;
      const max = el.scrollWidth - el.clientWidth;
      if (max <= 0) return;
      let next = el.scrollLeft + AUTOSCROLL_SPEED * dirRef.current;
      if (next >= max) {
        next = max;
        dirRef.current = -1;
      } else if (next <= 0) {
        next = 0;
        dirRef.current = 1;
      }
      el.scrollLeft = next;
    }, 30);
    return () => clearInterval(id);
  }, []);

  function handleVideoPlay(index) {
    videoRefs.current.forEach((el, i) => {
      if (el && i !== index) el.pause();
    });
    setActiveIndex(index);
  }

  function handleVideoStop(index) {
    setActiveIndex((current) => (current === index ? null : current));
  }

  function scrollByCards(dir) {
    scrollRef.current?.scrollBy({ left: dir * 240, behavior: "smooth" });
  }

  return (
    <section id="casos-de-exito" className="py-28 bg-gradient-to-b from-white to-violet-50/40 overflow-hidden">
      <div className="max-w-6xl mx-auto px-6">
        <div className="text-center max-w-2xl mx-auto">
          <Reveal>
            <Eyebrow>Casos de Éxito</Eyebrow>
          </Reveal>
          <Reveal delay={0.1}>
            <h2 className="font-display text-4xl md:text-5xl font-bold tracking-tight">
              De Invisible <br /> a Inolvidable.
            </h2>
          </Reveal>
          <Reveal delay={0.2}>
            <p className="mt-5 text-ink/60">Contenido real que ya estamos produciendo para negocios reales.</p>
          </Reveal>
        </div>
      </div>

      <Reveal delay={0.3} className="relative mt-14">
        <div
          onMouseEnter={() => (hoveringRef.current = true)}
          onMouseLeave={() => (hoveringRef.current = false)}
          onTouchStart={() => (hoveringRef.current = true)}
          onTouchEnd={() => (hoveringRef.current = false)}
        >
          <button
            data-cursor="hover"
            onClick={() => scrollByCards(-1)}
            className="hidden md:flex absolute left-4 top-1/2 -translate-y-1/2 z-20 w-10 h-10 rounded-full bg-white shadow-lg items-center justify-center text-ink/60 hover:text-ink"
          >
            ←
          </button>
          <button
            data-cursor="hover"
            onClick={() => scrollByCards(1)}
            className="hidden md:flex absolute right-4 top-1/2 -translate-y-1/2 z-20 w-10 h-10 rounded-full bg-white shadow-lg items-center justify-center text-ink/60 hover:text-ink"
          >
            →
          </button>
          <div ref={scrollRef} className="hide-scrollbar flex gap-4 overflow-x-auto py-4 px-6">
            {CASE_VIDEOS.map((v, i) => (
              <VideoCard
                key={i}
                src={v.src}
                poster={v.poster}
                isActive={activeIndex === i}
                dimmed={activeIndex !== null && activeIndex !== i}
                onVideoPlay={() => handleVideoPlay(i)}
                onVideoStop={() => handleVideoStop(i)}
                videoRef={(el) => (videoRefs.current[i] = el)}
              />
            ))}
          </div>
        </div>
      </Reveal>
    </section>
  );
}

function VideoCard({ src, poster, isActive, dimmed, onVideoPlay, onVideoStop, videoRef }) {
  const localRef = useRef(null);
  const [playing, setPlaying] = useState(false);

  function setRefs(el) {
    localRef.current = el;
    videoRef(el);
  }

  function handleClickPlay() {
    localRef.current.play();
  }

  return (
    <motion.div
      animate={{ scale: isActive ? 1.08 : dimmed ? 0.94 : 1, opacity: dimmed ? 0.55 : 1 }}
      transition={{ duration: 0.4, ease: easeOut }}
      style={{ zIndex: isActive ? 10 : 1 }}
      className="relative shrink-0 w-40 sm:w-48 md:w-52 aspect-[9/16] rounded-2xl overflow-hidden shadow-lg shadow-violet-900/15"
    >
      <video
        ref={setRefs}
        src={src}
        poster={poster}
        preload="none"
        playsInline
        controls={playing}
        onPlay={() => {
          setPlaying(true);
          onVideoPlay();
        }}
        onPause={() => {
          setPlaying(false);
          onVideoStop();
        }}
        onEnded={() => {
          setPlaying(false);
          onVideoStop();
        }}
        className="absolute inset-0 w-full h-full object-cover"
      />
      {!playing && (
        <button
          data-cursor="hover"
          onClick={handleClickPlay}
          className="absolute inset-0 flex items-center justify-center bg-black/5"
        >
          <motion.span
            animate={{ scale: [1, 1.08, 1] }}
            transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
            className="w-12 h-12 rounded-full bg-white/25 backdrop-blur border border-white/40 flex items-center justify-center text-xl text-white"
          >
            <span className="ml-0.5">▶</span>
          </motion.span>
        </button>
      )}
    </motion.div>
  );
}

/* ======================================================================
   ROLES SECTION
   ====================================================================== */

const ROLES = [
  {
    icon: "🍽️",
    title: "Restaurantes y Hostelería",
    copy: "Fotos y reels que dan hambre, gestión de reseñas y promos de temporada listas en minutos.",
  },
  {
    icon: "🛍️",
    title: "Comercios y Retail",
    copy: "Fichas de producto, catálogos y campañas de temporada que convierten visitas en ventas.",
  },
  {
    icon: "💼",
    title: "Servicios Profesionales",
    copy: "Contenido de autoridad para clínicas, peluquerías, gimnasios y despachos que genera confianza.",
  },
];

function RolesSection() {
  return (
    <section id="casos-de-exito" className="py-28">
      <div className="max-w-7xl mx-auto px-6">
        <div className="text-center max-w-2xl mx-auto">
          <Reveal>
            <Eyebrow>Roles</Eyebrow>
          </Reveal>
          <Reveal delay={0.1}>
            <h2 className="font-display text-4xl md:text-5xl font-bold tracking-tight">
              Soluciones para Cada Tipo de Negocio.
            </h2>
          </Reveal>
          <Reveal delay={0.2}>
            <p className="mt-5 text-ink/60">
              Ya vendas platos, cortes de pelo o consultas médicas, Infinity Pixel se adapta a tu forma de trabajar.
            </p>
          </Reveal>
        </div>

        <Stagger className="grid md:grid-cols-3 gap-6 mt-16" stagger={0.12}>
          {ROLES.map((r) => (
            <StaggerItem key={r.title}>
              <TiltCard className="h-full bg-white rounded-2xl border border-black/5 shadow-sm p-8">
                <div className="w-12 h-12 rounded-xl bg-violet-50 flex items-center justify-center text-2xl">
                  {r.icon}
                </div>
                <h3 className="mt-6 font-display font-semibold text-lg">{r.title}</h3>
                <p className="mt-3 text-sm text-ink/60 leading-relaxed">{r.copy}</p>
              </TiltCard>
            </StaggerItem>
          ))}
        </Stagger>

        <Reveal delay={0.2} className="mt-8">
          <ToolCTA />
        </Reveal>
      </div>
    </section>
  );
}

function ToolCTA() {
  const ref = useRef(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start end", "end start"] });
  const linesX = useTransform(scrollYProgress, [0, 1], [-60, 60]);

  return (
    <div ref={ref} className="relative overflow-hidden rounded-3xl bg-ink text-white">
      <div className="grid md:grid-cols-2">
        <div className="p-10 md:p-14 relative z-10">
          <Eyebrow dark>Auditoría Gratuita</Eyebrow>
          <h3 className="font-display text-3xl md:text-4xl font-bold leading-tight">
            Descubre Cómo <br /> Posicionar tu Marca.
          </h3>
          <p className="mt-4 text-white/60 max-w-sm">
            Analizamos tu presencia actual y te mostramos, sin compromiso, el plan para hacerla crecer.
          </p>
          <ul className="mt-6 space-y-2 text-sm text-white/70">
            {["Analizamos tu presencia actual", "Diseñamos tu estrategia de contenido", "Publicas en menos de 2 semanas"].map(
              (t) => (
                <li key={t} className="flex items-center gap-2">
                  <span className="text-mint-400">✓</span>
                  {t}
                </li>
              )
            )}
          </ul>
          <MagneticButton
            as="a"
            href={WHATSAPP_LINK}
            target="_blank"
            rel="noopener noreferrer"
            className="mt-8 inline-block rounded-full bg-white text-ink text-sm font-semibold px-6 py-3 hover:bg-mint-400 transition-colors"
          >
            Solicita tu Auditoría →
          </MagneticButton>
        </div>
        <div className="relative bg-gradient-to-br from-violet-600 to-violet-700 min-h-[260px] flex items-center justify-center overflow-hidden">
          <motion.div
            style={{ x: linesX }}
            className="absolute inset-0"
            aria-hidden
          >
            {[...Array(6)].map((_, i) => (
              <div
                key={i}
                className="absolute top-0 bottom-0 w-px bg-white/10"
                style={{ left: `${i * 18 - 20}%`, transform: "rotate(18deg)" }}
              />
            ))}
          </motion.div>
          <motion.div
            animate={{ scale: [1, 1.08, 1], opacity: [0.5, 0.8, 0.5] }}
            transition={{ duration: 4, repeat: Infinity, ease: "easeInOut" }}
            className="w-40 h-40 rounded-full bg-white/20 blur-2xl absolute"
          />
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 18, repeat: Infinity, ease: "linear" }}
            className="relative w-24 h-24 rounded-full border-2 border-dashed border-white/40 flex items-center justify-center"
          >
            <span className="text-3xl">✨</span>
          </motion.div>
        </div>
      </div>
    </div>
  );
}

/* ======================================================================
   PRICING
   ====================================================================== */

const PRICING = [
  {
    name: "Plan Sencillo",
    price: "800.000",
    desc: "Para negocios que están dando sus primeros pasos en redes.",
    features: ["8 publicaciones al mes", "Diseño y redacción incluidos", "Atención directa con el equipo"],
    highlight: false,
  },
  {
    name: "Plan Intermedio",
    price: "1.100.000",
    desc: "Para negocios que quieren mantener una presencia constante.",
    features: ["12 publicaciones al mes", "Diseño y redacción incluidos", "Atención directa con el equipo"],
    highlight: true,
  },
  {
    name: "Plan Premium",
    price: "1.500.000",
    desc: "Para negocios que quieren maximizar su presencia en redes.",
    features: ["16 publicaciones al mes", "Diseño y redacción incluidos", "Atención directa con el equipo"],
    highlight: false,
  },
];

function PricingSection() {
  return (
    <section id="precios" className="py-28 bg-violet-50/40">
      <div className="max-w-7xl mx-auto px-6">
        <div className="text-center max-w-2xl mx-auto">
          <Reveal>
            <Eyebrow>Precios</Eyebrow>
          </Reveal>
          <Reveal delay={0.1}>
            <h2 className="font-display text-4xl md:text-5xl font-bold tracking-tight">
              Planes para Cada Etapa de tu Negocio.
            </h2>
          </Reveal>
          <Reveal delay={0.2}>
            <p className="mt-5 text-ink/60">Sin permanencia. Cambia o cancela cuando quieras.</p>
          </Reveal>
        </div>

        <Stagger className="grid md:grid-cols-3 gap-6 mt-16" stagger={0.1}>
          {PRICING.map((p) => (
            <StaggerItem key={p.name}>
              <div
                className={`h-full rounded-2xl p-8 flex flex-col ${
                  p.highlight ? "bg-ink text-white shadow-2xl md:-translate-y-4" : "bg-white border border-black/5"
                }`}
              >
                {p.highlight && (
                  <span className="self-start text-xs font-semibold bg-mint-400 text-ink px-3 py-1 rounded-full mb-4">
                    Más popular
                  </span>
                )}
                <h3 className="font-display font-semibold text-xl">{p.name}</h3>
                <p className={`mt-2 text-sm ${p.highlight ? "text-white/60" : "text-ink/50"}`}>{p.desc}</p>
                <div className="mt-6 flex items-baseline gap-1.5">
                  <span className="text-3xl font-bold font-display">${p.price}</span>
                  <span className={p.highlight ? "text-white/50" : "text-ink/40"}>COP/mes</span>
                </div>
                <ul className="mt-6 space-y-3 text-sm flex-1">
                  {p.features.map((f) => (
                    <li key={f} className="flex items-center gap-2">
                      <span className={p.highlight ? "text-mint-400" : "text-violet-600"}>✓</span>
                      {f}
                    </li>
                  ))}
                </ul>
                <MagneticButton
                  as="a"
                  href={whatsappLink(`Me interesa posicionar mi marca - ${p.name}`)}
                  target="_blank"
                  rel="noopener noreferrer"
                  className={`mt-8 rounded-full text-sm font-semibold px-6 py-3 text-center transition-colors ${
                    p.highlight ? "bg-white text-ink hover:bg-mint-400" : "bg-ink text-white hover:bg-violet-700"
                  }`}
                >
                  Elegir {p.name}
                </MagneticButton>
              </div>
            </StaggerItem>
          ))}
        </Stagger>
      </div>
    </section>
  );
}

/* ======================================================================
   RESOURCES GRID
   ====================================================================== */

const RESOURCES = [
  { title: "Casos de Éxito", copy: "Historias reales de negocios que despegaron con Infinity Pixel.", color: "bg-[#ffb3c7]" },
  { title: "Academia", copy: "Cursos gratuitos sobre contenido, marca y redes sociales.", color: "bg-[#0b4fc4] text-white" },
  { title: "Blog de Marketing", copy: "Ideas, tendencias y análisis para negocios locales.", color: "bg-[#5ee6f0]" },
  { title: "Plantillas Gratis", copy: "Guiones, calendarios de contenido y ejemplos listos para usar.", color: "bg-[#ffb066]" },
];

function ResourcesSection() {
  return (
    <section id="recursos" className="py-28">
      <div className="max-w-7xl mx-auto px-6">
        <div className="max-w-2xl">
          <Reveal>
            <Eyebrow>Aprende</Eyebrow>
          </Reveal>
          <Reveal delay={0.1}>
            <h2 className="font-display text-4xl md:text-5xl font-bold tracking-tight">
              Recursos e Ideas para Vender Más.
            </h2>
          </Reveal>
        </div>

        <Stagger className="grid sm:grid-cols-2 md:grid-cols-4 gap-5 mt-14" stagger={0.1}>
          {RESOURCES.map((r) => (
            <StaggerItem key={r.title}>
              <TiltCard className={`h-full min-h-[220px] rounded-2xl p-6 flex flex-col justify-between ${r.color}`}>
                <p className="font-display font-semibold text-lg leading-snug">{r.title}</p>
                <div>
                  <p className="text-sm opacity-80 mb-4">{r.copy}</p>
                  <span data-cursor="hover" className="text-sm font-semibold inline-flex items-center gap-1">
                    Explorar <span aria-hidden>→</span>
                  </span>
                </div>
              </TiltCard>
            </StaggerItem>
          ))}
        </Stagger>
      </div>
    </section>
  );
}

/* ======================================================================
   FINAL CTA
   ====================================================================== */

function FinalCTA() {
  const ref = useRef(null);
  const { scrollYProgress } = useScroll({ target: ref, offset: ["start end", "end start"] });
  const orbScale = useTransform(scrollYProgress, [0, 0.5, 1], [0.8, 1.3, 0.8]);

  return (
    <section ref={ref} className="py-28 px-6">
      <div className="max-w-6xl mx-auto rounded-3xl bg-ink text-white relative overflow-hidden text-center py-24 px-6">
        <motion.div
          style={{ scale: orbScale }}
          className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[520px] h-[520px] rounded-full bg-gradient-to-br from-violet-600/40 to-coral-500/30 blur-[110px]"
        />
        <div className="relative z-10">
          <Reveal>
            <h2 className="font-display text-4xl md:text-6xl font-bold tracking-tight">
              Posiciona tu Marca. <br /> Que te Vean, que te Recuerden.
            </h2>
          </Reveal>
          <Reveal delay={0.15}>
            <p className="mt-5 text-white/60 max-w-xl mx-auto">
              Únete a los negocios de Manizales que ya construyeron una presencia de marca sólida en redes sociales.
            </p>
          </Reveal>
          <Reveal delay={0.3} className="mt-10">
            <MagneticButton
              as="a"
              href={WHATSAPP_LINK}
              target="_blank"
              rel="noopener noreferrer"
              className="rounded-full bg-white text-ink text-sm font-semibold px-8 py-4 hover:bg-mint-400 transition-colors"
            >
              Empezar Ahora
            </MagneticButton>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ======================================================================
   FOOTER
   ====================================================================== */

function Footer() {
  const cols = [
    { title: "Navegación", items: ["Inicio", "Servicios", "Casos de Éxito", "Precios"] },
    { title: "Trabaja con Nosotros", items: ["Auditoría Gratuita", "Portfolio", "Únete al Equipo"] },
    { title: "Recursos", items: ["Academia", "Blog", "Plantillas", "Ayuda"] },
  ];
  return (
    <footer className="pt-20 border-t border-black/5">
      <div className="max-w-7xl mx-auto px-6">
        <div className="grid md:grid-cols-[1.4fr_repeat(3,1fr)] gap-10">
          <div>
            <div className="flex items-center gap-2 font-display font-bold text-lg">
              <LogoMark />
              <span className="logo-text">Infinity Pixel</span>
            </div>
            <p className="mt-4 text-sm text-ink/50 max-w-xs">
              Agencia de contenido para redes sociales con sede en Manizales, Caldas.
            </p>
          </div>
          {cols.map((c) => (
            <div key={c.title}>
              <p className="text-sm font-semibold mb-4">{c.title}</p>
              <ul className="space-y-2.5 text-sm text-ink/50">
                {c.items.map((i) => (
                  <li key={i}>
                    <a href="#" data-cursor="hover" className="hover:text-ink transition-colors">
                      {i}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div className="flex flex-col sm:flex-row justify-between items-center gap-4 py-8 mt-12 border-t border-black/5 text-xs text-ink/40">
          <span>© 2026 Infinity Pixel. Todos los derechos reservados.</span>
          <div className="flex gap-6">
            <a href="#" data-cursor="hover" className="hover:text-ink">
              Política de Privacidad
            </a>
            <a href="#" data-cursor="hover" className="hover:text-ink">
              Términos de Uso
            </a>
          </div>
        </div>
      </div>

      <div className="overflow-hidden select-none pointer-events-none">
        <p
          className="font-display font-bold text-[10vw] whitespace-nowrap leading-none text-center -mb-[1.6vw]"
          style={{ WebkitTextStroke: "1px rgba(10,10,12,0.12)", color: "transparent" }}
        >
          Infinity Pixel
        </p>
      </div>
    </footer>
  );
}

/* ======================================================================
   APP
   ====================================================================== */

function App() {
  useLenis();
  const mouse = useMouse();

  return (
    <>
      <div className="grain" />
      <CustomCursor mouse={mouse} />
      <ScrollProgressBar />
      <Navbar />
      <main>
        <Hero mouse={mouse} />
        <Ticker />
        <AgentsSection />
        <BeforeAfterSection />
        <RolesSection />
        <PricingSection />
        <ResourcesSection />
        <FinalCTA />
      </main>
      <Footer />
    </>
  );
}

createRoot(document.getElementById("root")).render(<App />);
