// ── SERVICIOS — Orbital + Exit Burst ──────────────────────
function Servicios() {
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && window.innerWidth <= 768
  );

  const sectionRef = useRef(null);
  const orbitRef = useRef(null);
  const coreRef = useRef(null);
  const nodeRefs = useRef([]);
  const cardRefs = useRef([]);
  const stateRef = useRef({ angle: 0, autoRotate: true, activeId: null, raf: null });

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  const svcs = [
    { id: 0, Icon: IconDiagnostico, t: 'Auditoría de operación', d: 'Leemos el negocio antes de diseñar. Mapeamos procesos, datos, herramientas, dependencias y fricciones para definir con precisión qué construir y en qué secuencia.', tags: ['Auditoría', 'Mapeo', 'Roadmap'], energy: 88, relatedIds: [1, 3] },
    { id: 1, Icon: IconSistemas, t: 'Arquitectura de sistemas', d: 'Definimos la estructura completa del ecosistema digital: plataformas, integraciones, APIs y flujos de datos. Todo conectado desde el diseño, no parcheado después.', tags: ['Arquitectura', 'Sistemas', 'APIs'], energy: 95, relatedIds: [0, 2, 5] },
    { id: 2, Icon: IconAutomatizacion, t: 'Automatización operacional', d: 'Convertimos los procesos que hoy viven en WhatsApp, Excel o personas específicas en flujos automáticos, precisos y monitoreables.', tags: ['Flujos', 'Integraciones', 'Bots'], energy: 92, relatedIds: [1, 5] },
    { id: 3, Icon: IconEstrategia, t: 'Estrategia y posicionamiento', d: 'Definimos el mapa de crecimiento digital: qué construir, cuándo y por qué. Estrategia ejecutable con una hoja de ruta que conecta decisión con acción.', tags: ['Roadmap', 'Posicionamiento', 'GTM'], energy: 85, relatedIds: [0, 4] },
    { id: 4, Icon: IconDatos, t: 'Inteligencia operacional', d: 'Centralizamos y estructuramos los datos de la operación para convertirlos en visibilidad real. Cada decisión de negocio respaldada por información, no intuición.', tags: ['BI', 'Dashboards', 'Analytics'], energy: 90, relatedIds: [3, 1] },
    { id: 5, Icon: IconIntegracion, t: 'Construcción e integración', d: 'Construimos lo que diseñamos. Integramos las herramientas existentes. Operamos el sistema hasta que funciona exactamente como fue concebido.', tags: ['Desarrollo', 'Integración', 'Operación'], energy: 97, relatedIds: [2, 1] },
  ];


  // ── Orbital RAF + node interactions ──────────────────────────────────────
  useEffect(() => {
    const st = stateRef.current;
    const orbit = orbitRef.current;
    const core = coreRef.current;
    const nodes = nodeRefs.current;
    const cards = cardRefs.current;
    if (!orbit || !core) return;

    const TOTAL = svcs.length, RADIUS = isMobile ? 128 : 220;

    gsap.to(core, { scale: 1.12, duration: 1.8, ease: 'sine.inOut', yoyo: true, repeat: -1 });

    function positionNode(index, angle) {
      const rad = ((angle + (index / TOTAL) * 360) * Math.PI) / 180;
      const depth = (1 + Math.sin(rad)) / 2;
      return {
        x: RADIUS * Math.cos(rad),
        y: RADIUS * Math.sin(rad),
        op: Math.max(0.35, 0.35 + 0.65 * depth),
        sc: Math.max(0.75, 0.75 + 0.25 * depth),
        zi: Math.round(50 + 50 * depth),
      };
    }

    function tick() {
      if (st.autoRotate) st.angle = (st.angle + 0.18) % 360;
      nodes.forEach((node, i) => {
        if (!node) return;
        const { x, y, op, sc, zi } = positionNode(i, st.angle);
        node.style.transform = `translate(${x}px, ${y}px) scale(${sc})`;
        node.style.opacity = st.activeId === i ? '1' : op;
        node.style.zIndex = st.activeId === i ? '200' : zi;
      });
      st.raf = requestAnimationFrame(tick);
    }
    st.raf = requestAnimationFrame(tick);

    nodes.forEach((node, i) => {
      if (!node) return;
      node.addEventListener('click', (e) => {
        e.stopPropagation();
        const isOpen = st.activeId === i;

        // Close all other cards
        cards.forEach((c, j) => {
          if (c && j !== i) {
            gsap.to(c, {
              opacity: 0, scale: 0.88, duration: 0.22, ease: 'power2.in',
              onComplete: () => { c.style.display = 'none'; }
            });
          }
          if (nodes[j] && j !== i) nodes[j].querySelector('.svc-dot').classList.remove('active');
        });

        if (isOpen) {
          const card = cards[i];
          if (card) gsap.to(card, {
            opacity: 0, scale: 0.88, duration: 0.22, ease: 'power2.in',
            onComplete: () => { card.style.display = 'none'; }
          });
          node.querySelector('.svc-dot').classList.remove('active');
          st.activeId = null;
          st.autoRotate = true;
        } else {
          st.activeId = i;
          st.autoRotate = false;
          gsap.to(st, { angle: 270 - (i / TOTAL) * 360, duration: 0.9, ease: 'power3.out' });
          const card = cards[i];
          if (card) {
            card.style.display = 'block';
            gsap.fromTo(card,
              { opacity: 0, scale: 0.88, y: 8 },
              { opacity: 1, scale: 1, y: 0, duration: 0.32, ease: 'back.out(1.6)' }
            );
          }
          node.querySelector('.svc-dot').classList.add('active');
          svcs[i].relatedIds.forEach(rid => {
            const rn = nodes[rid];
            if (rn) gsap.fromTo(rn, { scale: 1 }, { scale: 1.3, duration: 0.4, ease: 'elastic.out(1,0.4)', yoyo: true, repeat: 1 });
          });
        }
      });
    });

    function closeAll() {
      cards.forEach((c, j) => {
        if (c) gsap.to(c, { opacity: 0, scale: 0.88, duration: 0.2, onComplete: () => { c.style.display = 'none'; } });
        if (nodes[j]) nodes[j].querySelector('.svc-dot').classList.remove('active');
      });
      st.activeId = null;
      st.autoRotate = true;
    }

    orbit.addEventListener('click', closeAll);

    // On mobile the cards live outside the orbit div, so also listen on the
    // full section so any tap outside the card (which stopPropagation) closes it.
    const section = sectionRef.current;
    if (section) section.addEventListener('click', closeAll);

    return () => {
      cancelAnimationFrame(st.raf);
      if (section) section.removeEventListener('click', closeAll);
    };
  }, [isMobile]);

  return (
    <section
      id="servicios"
      ref={sectionRef}
      style={{ height: '100vh', overflow: 'hidden', position: 'relative' }}
    >
        {/* ── Orbital UI ──────────────────────────────────────────────────── */}
        <div style={{ position: 'relative', zIndex: 2, display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'flex-start' }}>

          <div style={{ textAlign: 'center', paddingTop: isMobile ? '20px' : '48px', paddingBottom: isMobile ? '32px' : 'clamp(200px, 30vh, 300px)' }}>
            <h2 className="servicios-headline" style={{ textAlign: 'center', margin: '0 auto', fontSize: isMobile ? 'clamp(18px, 5vw, 26px)' : 'clamp(22px, 2.4vw, 36px)' }}>Seis disciplinas. Una sola arquitectura.</h2>
          </div>

          <div
            ref={orbitRef}
            style={{ position: 'relative', width: '100%', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
          >
            {/* Orbit rings */}
            <div style={{ position: 'absolute', width: isMobile ? '276px' : '460px', height: isMobile ? '276px' : '460px', borderRadius: '50%', border: '1px solid rgba(200,184,149,0.12)', pointerEvents: 'none' }} />
            <div style={{ position: 'absolute', width: isMobile ? '296px' : '490px', height: isMobile ? '296px' : '490px', borderRadius: '50%', border: '1px dashed rgba(200,184,149,0.06)', pointerEvents: 'none' }} />

            {/* Core orb */}
            <div
              ref={coreRef}
              style={{ position: 'absolute', width: '56px', height: '56px', borderRadius: '50%', background: 'radial-gradient(circle, #fff9ec 0%, #C8B895 40%, #8B744A 70%, transparent 100%)', boxShadow: '0 0 40px 12px rgba(200,184,149,0.3), 0 0 80px 30px rgba(200,184,149,0.1)', zIndex: 10, pointerEvents: 'none' }}
            />
            <div style={{ position: 'absolute', width: '80px', height: '80px', borderRadius: '50%', border: '1px solid rgba(200,184,149,0.2)', animation: 'orbitPing 2s ease-out infinite', pointerEvents: 'none', zIndex: 9 }} />

            {/* Nodes */}
            {svcs.map((svc, i) => (
              <div
                key={svc.id}
                ref={el => nodeRefs.current[i] = el}
                style={{ position: 'absolute', cursor: 'pointer', willChange: 'transform, opacity', display: 'flex', flexDirection: 'column', alignItems: 'center' }}
              >
                <div className="svc-dot" style={{ width: isMobile ? '40px' : '52px', height: isMobile ? '40px' : '52px', borderRadius: '50%', border: '1.5px solid rgba(200,184,149,0.45)', background: 'rgba(11,13,15,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'border-color 0.3s, background 0.3s, box-shadow 0.3s', backdropFilter: 'blur(6px)' }}>
                  <svc.Icon />
                </div>
                <div style={{ marginTop: '7px', fontFamily: 'Sora, sans-serif', fontSize: isMobile ? '8px' : '10px', fontWeight: 400, letterSpacing: '0.07em', textTransform: 'uppercase', color: 'var(--sand)', whiteSpace: 'normal', textAlign: 'center', width: isMobile ? '70px' : '110px', lineHeight: 1.35, pointerEvents: 'none' }}>
                  {svc.t}
                </div>

                {/* Desktop info card — must stay inside node so position:absolute is node-relative */}
                {!isMobile && (
                  <div
                    ref={el => cardRefs.current[i] = el}
                    style={{ display: 'none', position: 'absolute', top: '66px', left: '50%', transform: 'translateX(-50%)', width: '320px', background: 'rgba(11,13,15,0.92)', border: '1px solid rgba(200,184,149,0.22)', backdropFilter: 'blur(16px)', padding: '28px', zIndex: 300 }}
                    onClick={e => e.stopPropagation()}
                  >
                    <div style={{ position: 'absolute', top: '-12px', left: '50%', transform: 'translateX(-50%)', width: '1px', height: '12px', background: 'rgba(200,184,149,0.4)' }} />
                    <div style={{ fontSize: '11px', fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--sand)', marginBottom: '10px' }}>{String(i + 1).padStart(2, '0')}</div>
                    <div style={{ fontFamily: 'Sora, sans-serif', fontSize: '17px', fontWeight: 400, color: '#F2EFE8', marginBottom: '12px', letterSpacing: '-0.01em', lineHeight: 1.25 }}>{svc.t}</div>
                    <p style={{ fontSize: '13px', color: 'var(--stone)', lineHeight: 1.75, marginBottom: '18px' }}>{svc.d}</p>
                    <div style={{ marginBottom: '18px' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--stone)', marginBottom: '6px' }}>
                        <span style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Impacto operacional</span>
                        <span style={{ color: 'var(--sand)', fontWeight: 600 }}>{svc.energy}%</span>
                      </div>
                      <div style={{ height: '2px', background: 'rgba(200,184,149,0.12)' }}>
                        <div style={{ height: '100%', width: `${svc.energy}%`, background: 'linear-gradient(90deg, #8B744A, #C8B895)' }} />
                      </div>
                    </div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '7px' }}>
                      {svc.tags.map(tag => (
                        <span key={tag} style={{ fontSize: '10px', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--stone)', border: '1px solid rgba(110,110,110,0.3)', padding: '4px 10px' }}>{tag}</span>
                      ))}
                    </div>
                    {svc.relatedIds.length > 0 && (
                      <div style={{ marginTop: '18px', paddingTop: '14px', borderTop: '1px solid rgba(200,184,149,0.1)' }}>
                        <div style={{ fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--stone)', marginBottom: '10px' }}>Relacionado con</div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '7px' }}>
                          {svc.relatedIds.map(rid => (
                            <button key={rid}
                              style={{ fontSize: '11px', color: 'var(--sand)', background: 'rgba(200,184,149,0.08)', border: '1px solid rgba(200,184,149,0.2)', padding: '6px 12px', cursor: 'pointer', letterSpacing: '0.05em', fontFamily: 'Sora, sans-serif' }}
                              onClick={(e) => { e.stopPropagation(); nodeRefs.current[rid] && nodeRefs.current[rid].click(); }}
                            >
                              {svcs[rid].t.split(' ').slice(0, 2).join(' ')} →
                            </button>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>

          <div style={{ textAlign: 'center', paddingTop: isMobile ? '40px' : 'clamp(80px, 12vh, 130px)', paddingBottom: isMobile ? '24px' : '36px' }}>
            <p style={{ fontSize: '10px', color: 'var(--stone)', letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.5, margin: 0 }}>Selecciona una disciplina para explorar</p>
          </div>
        </div>

        {/* Mobile cards — outside node transform context, anchored to section bottom */}
        {isMobile && svcs.map((svc, i) => (
          <div
            key={`mcard-${i}`}
            ref={el => cardRefs.current[i] = el}
            style={{ display: 'none', position: 'absolute', bottom: '72px', left: '16px', right: '16px', maxHeight: '55vh', overflowY: 'auto', background: 'rgba(11,13,15,0.96)', border: '1px solid rgba(200,184,149,0.22)', backdropFilter: 'blur(16px)', padding: '20px', zIndex: 300 }}
            onClick={e => e.stopPropagation()}
          >
            <div style={{ fontSize: '10px', fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--sand)', marginBottom: '8px' }}>{String(i + 1).padStart(2, '0')}</div>
            <div style={{ fontFamily: 'Sora, sans-serif', fontSize: '15px', fontWeight: 700, color: '#F2EFE8', marginBottom: '10px', letterSpacing: '-0.01em', lineHeight: 1.25 }}>{svc.t}</div>
            <p style={{ fontSize: '13px', color: 'var(--stone)', lineHeight: 1.7, marginBottom: '14px' }}>{svc.d}</p>
            <div style={{ marginBottom: '14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: 'var(--stone)', marginBottom: '5px' }}>
                <span style={{ letterSpacing: '0.1em', textTransform: 'uppercase' }}>Impacto operacional</span>
                <span style={{ color: 'var(--sand)', fontWeight: 600 }}>{svc.energy}%</span>
              </div>
              <div style={{ height: '2px', background: 'rgba(200,184,149,0.12)' }}>
                <div style={{ height: '100%', width: `${svc.energy}%`, background: 'linear-gradient(90deg, #8B744A, #C8B895)' }} />
              </div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
              {svc.tags.map(tag => (
                <span key={tag} style={{ fontSize: '9px', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--stone)', border: '1px solid rgba(110,110,110,0.3)', padding: '3px 8px' }}>{tag}</span>
              ))}
            </div>
            {svc.relatedIds.length > 0 && (
              <div style={{ marginTop: '14px', paddingTop: '12px', borderTop: '1px solid rgba(200,184,149,0.1)' }}>
                <div style={{ fontSize: '9px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--stone)', marginBottom: '8px' }}>Relacionado con</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                  {svc.relatedIds.map(rid => (
                    <button key={rid}
                      style={{ fontSize: '10px', color: 'var(--sand)', background: 'rgba(200,184,149,0.08)', border: '1px solid rgba(200,184,149,0.2)', padding: '4px 10px', cursor: 'pointer', letterSpacing: '0.05em', fontFamily: 'Sora, sans-serif' }}
                      onClick={(e) => { e.stopPropagation(); nodeRefs.current[rid] && nodeRefs.current[rid].click(); }}
                    >
                      {svcs[rid].t.split(' ').slice(0, 2).join(' ')} →
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>
        ))}

    </section>
  );
}
