/* Clara v2 — Agentes como red de avatars alrededor del core de Clara */

/* Outline icons (no fill) for agents — local copies so sections.jsx isn't required */
function AgentIconBoxes() {
  return (
    <svg width="34" height="34" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.4">
      <rect x="3" y="3" width="9" height="9" /><rect x="16" y="3" width="9" height="9" />
      <rect x="3" y="16" width="9" height="9" /><rect x="16" y="16" width="9" height="9" />
    </svg>
  );
}
function AgentIconCoin() {
  return (
    <svg width="34" height="34" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="14" cy="14" r="11" /><path d="M14 7 V21 M10 11 H17 a2.4 2.4 0 0 1 0 5 H11 a2.4 2.4 0 0 0 0 5 H18" />
    </svg>
  );
}
function AgentIconChart() {
  return (
    <svg width="34" height="34" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M3 24 H25" /><path d="M6 20 V12" /><path d="M12 20 V6" /><path d="M18 20 V14" /><path d="M24 20 V9" />
    </svg>
  );
}
function AgentIconWave() {
  return (
    <svg width="34" height="34" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M3 17 C 7 9, 11 9, 14 14 S 21 19, 25 11" />
      <circle cx="14" cy="14" r="1.6" /><circle cx="25" cy="11" r="1.6" />
    </svg>
  );
}
function AgentIconNodes() {
  return (
    <svg width="34" height="34" viewBox="0 0 28 28" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="6" cy="6" r="2.4" /><circle cx="22" cy="6" r="2.4" /><circle cx="14" cy="22" r="2.4" /><circle cx="14" cy="13" r="2.4" />
      <path d="M8 8 L13 12 M20 8 L15 12 M14 16 V19" />
    </svg>
  );
}

const AGENTS_V2 = [
  {
    code: 'INV',
    name: 'Analista de inventario',
    desc: 'Detecta rotación, alertas de stockout y capital inmovilizado. Te dice qué referencias mover y cuándo.',
    Icon: AgentIconBoxes,
    // anchor position in % of stage
    angle: 200,  // degrees, 0 = right
  },
  {
    code: 'FIN',
    name: 'Asesor financiero',
    desc: 'Margen, EBITDA, flujo de caja y rentabilidad por línea. La vista que tu director financiero arma cada lunes — todos los días.',
    Icon: AgentIconCoin,
    angle: 250,
  },
  {
    code: 'MKT',
    name: 'Estratega de ventas y marketing',
    desc: 'Performance de campañas, ROAS real, mix de canales. Te dice qué campaña pausar antes de gastar el siguiente peso.',
    Icon: AgentIconChart,
    angle: 300,
  },
  {
    code: 'FCT',
    name: 'Predictor de demanda',
    desc: 'Tendencias, estacionalidad y proyecciones por producto. Te dice qué pedir, cuánto y cuándo.',
    Icon: AgentIconWave,
    angle: 350,
  },
  {
    code: 'B2B',
    name: 'Agente de clientes B2B',
    desc: 'Comportamiento de cuentas, riesgo de churn y oportunidades de expansión. Quién está creciendo y quién se está yendo.',
    Icon: AgentIconNodes,
    angle: 40,
  },
];

function AgentsOrbit() {
  const stageRef = React.useRef(null);
  const [dims, setDims] = React.useState({ w: 1000, h: 580, rx: 360, ry: 200 });
  const [lit, setLit] = React.useState(false);
  const beatRef = useBeatAnchor('beat-agents');

  React.useEffect(() => {
    const onResize = () => {
      const el = stageRef.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      setDims({
        w: r.width,
        h: r.height,
        rx: Math.min(r.width * 0.36, 380),
        ry: Math.min(r.height * 0.38, 220)
      });
    };
    onResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  React.useEffect(() => {
    const off = BeatBus.on((k) => {
      if (k === 'beat-agents') {
        setLit(true);
        setTimeout(() => setLit(false), 1400);
      }
    });
    return off;
  }, []);

  const cx = dims.w / 2;
  const cy = dims.h / 2;

  const positions = AGENTS_V2.map((a) => {
    const rad = (a.angle * Math.PI) / 180;
    return {
      ...a,
      x: cx + Math.cos(rad) * dims.rx,
      y: cy + Math.sin(rad) * dims.ry,
    };
  });

  // Bezier curves from core to each agent
  const paths = positions.map((p) => {
    const mx = (cx + p.x) / 2;
    const my = (cy + p.y) / 2 - 30;
    return `M ${cx} ${cy} Q ${mx} ${my} ${p.x} ${p.y}`;
  });

  return (
    <React.Fragment>
      <div className={`agents-stage ${lit ? 'lit' : ''}`} ref={(el) => { stageRef.current = el; beatRef.current = el; }}>
        <svg className="orbit-svg" viewBox={`0 0 ${dims.w} ${dims.h}`} preserveAspectRatio="none">
          <defs>
            <linearGradient id="orbit-line" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#1C1C1C" stopOpacity="0.35" />
              <stop offset="100%" stopColor="#E8006F" stopOpacity="0.65" />
            </linearGradient>
            <radialGradient id="orbit-glow" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor="rgba(232,0,111,0.20)" />
              <stop offset="60%" stopColor="rgba(232,0,111,0.06)" />
              <stop offset="100%" stopColor="rgba(232,0,111,0)" />
            </radialGradient>
          </defs>

          {/* glow halo behind core */}
          <ellipse cx={cx} cy={cy} rx={dims.rx * 0.92} ry={dims.ry * 0.92} fill="url(#orbit-glow)" />

          {/* dashed orbit ring */}
          <ellipse
            cx={cx}
            cy={cy}
            rx={dims.rx}
            ry={dims.ry}
            fill="none"
            stroke="rgba(28,28,28,0.10)"
            strokeWidth="1"
            strokeDasharray="2 4"
          />

          {/* connector paths */}
          {paths.map((d, i) => (
            <path
              key={i}
              d={d}
              fill="none"
              stroke="url(#orbit-line)"
              strokeWidth="1.4"
              strokeDasharray="3 6"
              style={{ opacity: 0.5 }}
            />
          ))}
        </svg>

        {/* Center: Clara core */}
        <div className="agent-core">
          <div className="logo">CLARA<span className="live" /></div>
          <div className="label">El equipo</div>
        </div>

        {/* Agent nodes */}
        {positions.map((p) => {
          const Icon = p.Icon;
          return (
            <div
              key={p.code}
              className="agent-node"
              style={{ left: p.x, top: p.y }}
            >
              <span className="label-tip">
                <span className="pip" />
                {p.code}
              </span>
              <div className="avatar">
                <Icon />
              </div>
              <div className="role">{p.name}</div>
              <div className="desc">{p.desc}</div>
            </div>
          );
        })}
      </div>

      {/* Mobile fallback */}
      <div className="agents-grid-mobile">
        {AGENTS_V2.map((a) => {
          const Icon = a.Icon;
          return (
            <div className="ag-row" key={a.code}>
              <div className="avatar"><Icon /></div>
              <div>
                <div className="role">{a.name}</div>
                <div className="desc">{a.desc}</div>
              </div>
            </div>
          );
        })}
      </div>
    </React.Fragment>
  );
}

window.AgentsOrbit = AgentsOrbit;
