// The animated agent terminal + workflow diagram

const AgentTerminal = () => {
  const script = React.useMemo(() => [
    { tag: 'agent.pulse', text: 'scanning Slack #launches...' },
    { tag: 'agent.pulse', text: 'new launch detected: "Q2 Beta"', check: true },
    { tag: 'agent.pulse', text: 'drafting brief from thread context' },
    { tag: 'agent.pulse', text: 'posting to Asana · 12 tasks', check: true },
    { tag: 'agent.pulse', text: 'notifying ops on Telegram', check: true },
    { tag: 'agent.pulse', text: 'logging outcome to Supabase', check: true },
  ], []);

  const [visible, setVisible] = React.useState(0);
  const [runtime, setRuntime] = React.useState(0);
  const [cycle, setCycle] = React.useState(0);

  React.useEffect(() => {
    if (visible < script.length) {
      const t = setTimeout(() => setVisible(v => v + 1), 700);
      return () => clearTimeout(t);
    }
    // hold, then reset
    const t = setTimeout(() => { setVisible(0); setRuntime(0); setCycle(c => c + 1); }, 3500);
    return () => clearTimeout(t);
  }, [visible, script.length, cycle]);

  React.useEffect(() => {
    if (visible > 0 && visible <= script.length) {
      setRuntime(r => +(r + (0.6 + Math.random() * 0.4)).toFixed(1));
    }
  }, [visible, script.length]);

  return (
    <div className="terminal">
      <div className="terminal-head">
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <div className="terminal-dots">
            <span className="terminal-dot"></span>
            <span className="terminal-dot"></span>
            <span className="terminal-dot"></span>
          </div>
          <span className="terminal-title">launch-coordinator.agent</span>
        </div>
        <span className="terminal-live">LIVE</span>
      </div>
      <div className="terminal-body">
        {script.slice(0, visible).map((line, i) => (
          <div className="term-line" key={`${cycle}-${i}`}>
            <span className="term-dim">[</span>
            <span className="term-tag" style={{ marginLeft: -6, marginRight: -6 }}>{line.tag}</span>
            <span className="term-dim">]</span>
            <span style={{ flex: 1 }}>{line.text}</span>
            {line.check && <span className="term-check">✓</span>}
          </div>
        ))}
        {visible < script.length && (
          <div className="term-line" style={{ opacity: 0.6 }}>
            <span className="term-cursor"></span>
          </div>
        )}
        {visible === script.length && (
          <div className="term-runtime">
            <span>runtime</span>
            <span className="val">{runtime.toFixed(1)}s · 0 errors · {script.length} steps</span>
          </div>
        )}
      </div>
    </div>
  );
};

// Workflow diagram SVG — agent hub + connected stack
const WorkflowDiagram = () => {
  const nodes = [
    { id: 'slack',     x: 60,  y: 40,  label: 'Slack' },
    { id: 'salesforce',x: 60,  y: 120, label: 'Salesforce' },
    { id: 'gmail',     x: 60,  y: 200, label: 'Gmail' },
    { id: 'agent',     x: 280, y: 120, label: 'Agent', hub: true },
    { id: 'asana',     x: 500, y: 40,  label: 'Asana' },
    { id: 'telegram',  x: 500, y: 120, label: 'Telegram' },
    { id: 'supabase',  x: 500, y: 200, label: 'Supabase' },
  ];
  const edges = [
    { from: 'slack', to: 'agent', dir: 'in' },
    { from: 'salesforce', to: 'agent', dir: 'in' },
    { from: 'gmail', to: 'agent', dir: 'in' },
    { from: 'agent', to: 'asana', dir: 'out' },
    { from: 'agent', to: 'telegram', dir: 'out' },
    { from: 'agent', to: 'supabase', dir: 'out' },
  ];
  const byId = Object.fromEntries(nodes.map(n => [n.id, n]));

  return (
    <svg className="workflow-diagram" viewBox="0 0 580 240" preserveAspectRatio="xMidYMid meet">
      <defs>
        <radialGradient id="hubGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#00C9A7" stopOpacity="0.4" />
          <stop offset="100%" stopColor="#00C9A7" stopOpacity="0" />
        </radialGradient>
      </defs>

      {edges.map((e, i) => {
        const a = byId[e.from]; const b = byId[e.to];
        return (
          <g key={i}>
            <line x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke="#1F1F1F" strokeWidth="1.5" />
            <circle r="3" fill="#00C9A7">
              <animateMotion dur={`${2.4 + i * 0.4}s`} repeatCount="indefinite" path={`M${a.x},${a.y} L${b.x},${b.y}`} />
              <animate attributeName="opacity" values="0;1;1;0" dur={`${2.4 + i * 0.4}s`} repeatCount="indefinite" />
            </circle>
          </g>
        );
      })}

      {/* hub glow */}
      <circle cx={byId.agent.x} cy={byId.agent.y} r="50" fill="url(#hubGlow)" />

      {nodes.map(n => (
        <g key={n.id}>
          <circle cx={n.x} cy={n.y} r={n.hub ? 22 : 14} fill={n.hub ? '#00C9A7' : '#111'} stroke={n.hub ? '#00C9A7' : '#2A2A2A'} strokeWidth="1.5" />
          {n.hub && <circle cx={n.x} cy={n.y} r="28" fill="none" stroke="#00C9A7" strokeOpacity="0.4" strokeWidth="1">
            <animate attributeName="r" values="22;40;22" dur="3s" repeatCount="indefinite" />
            <animate attributeName="stroke-opacity" values="0.5;0;0.5" dur="3s" repeatCount="indefinite" />
          </circle>}
          <text
            x={n.x}
            y={n.hub ? n.y + 4 : n.y + (n.x < 200 ? -24 : 32)}
            textAnchor={n.hub ? 'middle' : (n.x < 200 ? 'start' : 'end')}
            fill={n.hub ? '#000' : '#9CA3AF'}
            fontFamily="var(--font-mono)"
            fontSize="11"
            fontWeight={n.hub ? 700 : 500}
            letterSpacing="0.04em"
          >
            {n.hub ? 'AGENT' : n.label.toLowerCase()}
          </text>
        </g>
      ))}
    </svg>
  );
};

Object.assign(window, { AgentTerminal, WorkflowDiagram });
