/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Icons (inline SVG) ---------- */
const Icon = ({ name, size = 22, stroke = 1.8 }) => {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case "monitor": return <svg {...common}><rect x="2" y="4" width="20" height="14" rx="2" /><path d="M8 21h8M12 18v3" /></svg>;
    case "refresh": return <svg {...common}><path d="M21 12a9 9 0 1 1-3-6.7" /><path d="M21 4v5h-5" /></svg>;
    case "megaphone": return <svg {...common}><path d="M3 11v2a2 2 0 0 0 2 2h2l8 4V5l-8 4H5a2 2 0 0 0-2 2Z" /><path d="M19 8a4 4 0 0 1 0 8" /></svg>;
    case "palette": return <svg {...common}><circle cx="12" cy="12" r="9" /><circle cx="7.5" cy="10.5" r="1" /><circle cx="11" cy="7" r="1" /><circle cx="15.5" cy="9" r="1" /><path d="M14 17a2 2 0 0 0 2-2c0-1-.5-1.5-.5-2.5s.5-1.5 1.5-1.5h1" /></svg>;
    case "search": return <svg {...common}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>;
    case "wrench": return <svg {...common}><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z" /></svg>;
    case "nut": return <svg {...common}><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S15.33 8 14.5 8 13 8.67 13 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S8.33 8 7.5 8 6 8.67 6 9.5 6.67 11 7.5 11z" transform="rotate(45 12 12)" /></svg>;
    case "arrow": return <svg {...common}><path d="M5 12h14M13 5l7 7-7 7" /></svg>;
    case "mail": return <svg {...common}><rect x="3" y="5" width="18" height="14" rx="2" /><path d="m3 7 9 6 9-6" /></svg>;
    case "phone": return <svg {...common}><path d="M22 17v3a2 2 0 0 1-2.2 2 19 19 0 0 1-8.3-3 19 19 0 0 1-6-6A19 19 0 0 1 2.5 4.2 2 2 0 0 1 4.5 2h3a2 2 0 0 1 2 1.7c.1.9.3 1.8.6 2.6a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.5-1.5a2 2 0 0 1 2.1-.5c.8.3 1.7.5 2.6.6a2 2 0 0 1 1.7 2Z" /></svg>;
    case "pin": return <svg {...common}><path d="M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0 1 18 0Z" /><circle cx="12" cy="10" r="3" /></svg>;
    case "check": return <svg {...common} strokeWidth="2.6"><path d="M5 12l5 5 9-11" /></svg>;
    case "menu": return <svg {...common}><path d="M3 6h18M3 12h18M3 18h18" /></svg>;
    case "ig": return <svg {...common}><rect x="3" y="3" width="18" height="18" rx="5" /><circle cx="12" cy="12" r="4" /><circle cx="17.5" cy="6.5" r="1" fill="currentColor" /></svg>;
    case "li": return <svg {...common}><rect x="3" y="3" width="18" height="18" rx="3" /><path d="M8 10v7M8 7v.01M12 17v-4a2 2 0 0 1 4 0v4M12 10v7" /></svg>;
    case "x": return <svg {...common}><path d="M4 4l16 16M20 4 4 20" /></svg>;
    case "be": return <svg {...common}><path d="M3 6h6a3 3 0 0 1 0 6H3zM3 12h7a3 3 0 0 1 0 6H3zM15 9h6M15 14h6a3 3 0 0 0-6 0v3a3 3 0 0 0 6 0" /></svg>;
    case "send": return <svg {...common}><path d="M22 2 11 13M22 2l-7 20-4-9-9-4z" /></svg>;
    default: return null;
  }
};

/* ---------- Decorative SVG cloud ---------- */
const SvgCloud = ({ className, style, fill = "white" }) => (
  <svg className={className} style={style} viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
    <path d="M40 78c-14 0-26-10-26-23 0-12 9-21 21-22 4-12 16-21 30-21 16 0 28 11 31 25 2 0 5-1 7-1 13 0 24 10 24 22 0 12-11 22-24 22Z" fill={fill} />
  </svg>
);

/* ---------- Header ---------- */
const Header = ({ active = "" }) => {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);
  const closeMenu = () => setMenuOpen(false);
  const nl = (id, label) => <a href={`#${id}`} className={active === id ? "active" : ""}>{label}</a>;
  const ml = (id, label) => (
    <a href={`#${id}`} onClick={closeMenu} className={active === id ? "active" : ""}>{label}</a>
  );
  return (
    <>
      <header className={`header ${scrolled ? "scrolled" : ""}`}>
        <a href="#top" className="brand">
          <img src="assets/nubea-logo.png" alt="Nubea Studio" />
          <span className="brand-name" style={{ color: 'var(--blue)' }}>Nubea<span className="dot" style={{ color: '#9CA3AF' }}>.studio</span></span>
        </a>
        <nav className="nav">
          {nl("inicio", "Inicio")}
          {nl("servicios", "Servicios")}
          {nl("proyectos", "Proyectos")}
          {nl("proceso", "Proceso")}
          {nl("contacto", "Contacto")}
        </nav>
        <div className="header-cta">
          <a href="#contacto" className="btn btn-primary">
            Pide tu web <Icon name="arrow" size={16} />
          </a>
          <button
            className={`menu-toggle ${menuOpen ? "is-open" : ""}`}
            aria-label="Menu"
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen(o => !o)}
          >
            <Icon name={menuOpen ? "x" : "menu"} size={20} />
          </button>
        </div>
      </header>
      <div className={`mobile-menu ${menuOpen ? "open" : ""}`} onClick={closeMenu}>
        <div className="mobile-menu-panel" onClick={e => e.stopPropagation()}>
          <nav className="mobile-nav">
            {ml("inicio", "Inicio")}
            {ml("servicios", "Servicios")}
            {ml("proyectos", "Proyectos")}
            {ml("proceso", "Proceso")}
            {ml("contacto", "Contacto")}
          </nav>
          <a href="#contacto" onClick={closeMenu} className="btn btn-primary mobile-cta">
            Pide tu web <Icon name="arrow" size={16} />
          </a>
        </div>
      </div>
    </>
  );
};

/* ---------- Hero ---------- */
const Hero = () => (
  <section id="inicio" className="hero" style={{ position: "relative", zIndex: 3, overflow: "visible", }}>
    <div className="cloud cloud-1"></div>
    <div className="cloud cloud-2"></div>
    <SvgCloud className="svg-cloud" style={{ top: "12%", left: "6%", width: 90, opacity: .65 }} />
    <SvgCloud className="svg-cloud" style={{ bottom: "16%", left: "42%", width: 70, opacity: .55 }} />
    <div className="container">
      <div className="hero-grid">
        <div>
          <span className="eyebrow reveal"><span className="dot"></span>Estudio digital · Zafra</span>
          <h1 className="reveal-blur" style={{ "--delay": "60ms" }}>
            Diseñamos webs<br /> que <span className="accent">elevan tu marca</span>
          </h1>
          <p className="lede reveal" style={{ "--delay": "160ms" }}>
            Creamos páginas web modernas, rediseños profesionales y estrategias digitales
            para que tu negocio destaque, conecte y crezca online.
          </p>
          <div className="hero-actions reveal" style={{ "--delay": "240ms" }}>
            <a href="#proyectos" className="btn btn-primary">Ver proyectos <Icon name="arrow" size={16} /></a>
            <a href="#contacto" className="btn btn-ghost">Contactar ahora</a>
          </div>
        </div>

        <div className="hero-visual reveal-right" style={{ "--delay": "200ms", display: "flex", alignItems: "center", justifyContent: "center", overflow: "visible" }}>
          <img
            src="assets/imagen_index.png"
            alt="Nubea Studio"
            style={{
              width: "120%",
              height: "auto",
              opacity: 0,
              animation: "floatIn 0.8s ease-out 200ms forwards",
              transition: "all 0.5s cubic-bezier(0.16, 1, 0.3, 1)",
              cursor: "pointer",
              filter: "drop-shadow(0 0 0 transparent)"
            }}
            onMouseEnter={e => {
              e.target.style.transform = "scale(1.12)";
              e.target.style.filter = "drop-shadow(0 30px 80px rgba(0, 87, 184, 0.5))";
            }}
            onMouseLeave={e => {
              e.target.style.transform = "scale(1)";
              e.target.style.filter = "drop-shadow(0 0 0 transparent)";
            }}
          />
          <style>{`
            @keyframes floatIn {
              from { opacity: 0; transform: translateY(30px) scale(0.85); }
              to { opacity: 1; transform: translateY(0) scale(1); }
            }
          `}</style>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Tech Strip ---------- */
const TECHS_ROW1 = [
  { name: "React", color: "#61DAFB" },
  { name: "JavaScript", color: "#F7DF1E" },
  { name: "TypeScript", color: "#3178C6" },
  { name: "Node.js", color: "#339933" },
  { name: "Python", color: "#3776AB" },
  { name: "PHP", color: "#A97BCA" },
  { name: "Laravel", color: "#FF2D20" },
  { name: "Django", color: "#44B78B" },
  { name: "Docker", color: "#2496ED" },
  { name: "AWS", color: "#FF9900" },
  { name: "Tailwind CSS", color: "#06B6D4" },
  { name: "Next.js", color: "#9BD0FF" },
];

const TECHS_ROW2 = [
  { name: "MySQL", color: "#4479A1" },
  { name: "MongoDB", color: "#47A248" },
  { name: "Git", color: "#F05032" },
  { name: "Linux", color: "#FCC624" },
  { name: "WordPress", color: "#21759B" },
  { name: "Figma", color: "#F24E1E" },
  { name: "HTML5", color: "#E34F26" },
  { name: "CSS3", color: "#1572B6" },
  { name: "PostgreSQL", color: "#336791" },
  { name: "Vue.js", color: "#4FC08D" },
  { name: "GraphQL", color: "#E10098" },
  { name: "Vite", color: "#BD34FE" },
];

const TechStrip = () => (
  <section id="stack" className="tech-strip">
    <div className="container tech-strip-header reveal">
      <span className="eyebrow eyebrow--dark"><span className="dot"></span>Stack tecnológico</span>
      <h2>Las herramientas que dominamos</h2>
      <p>Trabajamos con las tecnologías más actuales para construir webs rápidas, escalables y fáciles de mantener.</p>
    </div>
    <div className="tech-marquee-wrap">
      <div className="tech-track track-left">
        {[...TECHS_ROW1, ...TECHS_ROW2, ...TECHS_ROW1].map((t, i) => (
          <div key={i} className="tech-item">
            <span className="tech-dot" style={{ background: t.color, boxShadow: `0 0 8px ${t.color}88` }}></span>
            <span>{t.name}</span>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- Stats Strip ---------- */
const STATS = [
  { num: "7", label: "Proyectos Lanzados" },
  { num: "100%", label: "Satisfacción Cliente" },
  { num: "4.9", label: "Valoración Media" },
  { num: "14d", label: "Tiempo Entrega" },
];
const StatsStrip = () => (
  <section className="stats-strip">
    <div className="container stats-grid">
      {STATS.map((s, i) => (
        <div key={i} className="stat-item">
          <div className="stat-num">{s.num}</div>
          <div className="stat-label">{s.label}</div>
        </div>
      ))}
    </div>
  </section>
);

const LogoStrip = StatsStrip;

/* ---------- Services ---------- */
const SERVICES = [
  { id: "web-design", icon: "monitor", num: "01", color: "#0057B8", title: "Diseño de páginas web", desc: "Webs corporativas, landings y portfolios diseñados a medida. Rápidas, elegantes y centradas en convertir visitas en clientes." },
  { id: "web-redesign", icon: "refresh", num: "02", color: "#5aa5ec", title: "Rediseño web", desc: "Renovamos tu web actual con una experiencia moderna, mejor jerarquía visual y un sitio listo para crecer contigo." },
  { id: "marketing", icon: "megaphone", num: "03", color: "#21c46a", title: "Marketing digital", desc: "Campañas, contenido y embudos de captación pensados para mover tráfico cualificado a tu negocio cada mes." },
  { id: "branding", icon: "palette", num: "04", color: "#a78bfa", title: "Branding visual", desc: "Logotipo, paleta, tipografía y un sistema visual coherente que hace que tu marca se reconozca al primer vistazo." },
  { id: "seo", icon: "search", num: "05", color: "#f59e0b", title: "SEO básico optimizado", desc: "Estructura técnica, metadatos, copy y velocidad alineados para que Google posicione tu web por lo que importa." },
  { id: "maintenance", icon: "nut", num: "06", color: "#fb7185", title: "Mantenimiento web", desc: "Actualizaciones, copias de seguridad, soporte y mejoras continuas. Tu web siempre activa, segura y al día." },
];

const SERVICE_DETAILS = {
  "web-design": {
    gradient: "linear-gradient(160deg,#0057B8 0%,#003B7A 60%,#0d47a1 100%)",
    fullDesc: "Creamos webs desde cero que no solo son hermosas, sino que están diseñadas para convertir. Cada proyecto es un equilibrio perfecto entre estética, usabilidad y estrategia de negocio.",
    process: "Comenzamos con una sesión profunda para entender tu marca, audiencia y objetivos. Luego diseñamos wireframes interactivos, iteramos con tu feedback, y finalmente desarrollamos tu web con tecnologías modernas, responsive design y optimización de velocidad.",
    includes: ["Diseño UI/UX personalizado", "Prototipo interactivo navegable", "Desarrollo HTML/CSS/JavaScript", "Responsive en todos los dispositivos", "Optimización de velocidad (Lighthouse 90+)", "SEO técnico básico", "Análisis de competencia y usuarios", "Hasta 2 rondas de revisión"],
  },
  "web-redesign": {
    gradient: "linear-gradient(160deg,#5aa5ec 0%,#2d8cf5 60%,#0057B8 100%)",
    fullDesc: "Tu web actual tiene usuarios, pero pide a gritos una renovación. Hacemos rediseños que respetan tu historia digital mientras modernizamos la experiencia, mejoran las conversiones y actualizan el look.",
    process: "Auditamos tu web actual: rendimiento, SEO, UX, conversiones. Identificamos qué funciona y qué duele. Luego diseñamos la nueva versión manteniendo lo valioso y rediseñando sin piedad lo que no aporta. Migramos con cuidado, sin perder posicionamiento SEO.",
    includes: ["Auditoría completa de la web actual", "Análisis de tráfico y comportamiento", "Rediseño visual moderno", "Mejora de UX y flujos de conversión", "Migración segura sin pérdida de SEO", "Actualización técnica (velocidad, seguridad)", "Testing A/B si lo necesitas", "Capacitación sobre la nueva web"],
  },
  "marketing": {
    gradient: "linear-gradient(160deg,#21c46a 0%,#16a34a 60%,#0f7d3e 100%)",
    fullDesc: "Una web bonita sin tráfico es un cuadro en una habitación vacía. Traemos personas cualificadas a tu negocio a través de estrategia, contenido y campañas pensadas para resultados.",
    process: "Definimos tu buyer persona, canales más rentables y embudos de captación. Creamos contenido que atrae (blog, emails, redes), lanzamos campañas (Google Ads, Meta Ads), y medimos todo obsesivamente. Iteramos semana a semana para mejorar ROI.",
    includes: ["Estrategia digital completa", "Setup de Google Analytics y conversiones", "Auditoría de competencia y mercado", "Campañas en Google Ads o Meta Ads", "Creación de contenido (blog, guides)", "Email marketing automático", "Social media planning y publicación", "Reportes mensuales de resultados"],
  },
  "branding": {
    gradient: "linear-gradient(160deg,#a78bfa 0%,#8b5cf6 60%,#6d28d9 100%)",
    fullDesc: "Tu marca no es solo un logo. Es la suma de todas las decisiones visuales, tonales y emocionales que haces. Construimos identidades visuales coherentes que se reconocen al primer vistazo y generan confianza.",
    process: "Exploramos tu visión, valores y mercado. Creamos múltiples direcciones visuales, probamos con tu audiencia y refinamos. El resultado es: logotipo, paleta de colores, tipografía, iconografía y guía de estilo completa para que todo sea coherente.",
    includes: ["Workshop de descubrimiento de marca", "Análisis de competencia visual", "3 direcciones de logo a elegir", "Variaciones de logo (horizontal, ícono, etc)", "Paleta de colores profesional (6+ colores)", "Tipografía primaria y secundaria", "Iconografía custom", "Guía de estilo de marca (50+ páginas)"],
  },
  "seo": {
    gradient: "linear-gradient(160deg,#f59e0b 0%,#d97706 60%,#b45309 100%)",
    fullDesc: "Google es el vendedor más poderoso que no pagas directamente. Optimizamos tu web para que posicione por lo que importa: las palabras que tus clientes buscan cuando necesitan lo que vendes.",
    process: "Investigamos keywords rentables en tu nicho. Auditamos tu web actual (estructura, velocidad, content gaps). Optimizamos on-page: títulos, meta descriptions, headings, contenido. Mejoramos velocidad, mobile experience y hacemos que Google entienda mejor tu web.",
    includes: ["Investigación de palabras clave (50+ keywords)", "Auditoría SEO técnica completa", "Optimización on-page (15+ páginas)", "Mejora de velocidad de carga", "Mobile experience optimization", "Setup de Search Console y seguimiento", "Contenido de alto valor para rankear", "Reportes mensuales de posiciones"],
  },
  "maintenance": {
    gradient: "linear-gradient(160deg,#fb7185 0%,#f43f5e 60%,#e11d48 100%)",
    fullDesc: "Después del lanzamiento, la web requiere cuidado. Actualizaciones de seguridad, copias de seguridad, mejoras continuas. No puedes estar pendiente 24/7 de eso: nosotros nos encargamos.",
    process: "Nos suscribimos a tu web. Vigilamos la seguridad, hacemos backups automáticos semanales, actualizamos plugins y dependencias. Si algo falla, respondemos en menos de 24h. También añadimos mejoras: analytics, optimizaciones basadas en datos, nuevas features.",
    includes: ["Monitoreo 24/7 de salud de la web", "Backups automáticos semanales", "Actualizaciones de seguridad", "Parches y fixes menores", "Análisis de velocidad y rendimiento", "Optimizaciones basadas en datos", "Soporte técnico por email/Slack", "Reportes mensuales de actividad"],
  },
};

/* --- Service modal --- */
const ServiceModal = ({ service, onClose }) => {
  const d = SERVICE_DETAILS[service.id];
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-panel" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">
          <Icon name="x" size={18} />
        </button>

        <div className="modal-hero" style={{ background: d.gradient }}>
          <div className="modal-hero-text">
            <span className="eyebrow eyebrow--dark"><span className="dot"></span>Servicio · {service.num}</span>
            <h2>{service.title}</h2>
            <p>{d.fullDesc}</p>
          </div>
          <div className="modal-service-icon">
            <Icon name={service.icon} size={48} />
          </div>
        </div>

        <div className="modal-body">
          <div className="modal-cols">
            <div className="modal-desc">
              <h3>Cómo lo hacemos</h3>
              <p>{d.process}</p>
            </div>
            <div className="modal-features">
              <h3>Incluye</h3>
              <ul className="modal-list">
                {d.includes.map((item, i) => (
                  <li key={i}><Icon name="check" size={14} />{item}</li>
                ))}
              </ul>
            </div>
          </div>
          <div className="modal-actions">
            <a href="#contacto" className="btn btn-primary" onClick={onClose}>
              Hablemos de esto <Icon name="arrow" size={16} />
            </a>
            <button className="btn btn-ghost" onClick={onClose}>Cerrar</button>
          </div>
        </div>
      </div>
    </div>
  );
};

const ServiceCard = ({ s, i, onOpen }) => {
  const ref = useRef(null);

  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const xPct = (e.clientX - r.left) / r.width;
    const yPct = (e.clientY - r.top) / r.height;
    const rx = (yPct - 0.5) * -12;
    const ry = (xPct - 0.5) * 12;
    ref.current.style.transform = `perspective(700px) rotateX(${rx}deg) rotateY(${ry}deg) translateY(-10px) scale(1.01)`;
    ref.current.style.setProperty("--mx", (xPct * 100) + "%");
    ref.current.style.setProperty("--my", (yPct * 100) + "%");
  };

  const onLeave = () => {
    ref.current.style.transform = "";
  };

  return (
    <div
      className="service-card reveal-scale svc-clickable"
      ref={ref}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
      onClick={() => onOpen(s.id)}
      style={{ "--delay": `${i * 90}ms`, "--card-color": s.color }}
    >
      <div className="service-card-num" style={{ opacity: 0.18 }}>{s.num}</div>
      <div className="service-icon"><Icon name={s.icon} size={26} /></div>
      <h3>{s.title}</h3>
      <p>{s.desc}</p>
      <span className="arrow-link">Saber más <Icon name="arrow" size={14} /></span>
    </div>
  );
};

const Services = () => {
  const [openService, setOpenService] = useState(null);
  return (
    <section id="servicios" className="services">
      {openService && <ServiceModal service={SERVICES.find(s => s.id === openService)} onClose={() => setOpenService(null)} />}

      <SvgCloud fill="#d0e8ff" className="svc-cloud svc-cloud--a" />
      <SvgCloud fill="#c8e2ff" className="svc-cloud svc-cloud--b" />
      <SvgCloud fill="#daeeff" className="svc-cloud svc-cloud--c" />
      <SvgCloud fill="#c4ddf8" className="svc-cloud svc-cloud--d" />
      <div className="container">
        <div className="section-head reveal-blur">
          <span className="eyebrow"><span className="dot"></span>Servicios</span>
          <h2>Todo lo que necesita tu marca para destacar online.</h2>
          <p style={{ marginTop: 14, fontSize: 17, color: "var(--ink-3)" }}>
            De la idea al lanzamiento: diseño, desarrollo, marketing y mantenimiento — bajo el mismo equipo.
          </p>
        </div>
        <div className="services-grid">
          {SERVICES.map((s, i) => <ServiceCard key={s.id} s={s} i={i} onOpen={setOpenService} />)}
        </div>
      </div>
    </section>
  );
};

/* ---------- Counter ---------- */
const Counter = ({ to, suffix = "", prefix = "", duration = 1400 }) => {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(to * eased));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{prefix}{val}{suffix}</span>;
};

/* ---------- Value / Differential ---------- */
const BENEFITS = [
  { icon: "monitor", title: "Diseño estratégico", desc: "Cada pixel sirve a tu negocio, no solo a la estética" },
  { icon: "refresh", title: "Performance garantizado", desc: "Webs rápidas que no hacen esperar a tus clientes" },
  { icon: "megaphone", title: "Orientado a resultados", desc: "Conversiones, tráfico y engagement medibles" },
  { icon: "wrench", title: "Soporte continuo", desc: "Mantenimiento, mejoras y actualizaciones incluidas" },
];

const Value = () => (
  <section className="value">
    <div className="value-bg">
      <div className="value-orb a"></div>
      <div className="value-orb b"></div>
      <SvgCloud className="value-cloud x" style={{ top: "12%", left: "10%", width: 90 }} />
      <SvgCloud className="value-cloud y" style={{ bottom: "12%", right: "12%", width: 110 }} />
    </div>
    <div className="container value-grid">
      <div className="value-copy reveal-left">
        <span className="eyebrow eyebrow--dark"><span className="dot"></span>Por qué Nubea</span>
        <h2>Tu marca no necesita solo una web.<br />Necesita <em>presencia</em>.</h2>
        <p>
          Combinamos diseño, estrategia y tecnología para crear experiencias digitales
          que transmiten confianza desde el primer clic — y rinden cada mes.
        </p>
        <div className="metrics">
          {BENEFITS.map((b, i) => (
            <div key={i} className="metric reveal-left benefit-card" style={{ "--delay": `${i * 90}ms` }}>
              <div className="benefit-icon"><Icon name={b.icon} size={24} /></div>
              <div className="benefit-content">
                <div className="benefit-title">{b.title}</div>
                <div className="benefit-desc">{b.desc}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="value-visual reveal-right" style={{ "--delay": "200ms" }}>
        <div className="vv-card vv-main">
          <div className="browser-bar">
            <div className="dot-bar"><i></i><i></i><i></i></div>
            <div className="browser-url">tu-web-final.com</div>
          </div>
          <div className="vv-body">
            <div style={{ padding: "24px", textAlign: "center" }}>
              <div style={{ fontSize: "14px", color: "rgba(255,255,255,.6)", marginBottom: "16px" }}>Resultado real de nuestro trabajo</div>
              <div style={{ fontSize: "32px", fontWeight: "800", color: "white", marginBottom: "20px" }}>Tu marca online</div>
              <div style={{ fontSize: "13px", color: "rgba(255,255,255,.7)", lineHeight: "1.6" }}>
                Diseñada para convertir.<br />Optimizada para crecer.<br />Lista para el mundo.
              </div>
            </div>
          </div>
        </div>
        <div className="vv-card vv-mini">
          <div className="vv-mini-title">Proceso</div>
          <div style={{ padding: "16px 0", textAlign: "center", fontSize: "13px", color: "rgba(255,255,255,.8)" }}>
            <div style={{ marginBottom: "12px" }}>📋 Descubrimiento</div>
            <div style={{ marginBottom: "12px" }}>🎨 Diseño</div>
            <div style={{ marginBottom: "12px" }}>⚙️ Desarrollo</div>
            <div>🚀 Lanzamiento</div>
          </div>
        </div>
        <div className="vv-card vv-tag">
          <span className="pulse"></span>Proyectos en vivo
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Projects ---------- */
const LEGO_COLORS = [
  "#E3000B", "#006CB7", "#F5C400", "#00A846",
  "#F47422", "#FFFFFF", "#006CB7", "#E3000B",
  "#00A846", "#F5C400", "#F47422", "#E3000B",
];

const PROJECTS = [
  { id: "campitoo", name: "El Campito", cat: "Web corporativa", year: "2025", emoji: "🌿", bg: "assets/elcampito/elcampito_entorno.png", overlay: "rgba(20, 20, 15, 0.96)", accentOrb: "rgba(74,222,128,0.15)", desc: "Restaurante y espacio de ocio al aire libre en Zafra. Web corporativa con galería, carta y formulario de reservas." },
  { id: "clicknbeer", name: "ClicknBeer", cat: "E-commerce", year: "2025", emoji: "🍺", bg: "assets/clicknbeer/Index1.png", overlay: "rgba(120, 74, 3, 0.96)", accentOrb: "rgba(212,131,10,0.16)", desc: "Tienda online de cervezas artesanales. Catálogo filtrable, carrito y sistema de suscripción mensual." },
  { id: "abedules", name: "Los Abedules", cat: "Web corporativa", year: "2025", emoji: "🌲", bg: "assets/los_abedules/index.png", overlay: "rgba(26, 47, 26, 0.97)", accentOrb: "rgba(134,239,172,0.12)", desc: "Hotel rural con encanto. Web de presentación con reservas, galería editorial y blog de experiencias." },
  { id: "auradental", name: "Aura Dental", cat: "Landing", year: "2026", emoji: "✨", bg: "assets/clinicadental/clinica-inicio.png", overlay: "rgba(15, 31, 46, 0.95)", accentOrb: "rgba(126,182,255,0.14)", desc: "Landing de captación para clínica dental. Cita online, tratamientos y reseñas de pacientes integrados." },
  { id: "dentify", name: "Dentify", cat: "Landing", year: "2026", emoji: "🦷", bg: "assets/clinicadentalisra/adminIndex.png", overlay: "rgba(10, 22, 40, 0.97)", accentOrb: "rgba(99,179,237,0.14)", desc: "App web para gestión de citas en clínica dental. Panel, historial y recordatorios automáticos." },
  { id: "legodjango", name: "Lego Django", cat: "Portfolio", year: "2025", emoji: "🧱", bg: "assets/lego/lego-incio.png", overlay: "rgba(20, 20, 20, 0.97)", accentOrb: "rgba(255,208,0,0.14)", desc: "Tienda de sets Lego con Django y Python. Búsqueda avanzada, valoraciones y panel de administración." },
];


/* Dot-grid pattern para project cards */
const ProjectDotGrid = () => (
  <svg className="pc-dotgrid" viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
    <defs>
      <pattern id="dots" x="0" y="0" width="30" height="30" patternUnits="userSpaceOnUse">
        <circle cx="15" cy="15" r="1.5" fill="rgba(255,255,255,0.08)" />
      </pattern>
    </defs>
    <rect width="100%" height="100%" fill="url(#dots)" />
  </svg>
);


const Projects = () => (
  <section id="proyectos" className="projects">
    <SvgCloud fill="#c2dcf7" className="proj-cloud proj-cloud--a" />
    <SvgCloud fill="#b8d4f5" className="proj-cloud proj-cloud--b" />
    <SvgCloud fill="#cde5ff" className="proj-cloud proj-cloud--c" />
    <SvgCloud fill="#b0ceee" className="proj-cloud proj-cloud--d" />

    <div className="container">
      <div className="section-head reveal-blur">
        <span className="eyebrow"><span className="dot"></span>Proyectos seleccionados</span>
        <h2>Trabajo reciente que estamos orgullosos de mostrar.</h2>
        <p style={{ marginTop: 14, fontSize: 17, color: "var(--ink-3)" }}>
          Una pequeña selección de marcas con las que hemos colaborado este último año.
        </p>
      </div>

      <div className="projects-grid">
        {PROJECTS.map((p, i) => (
          <a
            key={p.name}
            href={`proyectos/${p.id}.html`}
            className="project-card reveal-scale"
            style={{
              "--delay": `${i * 70}ms`,
              "--overlay-color": p.overlay,
              backgroundImage: `url('${p.bg}')`,
              textDecoration: "none",
              color: "white",
              display: "block"
            }}
          >
            <ProjectDotGrid />
            <span className="pc-watermark">{String(i+1).padStart(2,'0')}</span>

            <div className="pc-top">
              <span className="pc-cat">{p.cat}</span>
              <span className="pc-year">{p.year}</span>
            </div>

            <div className="pc-body">
              <div className="pc-emoji">{p.emoji}</div>
              <h3 className="pc-title">{p.name}</h3>
              <p className="pc-desc">{p.desc}</p>
            </div>

            <div className="pc-footer">
              <span className="pc-cta">
                Ver proyecto <Icon name="arrow" size={13} />
              </span>
            </div>

            <div className="pc-orb" style={{ background: p.accentOrb }} />
          </a>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- Process ---------- */
const STEPS = [
  { n: "01", title: "Escuchamos tu idea", desc: "Sesión de descubrimiento para entender tu marca, audiencia y objetivos antes de tocar un píxel." },
  { n: "02", title: "Diseñamos la propuesta", desc: "Wireframes, dirección visual y prototipo navegable. Iteramos contigo hasta el detalle final." },
  { n: "03", title: "Creamos tu web", desc: "Desarrollo a medida, contenido, animaciones y rendimiento. Calidad pixel-perfect en cada pantalla." },
  { n: "04", title: "Lanzamos y optimizamos", desc: "Despliegue, analítica y mejora continua. Hacemos que tu web siga creciendo después del go-live." },
];

const Process = () => (
  <section id="proceso" className="process">
    <SvgCloud className="svg-cloud" style={{ top: "10%", left: "6%", width: 70, opacity: .35 }} />
    <SvgCloud className="svg-cloud" style={{ top: "20%", right: "8%", width: 90, opacity: .35 }} />
    <div className="container">
      <div className="section-head reveal-blur">
        <span className="eyebrow"><span className="dot"></span>Cómo trabajamos</span>
        <h2>Así llevamos tu idea a la nube.</h2>
      </div>
      <div className="process-rail">
        {STEPS.map((s, i) => (
          <div key={s.n} className="step reveal-pop" style={{ "--delay": `${i * 110}ms` }}>
            <div className="step-num">{s.n}</div>
            <h3>{s.title}</h3>
            <p>{s.desc}</p>
          </div>
        ))}
      </div>
    </div>
  </section>
);

/* ---------- CTA ---------- */
const CtaBand = () => (
  <section className="cta-band">
    <div className="container">
      <div className="cta-inner reveal-scale">
        <svg className="cta-cloud a" viewBox="0 0 200 100"><path d="M40 78c-14 0-26-10-26-23 0-12 9-21 21-22 4-12 16-21 30-21 16 0 28 11 31 25 2 0 5-1 7-1 13 0 24 10 24 22 0 12-11 22-24 22Z" /></svg>
        <svg className="cta-cloud b" viewBox="0 0 200 100"><path d="M40 78c-14 0-26-10-26-23 0-12 9-21 21-22 4-12 16-21 30-21 16 0 28 11 31 25 2 0 5-1 7-1 13 0 24 10 24 22 0 12-11 22-24 22Z" /></svg>
        <svg className="cta-cloud c" viewBox="0 0 200 100"><path d="M40 78c-14 0-26-10-26-23 0-12 9-21 21-22 4-12 16-21 30-21 16 0 28 11 31 25 2 0 5-1 7-1 13 0 24 10 24 22 0 12-11 22-24 22Z" /></svg>
        <h2>¿Listo para subir tu marca a la nube?</h2>
        <p>Cuéntanos tu proyecto. Te respondemos en menos de 24 h con una propuesta clara, sin compromiso y con el siguiente paso definido.</p>
        <div className="actions">
          <a href="#contacto" className="btn btn-primary">Hablemos de tu proyecto <Icon name="arrow" size={16} /></a>
          <a href="#proyectos" className="btn btn-glass">Ver proyectos</a>
        </div>
      </div>
    </div>
  </section>
);

/* ---------- Contact ---------- */
/* ⚙️  CONFIGURACIÓN: obtén tu clave gratuita en https://web3forms.com
   Introduce tu email nubeaestudio@gmail.com, copia la clave y pégala aquí: */
const W3F_KEY = "3c99b4e5-87f7-4e4d-91a1-29ac74f9cf8d";

const Contact = () => {
  const [form, setForm] = useState({ name: "", email: "", company: "", service: "", message: "" });
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState("idle"); /* idle | sending | sent | error */
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = "Indica tu nombre";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = "Email no válido";
    if (!form.service) errs.service = "Elige un servicio";
    if (form.message.trim().length < 10) errs.message = "Cuéntanos un poco más (10+ caracteres)";
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setStatus("sending");
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: W3F_KEY,
          subject: `Nuevo contacto Nubea Studio — ${form.service}`,
          from_name: form.name,
          replyto: form.email,
          name: form.name,
          email: form.email,
          message: `Empresa: ${form.company || "No indicada"}\nServicio: ${form.service}\n\n${form.message}`,
        }),
      });
      const data = await res.json();
      setStatus(data.success ? "sent" : "error");
    } catch {
      setStatus("error");
    }
  };

  const reset = () => {
    setStatus("idle");
    setForm({ name: "", email: "", company: "", service: "", message: "" });
  };

  return (
    <section id="contacto" className="contact">
      <div className="container">
        <div className="section-head reveal-blur">
          <span className="eyebrow"><span className="dot"></span>Contacto</span>
          <h2>Hablemos de tu próximo proyecto.</h2>
          <p style={{ marginTop: 14, fontSize: 17, color: "var(--ink-3)" }}>
            Cuéntanos qué necesitas. Volvemos a ti en menos de 24 h con próximos pasos.
          </p>
        </div>

        <div className="contact-grid">
          <aside className="contact-info reveal-left">
            <h3>Estamos a un mensaje de distancia</h3>
            <p>Nos encanta conocer marcas nuevas. Escríbenos por el canal que prefieras.</p>

            <div className="contact-list">
              <div className="contact-item">
                <div className="ico"><Icon name="mail" size={18} /></div>
                <div><div className="label">Email</div><div>nubeaestudio@gmail.com</div></div>
              </div>
              <div className="contact-item">
                <div className="ico"><Icon name="phone" size={18} /></div>
                <div><div className="label">Teléfono</div><div>+34 600 000 000</div></div>
              </div>
              <div className="contact-item">
                <div className="ico"><Icon name="ig" size={18} /></div>
                <div><div className="label">Instagram</div><div><a href="https://www.instagram.com/nubea__studio/" target="_blank" rel="noopener noreferrer" style={{ color: "var(--blue)", textDecoration: "none" }}>@nubeaestudio</a></div></div>
              </div>
            </div>
          </aside>

          <form className="form-card reveal-right" onSubmit={submit} noValidate>
            <div className="form-grid">
              <div className={`field ${errors.name ? "invalid" : ""}`}>
                <label>Nombre</label>
                <input type="text" placeholder="Tu nombre" value={form.name} onChange={set("name")} disabled={status === "sending"} />
                {errors.name && <div className="err">{errors.name}</div>}
              </div>
              <div className={`field ${errors.email ? "invalid" : ""}`}>
                <label>Email</label>
                <input type="email" placeholder="tu@email.com" value={form.email} onChange={set("email")} disabled={status === "sending"} />
                {errors.email && <div className="err">{errors.email}</div>}
              </div>
              <div className="field">
                <label>Empresa</label>
                <input type="text" placeholder="Nombre de tu empresa" value={form.company} onChange={set("company")} disabled={status === "sending"} />
              </div>
              <div className={`field ${errors.service ? "invalid" : ""}`}>
                <label>Servicio que necesitas</label>
                <select
                  value={form.service}
                  onChange={set("service")}
                  disabled={status === "sending"}
                  className={form.service ? "has-value" : ""}
                >
                  <option value="">Selecciona un servicio</option>
                  <option>Diseño de página web</option>
                  <option>Rediseño web</option>
                  <option>Marketing digital</option>
                  <option>Branding visual</option>
                  <option>SEO básico</option>
                  <option>Mantenimiento web</option>
                </select>
                {errors.service && <div className="err">{errors.service}</div>}
              </div>
              <div className={`field full ${errors.message ? "invalid" : ""}`}>
                <label>Mensaje</label>
                <textarea placeholder="Cuéntanos sobre tu proyecto, plazos, referencias..." value={form.message} onChange={set("message")} disabled={status === "sending"}></textarea>
                {errors.message && <div className="err">{errors.message}</div>}
              </div>
            </div>

            <div className="form-submit">
              <span className="legal">Al enviar aceptas nuestra política de privacidad.</span>
              <button type="submit" className={`btn btn-primary ${status === "sending" ? "btn-sending" : ""}`} disabled={status === "sending"}>
                {status === "sending"
                  ? <><span className="spinner"></span>Enviando…</>
                  : <>Enviar mensaje <Icon name="send" size={16} /></>
                }
              </button>
            </div>

            {status === "error" && (
              <div className="form-error">
                <strong>No se pudo enviar el mensaje.</strong>
                <span>Inténtalo de nuevo o escríbenos directamente a <strong>nubeaestudio@gmail.com</strong></span>
                <button type="button" className="btn btn-ghost" style={{ marginLeft: "auto" }} onClick={() => setStatus("idle")}>Reintentar</button>
              </div>
            )}

            {status === "sent" && (
              <div className="form-success">
                <div className="check"><Icon name="check" size={28} /></div>
                <h3>¡Mensaje enviado!</h3>
                <p>Gracias {form.name.split(" ")[0]}. Te respondemos a {form.email} en menos de 24 horas.</p>
                <button type="button" className="btn btn-ghost" onClick={reset}>
                  Enviar otro mensaje
                </button>
              </div>
            )}
          </form>
        </div>
      </div>
    </section>
  );
};

/* ---------- Footer ---------- */
const Footer = () => (
  <footer className="footer">
    <div className="container">
      <div>
        <div className="brand" style={{ marginBottom: 6 }}>
          <img src="assets/nubea-logo.png" alt="Nubea Studio" />
          <span className="brand-name" style={{ color: "white" }}>Nubea<span style={{ color: "#7eb6ff" }}>.studio</span></span>
        </div>
        <p>Diseño web, rediseños y marketing digital para marcas que quieren crecer. Subimos tu negocio a la nube — ligero, rápido y memorable.</p>
      </div>
      <div>
        <h4>Navegación</h4>
        <ul>
          <li><a href="#inicio">Inicio</a></li>
          <li><a href="#servicios">Servicios</a></li>
          <li><a href="#proyectos">Proyectos</a></li>
          <li><a href="#contacto">Contacto</a></li>
        </ul>
      </div>
      <div>
        <h4>Contacto</h4>
        <ul>
          <li><a href="mailto:hola@nubeastudio.com">nubeaestudio@gmail.com</a></li>
          <li><a href="#contacto">+34 600 000 000</a></li>
        </ul>
      </div>
    </div>
    <div className="container footer-bottom">
      <span>© 2026 Nubea Studio. Todos los derechos reservados.</span>
      <span>Hecho con ☁︎ en Zafra</span>
    </div>
  </footer>
);

/* ---------- Scroll animations & parallax ---------- */
const REVEAL_SEL = ".reveal, .reveal-left, .reveal-right, .reveal-scale, .reveal-blur, .reveal-pop";

const useReveal = () => {
  useEffect(() => {
    const els = document.querySelectorAll(REVEAL_SEL);
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          en.target.classList.add("in");
          io.unobserve(en.target);
        }
      });
    }, { threshold: 0.1, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
};

const useActiveSection = () => {
  const [active, setActive] = useState("inicio");
  useEffect(() => {
    const ids = ["inicio", "servicios", "proyectos", "proceso", "contacto"];
    const sections = ids.map(id => document.getElementById(id)).filter(Boolean);
    const io = new IntersectionObserver(
      (entries) => { entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); }); },
      { threshold: 0.3, rootMargin: "-8% 0px -8% 0px" }
    );
    sections.forEach(s => io.observe(s));
    return () => io.disconnect();
  }, []);
  return active;
};

const useParallax = () => {
  useEffect(() => {
    const isMobile = () => window.innerWidth <= 860;
    const onScroll = () => {
      if (isMobile()) return;
      const scrollY = window.scrollY;
      document.querySelectorAll(".svg-cloud, .cloud").forEach((el) => {
        const speed = el.classList.contains("cloud") ? 0.5 : 0.3;
        el.style.transform = `translateY(${scrollY * speed}px)`;
      });
      const heroGrid = document.querySelector(".hero-grid");
      if (heroGrid) heroGrid.style.transform = `translateY(${scrollY * 0.18}px)`;
    };
    const onResize = () => {
      if (isMobile()) {
        document.querySelectorAll(".svg-cloud, .cloud").forEach(el => el.style.transform = "");
        const heroGrid = document.querySelector(".hero-grid");
        if (heroGrid) heroGrid.style.transform = "";
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onResize, { passive: true });
    onResize();
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onResize);
    };
  });
};

/* ---------- Scroll Experience (Nubea Process) ---------- */
const ScrollExperience = () => {
  const containerRef = useRef(null);
  const centerRef = useRef(null);
  const partLeftRef = useRef(null);
  const partRightRef = useRef(null);
  const partTopRef = useRef(null);
  const partBottomRef = useRef(null);
  const linesRef = useRef(null);
  const titleRef = useRef(null);

  useEffect(() => {
    const gsapScript = document.createElement('script');
    gsapScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js';
    gsapScript.async = true;

    gsapScript.onload = () => {
      const stScript = document.createElement('script');
      stScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js';
      stScript.async = true;

      stScript.onload = () => {
        window.gsap.registerPlugin(window.ScrollTrigger);

        if (containerRef.current && centerRef.current) {
          const timeline = window.gsap.timeline({
            scrollTrigger: {
              trigger: '.nubea-scroll-section',
              start: 'top top',
              end: 'bottom center',
              scrub: 1,
              pin: '.nubea-scroll-container',
              markers: false,
            }
          });

          // Fase 1: Centro se expande y pulsa (0 - 0.3)
          timeline
            .to(centerRef.current, {
              scale: 1.15,
              boxShadow: '0 30px 80px rgba(0, 87, 184, 0.5)',
              duration: 0.6,
              ease: 'power2.inOut'
            }, 0)

            // Fase 2: Las líneas de conexión aparecen (0.1 - 0.5)
            .to(linesRef.current, {
              opacity: 0.6,
              duration: 0.5,
              ease: 'sine.inOut'
            }, 0.1, '-=0.5')

            // Fase 3: Las 4 partes emergen suavemente (0.2 - 0.9)
            .to([partLeftRef.current, partRightRef.current, partTopRef.current, partBottomRef.current], {
              opacity: 1,
              duration: 0.6,
              ease: 'power2.out'
            }, 0.2, '-=0.4')

            // Fase 4: Las partes se mueven hacia sus órbitas finales con easing suave
            .to(partLeftRef.current, {
              x: -180,
              duration: 1.2,
              ease: 'cubic.inOut'
            }, 0.3, '-=0.4')

            .to(partRightRef.current, {
              x: 180,
              duration: 1.2,
              ease: 'cubic.inOut'
            }, 0.3, '-=1.2')

            .to(partTopRef.current, {
              y: -180,
              duration: 1.2,
              ease: 'cubic.inOut'
            }, 0.3, '-=1.2')

            .to(partBottomRef.current, {
              y: 180,
              duration: 1.2,
              ease: 'cubic.inOut'
            }, 0.3, '-=1.2')

            // Fase 5: Rotaciones suaves y sincronizadas (0.5 - fin)
            .to(containerRef.current, {
              rotationY: 360,
              rotationX: 0,
              duration: 2,
              ease: 'none'
            }, 0.5, '-=0.9')

            // Fase 6: Las partes escalan ligeramente en órbita
            .to([partLeftRef.current, partRightRef.current, partTopRef.current, partBottomRef.current], {
              scale: 1.05,
              duration: 0.8,
              ease: 'sine.inOut',
              yoyo: true,
              repeat: -1
            }, 0.5, '-=0.9')

            // Fase 7: Centro pulsa sutilmente
            .to(centerRef.current, {
              scale: 1.08,
              duration: 1,
              ease: 'sine.inOut',
              yoyo: true,
              repeat: -1
            }, 0.5, '-=0.9');

          const textTimeline = window.gsap.timeline({
            scrollTrigger: {
              trigger: '.nubea-scroll-section',
              start: 'top top',
              end: 'bottom center',
              scrub: 1,
            }
          });

          textTimeline
            .to(titleRef.current, { opacity: 1, duration: 0.5 }, 0)
            .to(titleRef.current, { opacity: 0, duration: 0.4 }, 0.9);

          window.ScrollTrigger.refresh();
        }
      };
      document.head.appendChild(stScript);
    };
    document.head.appendChild(gsapScript);

    return () => window.ScrollTrigger && window.ScrollTrigger.refresh();
  }, []);

  return (
    <section className="nubea-scroll-section" style={{ position: 'relative', height: '350vh', background: 'var(--white)' }}>
      <div className="nubea-scroll-container" style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', background: 'linear-gradient(180deg, var(--blue-soft) 0%, var(--blue-mist) 100%)' }}>
        <div style={{ position: 'absolute', top: '60px', left: 0, right: 0, textAlign: 'center', pointerEvents: 'none', zIndex: 5 }}>
          <h2 ref={titleRef} style={{ fontSize: '2rem', fontWeight: 900, color: 'var(--blue)', opacity: 0, margin: 0 }}>Así Llevamos Tu Idea a Realidad</h2>
        </div>

        <div className="product-wrapper" style={{ perspective: '1200px', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
          <div ref={containerRef} style={{ position: 'relative', width: '420px', height: '420px', maxWidth: '85vw', maxHeight: '85vh', transformStyle: 'preserve-3d' }}>
            {/* Líneas de conexión SVG */}
            <svg ref={linesRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0, zIndex: 0, pointerEvents: 'none' }}>
              <defs>
                <linearGradient id="lineGrad1" x1="0%" y1="0%" x2="100%" y2="0%">
                  <stop offset="0%" stopColor="rgba(0, 87, 184, 0.4)" />
                  <stop offset="100%" stopColor="rgba(0, 87, 184, 0.1)" />
                </linearGradient>
              </defs>
              <line x1="50%" y1="50%" x2="50%" y2="10%" stroke="url(#lineGrad1)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
              <line x1="50%" y1="50%" x2="90%" y2="50%" stroke="url(#lineGrad1)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
              <line x1="50%" y1="50%" x2="50%" y2="90%" stroke="url(#lineGrad1)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
              <line x1="50%" y1="50%" x2="10%" y2="50%" stroke="url(#lineGrad1)" strokeWidth="2" vectorEffect="non-scaling-stroke" />
            </svg>

            {/* Centro: Proceso Nubea */}
            <div ref={centerRef} style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', borderRadius: '40px', overflow: 'hidden', background: 'linear-gradient(135deg, var(--blue) 0%, var(--blue-deep) 100%)', border: '3px solid white', backdropFilter: 'blur(20px)', transformStyle: 'preserve-3d', boxShadow: '0 20px 60px rgba(0, 87, 184, 0.3)', transition: 'box-shadow 0.3s ease' }}>
              <div style={{ fontSize: '3rem', marginBottom: '8px' }}>🚀</div>
              <div style={{ color: 'white', fontWeight: 800, fontSize: '1.3rem', textAlign: 'center' }}>Nubea</div>
              <div style={{ color: 'rgba(255,255,255,0.8)', fontWeight: 600, fontSize: '0.85rem', marginTop: '4px' }}>Diseño + Estrategia</div>
            </div>

            {/* Partes del proceso */}
            <div ref={partLeftRef} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '150px', height: '150px', borderRadius: '28px', background: 'linear-gradient(135deg, rgba(0, 87, 184, 0.9) 0%, var(--blue) 100%)', border: '2px solid white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: '1rem', color: 'white', transformStyle: 'preserve-3d', opacity: 0, boxShadow: '0 10px 30px rgba(0, 87, 184, 0.2)', textAlign: 'center', gap: '6px', padding: '12px', transition: 'box-shadow 0.3s ease' }}>
              <div style={{ fontSize: '2rem' }}>👂</div>
              <div>Escuchamos</div>
            </div>

            <div ref={partRightRef} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '150px', height: '150px', borderRadius: '28px', background: 'linear-gradient(135deg, rgba(0, 87, 184, 0.9) 0%, var(--blue) 100%)', border: '2px solid white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: '1rem', color: 'white', transformStyle: 'preserve-3d', opacity: 0, boxShadow: '0 10px 30px rgba(0, 87, 184, 0.2)', textAlign: 'center', gap: '6px', padding: '12px', transition: 'box-shadow 0.3s ease' }}>
              <div style={{ fontSize: '2rem' }}>💻</div>
              <div>Creamos</div>
            </div>

            <div ref={partTopRef} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '150px', height: '150px', borderRadius: '28px', background: 'linear-gradient(135deg, rgba(0, 87, 184, 0.9) 0%, var(--blue) 100%)', border: '2px solid white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: '1rem', color: 'white', transformStyle: 'preserve-3d', opacity: 0, boxShadow: '0 10px 30px rgba(0, 87, 184, 0.2)', textAlign: 'center', gap: '6px', padding: '12px', transition: 'box-shadow 0.3s ease' }}>
              <div style={{ fontSize: '2rem' }}>🎨</div>
              <div>Diseñamos</div>
            </div>

            <div ref={partBottomRef} style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '150px', height: '150px', borderRadius: '28px', background: 'linear-gradient(135deg, rgba(0, 87, 184, 0.9) 0%, var(--blue) 100%)', border: '2px solid white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: '1rem', color: 'white', transformStyle: 'preserve-3d', opacity: 0, boxShadow: '0 10px 30px rgba(0, 87, 184, 0.2)', textAlign: 'center', gap: '6px', padding: '12px', transition: 'box-shadow 0.3s ease' }}>
              <div style={{ fontSize: '2rem' }}>🎯</div>
              <div>Lanzamos</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ---------- Narrativa Visual / Marna Inspired ---------- */
const NarrativaVisual = () => {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  const [hoveredPillar, setHoveredPillar] = useState(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      entries => {
        if (entries[0].isIntersecting) {
          setInView(true);
          observer.unobserve(entries[0].target);
        }
      },
      { threshold: 0.2 }
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  const pillarData = [
    { emoji: '👂', title: 'Escuchamos', desc: 'Profundizamos en tu negocio, audiencia y objetivos reales.' },
    { emoji: '🎨', title: 'Diseñamos', desc: 'Creamos una experiencia única y coherente con tu marca.' },
    { emoji: '🚀', title: 'Lanzamos', desc: 'Con soporte continuo para maximizar tu presencia online.' },
  ];

  return (
    <section id="narrativa" ref={ref} style={{
      background: 'linear-gradient(180deg, #ffffff 0%, #f9fafb 100%)',
      padding: '120px 40px',
      position: 'relative',
      overflow: 'clip',
      minHeight: '120vh',
      display: 'flex',
      alignItems: 'center',
      zIndex: 1,
      marginTop: '-1px',
    }}>
      {/* Animated background orbs */}
      <div style={{
        position: 'absolute',
        top: '10%',
        right: '5%',
        width: '300px',
        height: '300px',
        background: 'radial-gradient(circle, rgba(0, 87, 184, 0.08) 0%, transparent 70%)',
        borderRadius: '50%',
        animation: inView ? 'floatSlow 8s ease-in-out infinite' : 'none',
        pointerEvents: 'none'
      }} />
      <div style={{
        position: 'absolute',
        bottom: '10%',
        left: '5%',
        width: '250px',
        height: '250px',
        background: 'radial-gradient(circle, rgba(0, 87, 184, 0.06) 0%, transparent 70%)',
        borderRadius: '50%',
        animation: inView ? 'floatReverse 10s ease-in-out infinite' : 'none',
        pointerEvents: 'none'
      }} />

      <div style={{ maxWidth: '1300px', margin: '0 auto', width: '100%', position: 'relative', zIndex: 2 }}>

        {/* Main Title with better styling */}
        <div style={{ marginBottom: '120px', position: 'relative', zIndex: 3 }}>
          <div style={{ overflow: 'hidden', marginBottom: '16px' }}>
            <h2 style={{
              fontSize: 'clamp(2.8rem, 9vw, 5rem)',
              fontWeight: 900,
              lineHeight: 1.05,
              margin: 0,
              letterSpacing: '-0.03em',
              background: 'linear-gradient(135deg, #0a0e27 0%, #0057B8 100%)',
              backgroundClip: 'text',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent',
              transform: inView ? 'translateY(0)' : 'translateY(100px)',
              opacity: inView ? 1 : 0,
              transition: 'all 1.2s cubic-bezier(0.16, 1, 0.3, 1) 0.15s',
            }}>
              Creamos tu marca.
            </h2>
          </div>
          <div style={{ overflow: 'hidden', maxWidth: '700px' }}>
            <p style={{
              fontSize: 'clamp(1.05rem, 2.8vw, 1.5rem)',
              fontWeight: 400,
              lineHeight: 1.5,
              color: '#6b7280',
              margin: 0,
              transform: inView ? 'translateY(0)' : 'translateY(60px)',
              opacity: inView ? 1 : 0,
              transition: 'all 1.1s cubic-bezier(0.16, 1, 0.3, 1) 0.3s',
            }}>
              Desde la estrategia hasta el lanzamiento. Cada paso cuenta. Cada detalle importa. Guiamos tu presencia digital hacia el éxito.
            </p>
          </div>
        </div>

        {/* Three Pillars with enhanced design */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
          gap: '48px',
          marginBottom: '100px',
          position: 'relative',
          zIndex: 3
        }}>
          {pillarData.map((pillar, i) => (
            <div
              key={i}
              onMouseEnter={() => setHoveredPillar(i)}
              onMouseLeave={() => setHoveredPillar(null)}
              style={{
                padding: '40px 32px',
                borderRadius: '16px',
                background: hoveredPillar === i ? 'rgba(0, 87, 184, 0.08)' : 'white',
                border: hoveredPillar === i ? '1px solid rgba(0, 87, 184, 0.2)' : '1px solid rgba(0, 87, 184, 0.08)',
                transition: 'all 0.6s cubic-bezier(0.16, 1, 0.3, 1)',
                transform: hoveredPillar === i ? 'translateY(-8px)' : 'translateY(0)',
                cursor: 'pointer',
                position: 'relative',
              }}
            >
              {/* Icon with animation */}
              <div style={{
                fontSize: '56px',
                marginBottom: '24px',
                opacity: inView ? 1 : 0,
                transform: inView ? 'scale(1) rotate(0deg)' : 'scale(0.5) rotate(-180deg)',
                transition: `all 0.9s cubic-bezier(0.16, 1, 0.3, 1) ${300 + i * 120}ms`,
                transformOrigin: 'left center',
                filter: hoveredPillar === i ? 'drop-shadow(0 8px 16px rgba(0, 87, 184, 0.15))' : 'drop-shadow(none)',
              }}>
                {pillar.emoji}
              </div>

              {/* Title */}
              <div style={{ overflow: 'hidden', marginBottom: '12px' }}>
                <h3 style={{
                  fontSize: '22px',
                  fontWeight: 700,
                  margin: 0,
                  color: '#0a0e27',
                  transform: inView ? 'translateY(0)' : 'translateY(40px)',
                  opacity: inView ? 1 : 0,
                  transition: `all 0.8s cubic-bezier(0.16, 1, 0.3, 1) ${400 + i * 120}ms`,
                  letterSpacing: '-0.01em'
                }}>
                  {pillar.title}
                </h3>
              </div>

              {/* Description */}
              <div style={{ overflow: 'hidden' }}>
                <p style={{
                  fontSize: '15px',
                  lineHeight: 1.7,
                  color: '#6b7280',
                  margin: 0,
                  transform: inView ? 'translateY(0)' : 'translateY(40px)',
                  opacity: inView ? 1 : 0,
                  transition: `all 0.8s cubic-bezier(0.16, 1, 0.3, 1) ${500 + i * 120}ms`,
                }}>
                  {pillar.desc}
                </p>
              </div>

              {/* Accent line on hover */}
              <div style={{
                position: 'absolute',
                bottom: 0,
                left: 0,
                right: 0,
                height: '3px',
                background: 'linear-gradient(90deg, #0057B8 0%, transparent 100%)',
                borderRadius: '0 0 16px 0',
                transform: hoveredPillar === i ? 'scaleX(1)' : 'scaleX(0)',
                transformOrigin: 'left',
                transition: 'transform 0.6s cubic-bezier(0.16, 1, 0.3, 1)'
              }} />
            </div>
          ))}
        </div>

      </div>

      <style>{`
        @keyframes floatSlow {
          0%, 100% { transform: translateY(0px) translateX(0px); }
          50% { transform: translateY(-40px) translateX(20px); }
        }
        @keyframes floatReverse {
          0%, 100% { transform: translateY(0px) translateX(0px); }
          50% { transform: translateY(40px) translateX(-20px); }
        }
      `}</style>
    </section>
  );
};

/* ---------- Section dots ---------- */
const SectionDots = ({ active }) => {
  const sections = [
    { id: "inicio", label: "Inicio" },
    { id: "servicios", label: "Servicios" },
    { id: "proyectos", label: "Proyectos" },
    { id: "proceso", label: "Proceso" },
    { id: "contacto", label: "Contacto" },
  ];
  return (
    <nav className="section-dots" aria-label="Secciones">
      {sections.map(s => (
        <a key={s.id} href={`#${s.id}`} className={`sdot ${active === s.id ? "active" : ""}`} title={s.label}></a>
      ))}
    </nav>
  );
};

/* ---------- App ---------- */
const App = () => {
  useReveal();
  useParallax();
  const active = useActiveSection();
  return (
    <div id="top">
      <SectionDots active={active} />
      <Header active={active} />
      <Hero />
      <NarrativaVisual />
      <TechStrip />
      <Services />
      <Value />
      <Projects />
      <Process />
      <CtaBand />
      <Contact />
      <Footer />
    </div>
  );
};

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