/* Radial orbital integration map — animated nodes orbiting Dominus core */
const { useState: useStateO, useEffect: useEffectO, useRef: useRefO } = React;

const INTEGRATIONS = [
  { id: 1,  key: 'wa',   label: 'WhatsApp',      glyph: 'WA',  color: '#22c55e',
    desc: 'Atendimento e vendas conversacionais. Mensagens entram, viram leads e ações no CRM.',
    status: 'completed', energy: 100, relatedIds: [6, 5, 4, 10] },
  { id: 2,  key: 'ig',   label: 'Instagram',     glyph: 'IG',  color: '#E1306C',
    desc: 'DMs e comentários capturados como leads, integrados ao funil de vendas.',
    status: 'completed', energy: 92,  relatedIds: [6, 5] },
  { id: 3,  key: 'gs',   label: 'Google Sheets', glyph: 'GS',  color: '#0F9D58',
    desc: 'Leitura e escrita em planilhas para alimentar relatórios e operações simples.',
    status: 'completed', energy: 86,  relatedIds: [5, 4] },
  { id: 4,  key: 'sb',   label: 'Supabase',      glyph: 'SB',  color: '#3ECF8E',
    desc: 'Banco de dados e auth em tempo real para sistemas sob medida.',
    status: 'completed', energy: 98,  relatedIds: [5, 6, 1, 12] },
  { id: 5,  key: 'n8',   label: 'n8n',           glyph: 'n8', color: '#EA4B71',
    desc: 'Orquestrador central das automações. Conecta todos os outros nós.',
    status: 'completed', energy: 100, relatedIds: [1, 2, 3, 4, 6, 11, 12] },
  { id: 6,  key: 'crm',  label: 'CRM',           glyph: 'CR',  color: '#2563EB',
    desc: 'Pipeline, contatos, oportunidades e cadência de follow-up unificados.',
    status: 'completed', energy: 96,  relatedIds: [1, 2, 4, 11, 7] },
  { id: 7,  key: 'site', label: 'Site',          glyph: '</>',color: '#0B0F19',
    desc: 'Landing pages rápidas e otimizadas, conectadas ao CRM e ao tracking.',
    status: 'completed', energy: 90,  relatedIds: [8, 9, 6] },
  { id: 8,  key: 'meta', label: 'Meta Ads',      glyph: 'MA',  color: '#1877F2',
    desc: 'Webhook de leads e conversões offline sincronizados em tempo real.',
    status: 'in-progress', energy: 78, relatedIds: [7, 6] },
  { id: 9,  key: 'ga',   label: 'Google Ads',    glyph: 'GA',  color: '#EA4335',
    desc: 'Conversões offline enviadas via API para otimizar campanhas reais.',
    status: 'in-progress', energy: 74, relatedIds: [7, 6] },
  { id: 10, key: 'pr',   label: 'Impressora',    glyph: 'PR',  color: '#6B7280',
    desc: 'Pedido cai no WhatsApp e imprime direto na cozinha. Zero digitação.',
    status: 'completed', energy: 88,  relatedIds: [1, 5] },
  { id: 11, key: 'em',   label: 'E-mail',        glyph: '@',   color: '#C6A15B',
    desc: 'Disparos transacionais, cadência de follow-up e notificações internas.',
    status: 'completed', energy: 84,  relatedIds: [5, 6] },
  { id: 12, key: 'wh',   label: 'Webhooks',      glyph: 'WH',  color: '#5CE1E6',
    desc: 'Eventos customizados para qualquer sistema externo. Saída e entrada.',
    status: 'completed', energy: 100, relatedIds: [5, 4] }
];

function RadialOrbital({ data = INTEGRATIONS }) {
  const [expanded, setExpanded] = useStateO({});
  const [rotation, setRotation] = useStateO(0);
  const [autoRotate, setAutoRotate] = useStateO(true);
  const [pulse, setPulse] = useStateO({});
  const [active, setActive] = useStateO(null);
  const containerRef = useRefO(null);
  const orbitRef = useRefO(null);

  // auto-rotate
  useEffectO(() => {
    if (!autoRotate) return;
    const id = setInterval(() => {
      setRotation(prev => +((prev + 0.25) % 360).toFixed(3));
    }, 50);
    return () => clearInterval(id);
  }, [autoRotate]);

  const handleBg = (e) => {
    if (e.target === containerRef.current || e.target === orbitRef.current) {
      setExpanded({});
      setActive(null);
      setPulse({});
      setAutoRotate(true);
    }
  };

  const getRelated = (id) => {
    const item = data.find(d => d.id === id);
    return item ? item.relatedIds : [];
  };

  const toggle = (id) => {
    setExpanded(prev => {
      const next = {};
      // close all others, toggle target
      const isOpening = !prev[id];
      if (isOpening) next[id] = true;
      return next;
    });
    const isOpening = !expanded[id];
    if (isOpening) {
      setActive(id);
      setAutoRotate(false);
      const rel = {};
      getRelated(id).forEach(r => rel[r] = true);
      setPulse(rel);
      // center node: rotate so this node is at top
      const idx = data.findIndex(d => d.id === id);
      const targetAngle = (idx / data.length) * 360;
      setRotation(270 - targetAngle);
    } else {
      setActive(null);
      setAutoRotate(true);
      setPulse({});
    }
  };

  const isRelated = (id) => {
    if (!active) return false;
    return getRelated(active).includes(id);
  };

  const statusBadge = (status) => {
    if (status === 'completed') return { text: 'ATIVO', bg: '#fff', color: '#0B0F19', border: '#fff' };
    if (status === 'in-progress') return { text: 'SINCRONIZANDO', bg: 'transparent', color: '#5CE1E6', border: '#5CE1E6' };
    return { text: 'PENDENTE', bg: 'rgba(255,255,255,0.06)', color: 'rgba(255,255,255,0.7)', border: 'rgba(255,255,255,0.3)' };
  };

  return (
    <div
      ref={containerRef}
      onClick={handleBg}
      className="orbital-stage"
      style={{
        position: 'relative',
        width: '100%',
        height: 'min(92vh, 900px)',
        minHeight: 720,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
        userSelect: 'none'
      }}
    >
      {/* Soft radial backdrop */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(closest-side, rgba(37,99,235,0.18), rgba(92,225,230,0.06) 35%, transparent 70%)'
      }} />

      <div
        ref={orbitRef}
        onClick={handleBg}
        style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          perspective: '1000px'
        }}
      >
        {/* Center hub */}
        <div style={{
          position: 'absolute',
          width: 140, height: 140,
          borderRadius: 32,
          background: 'linear-gradient(180deg, #0B0F19, #050816)',
          border: '1px solid rgba(255,255,255,0.08)',
          boxShadow: '0 30px 80px -20px rgba(37,99,235,0.55), 0 0 0 6px rgba(37,99,235,0.06)',
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          color: '#fff', zIndex: 10, pointerEvents: 'none'
        }}>
          {/* ping rings */}
          <span className="orb-ping" style={{ width: 170, height: 170 }} />
          <span className="orb-ping" style={{ width: 210, height: 210, animationDelay: '0.6s' }} />
          <div style={{
            width: 56, height: 56,
            backgroundImage: 'url(assets/dominus-logo.png)',
            backgroundSize: 'contain', backgroundRepeat: 'no-repeat', backgroundPosition: 'center',
            filter: 'drop-shadow(0 6px 16px rgba(92,225,230,0.45))',
            marginBottom: 6
          }} />
          <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.01em' }}>Dominus</div>
          <div className="mono" style={{ fontSize: 9.5, color: 'rgba(255,255,255,0.55)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>core</div>
        </div>

        {/* Orbital rings */}
        <div className="orb-ring" style={{ width: 640, height: 640 }} />
        <div className="orb-ring" style={{ width: 480, height: 480, opacity: 0.4 }} />

        {/* Connection lines SVG */}
        <svg style={{ position: 'absolute', width: 640, height: 640, pointerEvents: 'none' }}>
          <defs>
            <linearGradient id="orb-line" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#5CE1E6" stopOpacity="0.05" />
              <stop offset="50%" stopColor="#5CE1E6" stopOpacity="0.35" />
              <stop offset="100%" stopColor="#5CE1E6" stopOpacity="0.55" />
            </linearGradient>
          </defs>
          {data.map((it, i) => {
            const a = ((i / data.length) * 360 + rotation) % 360;
            const rad = (a * Math.PI) / 180;
            const radius = 280;
            const x = 320 + Math.cos(rad) * radius;
            const y = 320 + Math.sin(rad) * radius;
            const isAct = active === it.id;
            const isRel = isRelated(it.id);
            const strong = isAct || isRel;
            return (
              <g key={it.id}>
                <line x1="320" y1="320" x2={x} y2={y}
                  stroke={strong ? '#5CE1E6' : 'url(#orb-line)'}
                  strokeWidth={strong ? 1.2 : 0.6}
                  strokeOpacity={strong ? 0.9 : 0.5} />
                <line x1="320" y1="320" x2={x} y2={y}
                  stroke="#5CE1E6" strokeWidth="0.8"
                  strokeDasharray="2 6" strokeOpacity={strong ? 0.7 : 0.35}
                  style={{ animation: `dashFlow 2.${i % 5}s linear infinite` }} />
              </g>
            );
          })}
        </svg>

        {/* Nodes */}
        {data.map((it, i) => {
          const a = ((i / data.length) * 360 + rotation) % 360;
          const rad = (a * Math.PI) / 180;
          const radius = 280;
          const x = Math.cos(rad) * radius;
          const y = Math.sin(rad) * radius;
          const zIndex = Math.round(100 + 50 * Math.cos(rad));
          const opacity = Math.max(0.55, 0.55 + 0.45 * ((1 + Math.sin(rad)) / 2));
          const isExp = !!expanded[it.id];
          const isRel = isRelated(it.id);
          const isPulse = !!pulse[it.id];
          const sb = statusBadge(it.status);

          return (
            <div key={it.id}
              onClick={(e) => { e.stopPropagation(); toggle(it.id); }}
              style={{
                position: 'absolute',
                transform: `translate(${x}px, ${y}px)`,
                zIndex: isExp ? 300 : zIndex,
                opacity: isExp ? 1 : opacity,
                transition: 'transform 0.5s cubic-bezier(.2,.7,.2,1), opacity 0.5s ease',
                cursor: 'pointer'
              }}
            >
              {/* Glow halo */}
              <div style={{
                position: 'absolute',
                left: '50%', top: '50%',
                transform: 'translate(-50%, -50%)',
                width: it.energy * 0.5 + 50,
                height: it.energy * 0.5 + 50,
                borderRadius: 999,
                background: 'radial-gradient(circle, rgba(255,255,255,0.18) 0%, rgba(255,255,255,0) 70%)',
                animation: isPulse ? 'pulseSoft 1.6s ease-in-out infinite' : 'none',
                pointerEvents: 'none'
              }} />

              {/* Node chip */}
              <div className="orb-chip"
                style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  padding: '7px 11px 7px 7px',
                  background: isExp ? '#fff' : '#0B0F19',
                  border: '1px solid ' + (isExp ? '#fff' : isRel ? 'rgba(92,225,230,0.7)' : 'rgba(255,255,255,0.15)'),
                  borderRadius: 999,
                  boxShadow: isExp
                    ? '0 0 0 4px rgba(255,255,255,0.18), 0 14px 40px -8px rgba(92,225,230,0.45)'
                    : isRel
                      ? '0 0 0 3px rgba(92,225,230,0.18), 0 8px 22px -10px rgba(92,225,230,0.5)'
                      : '0 8px 18px -8px rgba(0,0,0,0.45)',
                  transition: 'all .35s ease',
                  transform: isExp ? 'scale(1.08)' : 'scale(1)',
                  whiteSpace: 'nowrap'
                }}
              >
                <div style={{
                  width: 22, height: 22, borderRadius: 6,
                  background: it.color,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#fff', fontSize: 9.5, fontWeight: 700,
                  fontFamily: 'Geist Mono, monospace',
                  flexShrink: 0
                }}>{it.glyph}</div>
                <span style={{
                  fontSize: 11.5, fontWeight: 500,
                  color: isExp ? '#0B0F19' : '#fff'
                }}>{it.label}</span>
              </div>

              {/* Expanded card */}
              {isExp && (
                <div className="orb-card" onClick={(e) => e.stopPropagation()}>
                  <div style={{
                    position: 'absolute', top: -10, left: '50%',
                    transform: 'translateX(-50%)',
                    width: 1, height: 10, background: 'rgba(92,225,230,0.6)'
                  }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                    <span className="mono" style={{
                      padding: '3px 8px', borderRadius: 999, fontSize: 9.5, fontWeight: 600,
                      letterSpacing: '0.08em',
                      background: sb.bg, color: sb.color, border: `1px solid ${sb.border}`
                    }}>{sb.text}</span>
                    <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)' }}>
                      {it.key.toUpperCase()}_{String(it.id).padStart(2, '0')}
                    </span>
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: '#fff', marginBottom: 8 }}>{it.label}</div>
                  <p style={{ fontSize: 12, lineHeight: 1.5, color: 'rgba(255,255,255,0.75)', margin: 0 }}>{it.desc}</p>

                  <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, marginBottom: 6 }}>
                      <span className="mono" style={{ color: 'rgba(255,255,255,0.55)', display: 'flex', alignItems: 'center', gap: 4, letterSpacing: '0.06em' }}>
                        <ZapIcon /> SINCRONIA
                      </span>
                      <span className="mono" style={{ color: '#5CE1E6' }}>{it.energy}%</span>
                    </div>
                    <div style={{ height: 3, background: 'rgba(255,255,255,0.08)', borderRadius: 99, overflow: 'hidden' }}>
                      <div style={{
                        height: '100%', width: `${it.energy}%`,
                        background: 'linear-gradient(90deg, #2563EB, #5CE1E6)'
                      }} />
                    </div>
                  </div>

                  {it.relatedIds.length > 0 && (
                    <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
                      <div className="mono" style={{
                        fontSize: 10, color: 'rgba(255,255,255,0.55)',
                        letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8,
                        display: 'flex', alignItems: 'center', gap: 4
                      }}>
                        <LinkIcon /> Nós conectados
                      </div>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {it.relatedIds.slice(0, 6).map(rid => {
                          const r = data.find(d => d.id === rid);
                          if (!r) return null;
                          return (
                            <button key={rid}
                              onClick={(e) => { e.stopPropagation(); toggle(rid); }}
                              style={{
                                display: 'inline-flex', alignItems: 'center', gap: 4,
                                fontSize: 10.5,
                                padding: '3px 8px',
                                background: 'transparent',
                                color: 'rgba(255,255,255,0.85)',
                                border: '1px solid rgba(255,255,255,0.15)',
                                borderRadius: 4, cursor: 'pointer',
                                fontFamily: 'Geist, sans-serif'
                              }}>
                              {r.label}
                              <ArrowRightTiny />
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <style>{`
        @keyframes dashFlow { to { stroke-dashoffset: -40; } }
        @keyframes pulseSoft {
          0%, 100% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
          50% { opacity: 0.55; transform: translate(-50%, -50%) scale(1.18); }
        }
        @keyframes orbPing {
          0% { transform: scale(0.9); opacity: 0.7; }
          80%, 100% { transform: scale(1.6); opacity: 0; }
        }
        .orb-ping {
          position: absolute; border-radius: 999px;
          border: 1px solid rgba(255,255,255,0.18);
          animation: orbPing 2.4s cubic-bezier(0,0,.2,1) infinite;
          pointer-events: none;
        }
        .orb-ring {
          position: absolute; border-radius: 999px;
          border: 1px dashed rgba(255,255,255,0.10);
          pointer-events: none;
        }
        .orb-card {
          position: absolute;
          top: 46px; left: 50%;
          transform: translateX(-50%);
          width: 280px;
          padding: 16px;
          background: rgba(11,15,25,0.92);
          backdrop-filter: blur(14px);
          -webkit-backdrop-filter: blur(14px);
          border: 1px solid rgba(255,255,255,0.12);
          border-radius: 14px;
          box-shadow: 0 30px 80px -20px rgba(0,0,0,0.7), 0 0 0 6px rgba(92,225,230,0.06);
          z-index: 400;
        }
      `}</style>
    </div>
  );
}

function ZapIcon() {
  return (<svg width="10" height="10" viewBox="0 0 24 24" fill="none" style={{ marginRight: 2 }}>
    <path d="M13 2 L4 14 H11 L10 22 L20 9 H13 Z" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinejoin="round" />
  </svg>);
}
function LinkIcon() {
  return (<svg width="10" height="10" viewBox="0 0 24 24" fill="none">
    <path d="M10 14 a4 4 0 0 0 0 -5 l-1 -1 a4 4 0 0 0 -6 6 l4 4 a4 4 0 0 0 6 0 M14 10 a4 4 0 0 0 0 5 l1 1 a4 4 0 0 0 6 -6 l-4 -4 a4 4 0 0 0 -6 0" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
  </svg>);
}
function ArrowRightTiny() {
  return (<svg width="8" height="8" viewBox="0 0 10 10" fill="none">
    <path d="M2 5 H8 M5 2 L8 5 L5 8" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
  </svg>);
}

// Keep window.IntegrationMap as the new orbital
function IntegrationMap() {
  return <RadialOrbital />;
}

window.IntegrationMap = IntegrationMap;
window.RadialOrbital = RadialOrbital;
