/* ============================================================
   HeroEcosystem.jsx — núcleo "Agente de IA AR" orquestrando a
   operação. Topologia radial refinada com conexões curvas tipo
   data-flow / circuito, pulsos de dados e glow sutil.
   Desktop: rede radial · Mobile: empilhado.
   ============================================================ */

const HE_W = 760, HE_H = 600;
const RING = { cx: 380, cy: 300, rx: 258, ry: 214 };

const HE_LABELS = [
  { icon: 'message-circle', label: 'WhatsApp' },
  { icon: 'camera',         label: 'Instagram' },
  { icon: 'globe',          label: 'Site' },
  { icon: 'calendar-check', label: 'Agenda' },
  { icon: 'trending-up',    label: 'Vendas' },
  { icon: 'wallet',         label: 'Financeiro' },
  { icon: 'file-text',      label: 'Documentos' },
  { icon: 'contact',        label: 'CRM' },
  { icon: 'mail',           label: 'E-mail' },
];

const HE_NODES = HE_LABELS.map((n, i) => {
  const a = (-90 + i * 40) * Math.PI / 180;
  return { ...n, x: RING.cx + RING.rx * Math.cos(a), y: RING.cy + RING.ry * Math.sin(a) };
});

/* curva Bézier suave do núcleo até o nó (arco perpendicular alternado) */
const hePath = (n, i) => {
  const { cx, cy } = RING;
  const mx = (cx + n.x) / 2, my = (cy + n.y) / 2;
  const dx = n.x - cx, dy = n.y - cy, L = Math.hypot(dx, dy) || 1;
  const px = -dy / L, py = dx / L;
  const k = (i % 2 ? -1 : 1) * 30;
  return `M${cx},${cy} Q${(mx + px * k).toFixed(1)},${(my + py * k).toFixed(1)} ${n.x.toFixed(1)},${n.y.toFixed(1)}`;
};

const HE_RESULTS = [
  { icon: 'user-check',     label: 'Lead qualificado', x: 58,  y: 92,  anchor: 'l' },
  { icon: 'refresh-cw',     label: 'CRM sincronizado', x: 58,  y: 508, anchor: 'l' },
  { icon: 'calendar-check', label: 'Agenda atualizada',x: 702, y: 92,  anchor: 'r' },
  { icon: 'zap',            label: 'Resposta em segundos', x: 702, y: 508, anchor: 'r' },
];

const HeroEcosystem = ({ tilt = { x: 0, y: 0 } }) => {
  const [narrow, setNarrow] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 760px)');
    const on = () => setNarrow(mq.matches);
    on(); mq.addEventListener('change', on);
    return () => mq.removeEventListener('change', on);
  }, []);
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const tx = (tilt.x || 0) * 6, ty = (tilt.y || 0) * 6;
  const pct = (v, total) => (v / total) * 100 + '%';

  /* ---------------- mobile: stacked ---------------- */
  if (narrow) {
    return (
      <div style={{ width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 22 }}><HeroCore mobile /></div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 9 }}>
          {HE_LABELS.map(n => (
            <div key={n.label} style={heChipStyle}>
              <span style={heNodeIcon}><i data-lucide={n.icon} style={{ width: 15, height: 15 }}></i></span>
              <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 11.5, fontWeight: 500, color: 'var(--ar-text-main)' }}>{n.label}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginTop: 13, justifyContent: 'center' }}>
          {HE_RESULTS.map(r => <HeroResult key={r.label} {...r} mobile />)}
        </div>
      </div>
    );
  }

  /* ---------------- desktop: radial network ---------------- */
  return (
    <div className="he-stage" style={{
      position: 'relative', width: '100%', maxWidth: 580, margin: '0 auto',
      aspectRatio: `${HE_W} / ${HE_H}`,
      transform: `translate(${tx * 0.2}px, ${ty * 0.2}px)`, transition: 'transform 260ms var(--ar-ease)',
    }}>
      {/* ambient depth */}
      <div style={{ position: 'absolute', inset: '16% 20%', borderRadius: '50%', background: 'radial-gradient(circle, rgba(0,94,255,0.20), transparent 66%)', filter: 'blur(12px)', pointerEvents: 'none' }} />

      <svg viewBox={`0 0 ${HE_W} ${HE_H}`} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible', pointerEvents: 'none' }}>
        <defs>
          <linearGradient id="heGrad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#005EFF" /><stop offset="100%" stopColor="#00D4FF" />
          </linearGradient>
          <filter id="heGlow" x="-60%" y="-60%" width="220%" height="220%">
            <feGaussianBlur stdDeviation="2.4" result="b" />
            <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
        </defs>

        {/* faint topology guide ring */}
        <ellipse cx={RING.cx} cy={RING.cy} rx={RING.rx} ry={RING.ry} fill="none" stroke="rgba(0,212,255,0.10)" strokeWidth="1" strokeDasharray="2 9" />

        {HE_NODES.map((n, i) => {
          const d = hePath(n, i);
          return (
            <g key={i}>
              {/* base trace */}
              <path d={d} fill="none" stroke="url(#heGrad)" strokeWidth="1.3" opacity="0.22" />
              {/* flowing signal dashes */}
              <path d={d} fill="none" stroke="#00D4FF" strokeWidth="1.3" strokeDasharray="1.5 9" strokeLinecap="round"
                opacity="0.6" className="he-flow" style={{ animationDelay: `${(i % 5) * 0.34}s` }} />
              {/* endpoint node */}
              <circle cx={n.x} cy={n.y} r="3.4" fill="#05070D" stroke="#00D4FF" strokeWidth="1.4" />
              <circle cx={n.x} cy={n.y} r="1.5" fill="#00D4FF" />
              {/* traveling data pulse */}
              <circle r="2.5" fill="#7FE7FF" filter="url(#heGlow)">
                <animateMotion dur="2.8s" begin={`${i * 0.31}s`} repeatCount="indefinite" path={d} keyPoints="0;1" keyTimes="0;1" calcMode="spline" keySplines="0.4 0 0.2 1" />
                <animate attributeName="opacity" dur="2.8s" begin={`${i * 0.31}s`} repeatCount="indefinite" values="0;1;1;0" keyTimes="0;0.12;0.85;1" />
              </circle>
            </g>
          );
        })}
      </svg>

      {/* center core */}
      <div style={{ position: 'absolute', left: pct(RING.cx, HE_W), top: pct(RING.cy, HE_H), transform: 'translate(-50%,-50%)', zIndex: 3 }}>
        <HeroCore />
      </div>

      {/* channel / system nodes */}
      {HE_NODES.map((n, i) => (
        <div key={n.label} className="reveal he-node" style={{
          position: 'absolute', left: pct(n.x, HE_W), top: pct(n.y, HE_H),
          transform: 'translate(-50%,-50%)', zIndex: 2, transitionDelay: `${130 + i * 50}ms`,
        }}>
          <div className="he-card">
            <span style={heNodeIcon}><i data-lucide={n.icon} style={{ width: 15, height: 15 }}></i></span>
            <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 11.5, fontWeight: 500, color: 'var(--ar-text-main)', whiteSpace: 'nowrap' }}>{n.label}</span>
          </div>
        </div>
      ))}

      {/* result microcards (corners — sinais de execução) */}
      {HE_RESULTS.map((r, i) => (
        <div key={r.label} className="reveal he-result" style={{
          position: 'absolute', left: pct(r.x, HE_W), top: pct(r.y, HE_H),
          transform: `translate(${r.anchor === 'r' ? '-100%' : '0'}, -50%)`,
          zIndex: 2, transitionDelay: `${420 + i * 90}ms`, ['--fd']: `${i * 0.7}s`,
        }}>
          <HeroResult {...r} />
        </div>
      ))}

      <style>{`
        .he-card {
          display:inline-flex; align-items:center; gap:8px; padding:6px 11px 6px 6px; border-radius:11px;
          background:linear-gradient(150deg, rgba(16,24,43,0.96), rgba(8,12,24,0.92));
          border:1px solid rgba(0,212,255,0.22); box-shadow:0 12px 28px -16px rgba(0,0,0,0.85);
          backdrop-filter:blur(6px); transition:border-color 220ms var(--ar-ease), transform 220ms var(--ar-ease), box-shadow 220ms var(--ar-ease);
        }
        .he-node:hover .he-card { border-color:rgba(0,212,255,0.55); transform:translateY(-2px); box-shadow:0 14px 30px -14px rgba(0,94,255,0.5); }
        .he-flow { animation: heDash 1.6s linear infinite; }
        @keyframes heDash { to { stroke-dashoffset:-21; } }
        .he-result { animation: heFloat 6.5s ease-in-out infinite; animation-delay: var(--fd, 0s); }
        @keyframes heFloat { 0%,100%{ translate:0 0; } 50%{ translate:0 -5px; } }
        @media (prefers-reduced-motion: reduce) {
          .he-flow, .he-result { animation:none !important; }
        }
      `}</style>
    </div>
  );
};

/* ---- central core node (menor, elegante) ---- */
const HeroCore = ({ mobile }) => {
  const d = mobile ? 100 : 104;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 11 }}>
      <div className="he-core" style={{ position: 'relative', width: d, height: d, borderRadius: 999, flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'radial-gradient(circle at 50% 34%, #0a4fd8 0%, #06245f 60%, #07142c 100%)',
        border: '1px solid rgba(0,212,255,0.5)',
      }}>
        <span className="he-ring" />
        <span className="he-ring he-ring2" />
        <i data-lucide="bot" style={{ width: mobile ? 38 : 40, height: mobile ? 38 : 40, color: '#fff', filter: 'drop-shadow(0 0 9px rgba(0,212,255,0.7))', position: 'relative', zIndex: 2 }}></i>
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontFamily: 'var(--ar-font-title)', fontWeight: 700, fontSize: 14, color: 'var(--ar-text-main)', letterSpacing: '-0.01em' }}>Agente de IA AR</div>
        <div style={{ marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999, background: 'rgba(31,209,123,0.10)', border: '1px solid rgba(31,209,123,0.32)' }}>
          <span className="he-pulse" style={{ width: 5, height: 5, borderRadius: 999, background: '#1FD17B' }} />
          <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 10.5, fontWeight: 600, color: '#1FD17B' }}>em execução</span>
        </div>
      </div>
      <style>{`
        .he-core { box-shadow:0 0 0 1px rgba(0,212,255,0.16), 0 0 46px rgba(0,94,255,0.5), inset 0 0 22px rgba(0,212,255,0.2); animation: heBreathe 4.5s ease-in-out infinite; }
        @keyframes heBreathe {
          0%,100% { box-shadow:0 0 0 1px rgba(0,212,255,0.16), 0 0 40px rgba(0,94,255,0.42), inset 0 0 22px rgba(0,212,255,0.18); }
          50%     { box-shadow:0 0 0 1px rgba(0,212,255,0.24), 0 0 58px rgba(0,94,255,0.62), inset 0 0 26px rgba(0,212,255,0.26); }
        }
        .he-ring, .he-ring2 { position:absolute; inset:0; border-radius:999px; border:1px solid rgba(0,212,255,0.4); animation: heRing 3.4s ease-out infinite; }
        .he-ring2 { animation-delay:1.7s; }
        @keyframes heRing { 0%{ transform:scale(1); opacity:.55; } 70%,100%{ transform:scale(1.85); opacity:0; } }
        .he-pulse { animation: hePulse 1.8s var(--ar-ease) infinite; }
        @keyframes hePulse { 0%,100%{ box-shadow:0 0 0 0 rgba(31,209,123,0.5);} 50%{ box-shadow:0 0 0 5px rgba(31,209,123,0);} }
        @media (prefers-reduced-motion: reduce) { .he-core, .he-ring, .he-ring2, .he-pulse { animation:none !important; } }
      `}</style>
    </div>
  );
};

/* ---- result microcard ---- */
const HeroResult = ({ icon, label, mobile }) => (
  <div style={{
    display: 'inline-flex', alignItems: 'center', gap: 7, whiteSpace: 'nowrap',
    padding: '5px 11px 5px 6px', borderRadius: 999,
    background: 'rgba(8,12,24,0.78)', border: '1px solid rgba(31,209,123,0.30)',
    backdropFilter: 'blur(8px)', boxShadow: '0 10px 24px -14px rgba(0,0,0,0.85)',
  }}>
    <span style={{ width: 18, height: 18, borderRadius: 999, background: 'rgba(31,209,123,0.16)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#1FD17B', flexShrink: 0 }}>
      <i data-lucide={icon} style={{ width: 11, height: 11 }}></i>
    </span>
    <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: mobile ? 10.5 : 11, fontWeight: 500, color: '#C9F4DD' }}>{label}</span>
  </div>
);

/* ---- shared styles ---- */
const heNodeIcon = {
  width: 26, height: 26, borderRadius: 8, flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  background: 'rgba(0,212,255,0.10)', border: '1px solid rgba(0,212,255,0.30)', color: '#00D4FF',
};
const heChipStyle = {
  display: 'flex', alignItems: 'center', gap: 9, padding: '10px 11px', borderRadius: 13,
  background: 'var(--ar-bg-card)', border: '1px solid rgba(255,255,255,0.10)',
};

window.HeroEcosystem = HeroEcosystem;
