// AutomationViz v2, cinematic AI agent pipeline
// Shows a real multi-agent system: Trigger → Classify → Route → Act → Verify → Respond
// No tabs needed, this IS the hero viz alongside the agent graph
const { useRef: useAvRef, useEffect: useAvEffect, useState: useAvState } = React;

// Agent nodes in the pipeline
const PIPELINE = [
  { id: 'trigger',  label: 'Trigger',   sub: 'Incoming event',    color: '#00D9A0', x: 60,  y: 200 },
  { id: 'classify', label: 'Classify',  sub: 'Intent detection',  color: '#7C5CFF', x: 200, y: 120 },
  { id: 'memory',   label: 'Memory',    sub: 'Context retrieval', color: '#7C5CFF', x: 200, y: 280 },
  { id: 'llm',      label: 'LLM Core',  sub: 'Reasoning',         color: '#00D9A0', x: 360, y: 200 },
  { id: 'tool',     label: 'Tool Use',  sub: 'API / Action',      color: '#FF8A4C', x: 500, y: 120 },
  { id: 'verify',   label: 'Eval',      sub: 'Quality check',     color: '#FF8A4C', x: 500, y: 280 },
  { id: 'respond',  label: 'Respond',   sub: 'Output delivered',  color: '#00D9A0', x: 640, y: 200 },
];

const EDGES = [
  { from: 'trigger',  to: 'classify', primary: true  },
  { from: 'trigger',  to: 'memory',   primary: false },
  { from: 'classify', to: 'llm',      primary: true  },
  { from: 'memory',   to: 'llm',      primary: true  },
  { from: 'llm',      to: 'tool',     primary: true  },
  { from: 'llm',      to: 'verify',   primary: true  },
  { from: 'tool',     to: 'respond',  primary: true  },
  { from: 'verify',   to: 'respond',  primary: true  },
  { from: 'verify',   to: 'llm',      primary: false },  // feedback loop
];

// Live event stream cycling through
const EVENTS = [
  { label: 'New lead · Med Spa · Instagram DM',       vertical: 'Med Spa',     result: 'Appointment booked',      time: '1.2s' },
  { label: 'Invoice query · CPA client · Email',      vertical: 'CPA',         result: 'Draft sent to partner',   time: '0.8s' },
  { label: 'Contract review · Law firm · Upload',     vertical: 'Law Firm',    result: 'Summary + flags ready',   time: '2.1s' },
  { label: 'Lead form · Real estate · Web',           vertical: 'Real Estate', result: 'Qualified + scheduled',   time: '0.6s' },
  { label: 'Support ticket · E-commerce · Chat',      vertical: 'Retail',      result: 'Resolved autonomously',   time: '0.4s' },
  { label: 'Missed call · Med Spa · Voicemail',       vertical: 'Med Spa',     result: 'SMS rebooking sent',      time: '0.9s' },
];

function AutomationViz() {
  const [tick, setTick] = useAvState(0);
  const [activeNode, setActiveNode] = useAvState('trigger');
  const [activePath, setActivePath] = useAvState([]);
  const [eventIdx, setEventIdx] = useAvState(0);
  const [phaseT, setPhaseT] = useAvState(0);
  const rafRef = useAvRef(null);
  const startRef = useAvRef(null);
  const lastEventRef = useAvRef(0);

  // Animation loop
  useAvEffect(() => {
    const CYCLE = 3.5; // seconds per event
    const PATH_SEQUENCE = ['trigger','classify','memory','llm','tool','verify','respond'];

    const loop = (ts) => {
      if (!startRef.current) startRef.current = ts;
      const t = (ts - startRef.current) / 1000;
      setTick(t);

      // Which event
      const eIdx = Math.floor(t / CYCLE) % EVENTS.length;
      setEventIdx(eIdx);

      // Phase within cycle (0..1)
      const phase = (t % CYCLE) / CYCLE;
      setPhaseT(phase);

      // Which node is active based on phase
      const nodeIdx = Math.floor(phase * PATH_SEQUENCE.length);
      setActiveNode(PATH_SEQUENCE[Math.min(nodeIdx, PATH_SEQUENCE.length - 1)]);

      // Active path up to current node
      const pathSoFar = PATH_SEQUENCE.slice(0, nodeIdx + 1);
      setActivePath(pathSoFar);

      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  const getNode = (id) => PIPELINE.find(n => n.id === id);

  const getEdgePath = (edge) => {
    const a = getNode(edge.from);
    const b = getNode(edge.to);
    if (!a || !b) return '';
    const dx = b.x - a.x;
    const dy = b.y - a.y;
    const mx = a.x + dx * 0.5;
    const my = a.y + dy * 0.5 - (Math.abs(dy) < 10 ? 0 : 10);
    return `M ${a.x} ${a.y} Q ${mx} ${my} ${b.x} ${b.y}`;
  };

  const isEdgeActive = (edge) => {
    return activePath.includes(edge.from) && activePath.includes(edge.to);
  };

  const currentEvent = EVENTS[eventIdx];
  const isDone = phaseT > 0.85;

  return (
    <div style={{
      background: 'var(--bg-secondary)',
      border: '1px solid var(--border-subtle)',
      borderRadius: 16,
      overflow: 'hidden',
      position: 'relative',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 20px',
        borderBottom: '1px solid var(--border-subtle)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'var(--bg-tertiary)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
            color: 'var(--text-tertiary)', letterSpacing: '0.1em',
          }}>// AGENT PIPELINE</span>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
            color: 'var(--accent-mint)',
          }}>
            <span style={{
              width: 5, height: 5, borderRadius: '50%',
              background: 'var(--accent-mint)',
              boxShadow: '0 0 6px var(--accent-mint)',
              animation: 'av-blink 1.5s ease infinite',
            }} />
            live
          </span>
        </div>
        {/* Clock */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
          background: 'rgba(124,92,255,0.1)',
          border: '1px solid rgba(124,92,255,0.2)',
          borderRadius: 6, padding: '3px 10px',
        }}>
          <span style={{ fontSize: 10 }}>🌙</span>
          <span style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 500,
            color: 'var(--accent-violet)',
          }}>03:{String(Math.floor((tick * 2.3) % 60)).padStart(2,'0')} AM</span>
        </div>
      </div>

      {/* SVG Pipeline */}
      <div style={{ padding: '8px 12px 0', position: 'relative' }}>
        <svg viewBox="0 0 720 380" style={{ width: '100%', height: 'auto', overflow: 'visible' }}>
          <defs>
            {PIPELINE.map(n => (
              <filter key={n.id} id={`glow-${n.id}`}>
                <feGaussianBlur stdDeviation="4" result="blur"/>
                <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
              </filter>
            ))}
            {/* Animated gradient for active edges */}
            <linearGradient id="flowGrad" x1="0%" y1="0%" x2="100%" y2="0%">
              <stop offset="0%" stopColor="#00D9A0" stopOpacity="0"/>
              <stop offset="50%" stopColor="#00D9A0" stopOpacity="1"/>
              <stop offset="100%" stopColor="#7C5CFF" stopOpacity="0"/>
            </linearGradient>
          </defs>

          {/* Background grid */}
          {[0,1,2,3,4].map(i => (
            <line key={`h${i}`} x1={0} y1={80+i*60} x2={720} y2={80+i*60}
              stroke="rgba(255,255,255,0.02)" strokeWidth={1} />
          ))}

          {/* Edges, inactive */}
          {EDGES.map((edge, i) => (
            <path key={`base-${i}`}
              d={getEdgePath(edge)}
              fill="none"
              stroke={isEdgeActive(edge) ? edge.primary ? 'rgba(0,217,160,0.5)' : 'rgba(124,92,255,0.3)' : 'rgba(255,255,255,0.06)'}
              strokeWidth={isEdgeActive(edge) ? 1.5 : 1}
              strokeDasharray={edge.primary ? 'none' : '4 4'}
              style={{ transition: 'stroke 0.4s ease, stroke-width 0.3s ease' }}
            />
          ))}

          {/* Animated data packets on active edges */}
          {EDGES.filter(e => isEdgeActive(e) && e.primary).map((edge, i) => {
            const path = getEdgePath(edge);
            const fromNode = getNode(edge.from);
            return (
              <circle key={`packet-${i}`} r={3}
                fill={fromNode?.color || '#00D9A0'}
                opacity={0.9}
              >
                <animateMotion dur={`${0.8 + i * 0.1}s`} repeatCount="indefinite" path={path} />
              </circle>
            );
          })}

          {/* Nodes */}
          {PIPELINE.map((node) => {
            const isActive = activeNode === node.id;
            const isVisited = activePath.includes(node.id);
            const pulse = Math.sin(tick * 2 + PIPELINE.indexOf(node) * 0.9) * 0.5 + 0.5;

            return (
              <g key={node.id} transform={`translate(${node.x}, ${node.y})`}>
                {/* Glow ring when active */}
                {isActive && (
                  <circle r={30} fill="none"
                    stroke={node.color} strokeWidth={1}
                    opacity={0.2 + pulse * 0.2}
                    style={{ animation: 'av-ring 1.5s ease-in-out infinite' }}
                  />
                )}

                {/* Outer ring */}
                <circle r={22} fill="none"
                  stroke={isVisited ? node.color : 'rgba(255,255,255,0.1)'}
                  strokeWidth={isActive ? 1.5 : 0.5}
                  opacity={isVisited ? (isActive ? 0.8 : 0.4) : 0.15}
                  style={{ transition: 'all 0.4s ease' }}
                />

                {/* Core */}
                <circle r={16}
                  fill={isActive ? `${node.color}22` : isVisited ? `${node.color}0A` : 'var(--bg-tertiary)'}
                  stroke={isVisited ? node.color : 'rgba(255,255,255,0.1)'}
                  strokeWidth={isActive ? 1.5 : 0.8}
                  filter={isActive ? `url(#glow-${node.id})` : undefined}
                  style={{ transition: 'all 0.4s ease' }}
                />

                {/* Center dot */}
                <circle r={isActive ? 4 : 2.5}
                  fill={isVisited ? node.color : 'rgba(255,255,255,0.2)'}
                  style={{ transition: 'all 0.3s ease' }}
                />

                {/* Label above */}
                <text y={-28} textAnchor="middle"
                  fill={isActive ? node.color : isVisited ? 'rgba(245,245,247,0.7)' : 'rgba(245,245,247,0.3)'}
                  fontSize={10} fontFamily="JetBrains Mono, monospace" fontWeight={600}
                  style={{ transition: 'fill 0.3s ease', userSelect: 'none' }}
                >{node.label}</text>

                {/* Sub-label below */}
                <text y={32} textAnchor="middle"
                  fill={isActive ? 'rgba(245,245,247,0.6)' : 'rgba(245,245,247,0.18)'}
                  fontSize={8} fontFamily="JetBrains Mono, monospace"
                  style={{ transition: 'fill 0.3s ease', userSelect: 'none' }}
                >{node.sub}</text>
              </g>
            );
          })}
        </svg>
      </div>

      {/* Live event feed */}
      <div style={{
        margin: '0 12px 12px',
        padding: '12px 14px',
        background: 'var(--bg-tertiary)',
        border: `1px solid ${isDone ? 'rgba(0,217,160,0.3)' : 'var(--border-subtle)'}`,
        borderRadius: 10,
        transition: 'border-color 0.4s ease',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
              color: 'var(--text-tertiary)', letterSpacing: '0.08em', marginBottom: 4,
            }}>PROCESSING</div>
            <div style={{
              fontFamily: 'Inter, sans-serif', fontSize: 12,
              color: 'var(--text-primary)', lineHeight: 1.4,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{currentEvent.label}</div>
          </div>

          {isDone ? (
            <div style={{
              display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3,
              flexShrink: 0,
            }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 5,
                background: 'rgba(0,217,160,0.12)',
                border: '1px solid rgba(0,217,160,0.3)',
                borderRadius: 5, padding: '3px 8px',
              }}>
                <span style={{ color: 'var(--accent-mint)', fontSize: 10 }}>✓</span>
                <span style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                  color: 'var(--accent-mint)',
                }}>{currentEvent.result}</span>
              </div>
              <span style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
                color: 'var(--text-tertiary)',
              }}>{currentEvent.time}</span>
            </div>
          ) : (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 5,
              flexShrink: 0,
            }}>
              {[0,1,2].map(i => (
                <span key={i} style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: 'var(--accent-mint)', opacity: 0.4,
                  animation: `av-bounce 1s ease-in-out ${i * 0.18}s infinite`,
                }} />
              ))}
            </div>
          )}
        </div>

        {/* Progress bar */}
        <div style={{
          marginTop: 10, height: 2,
          background: 'var(--border-subtle)',
          borderRadius: 1, overflow: 'hidden',
        }}>
          <div style={{
            height: '100%',
            background: 'linear-gradient(90deg, var(--accent-mint), var(--accent-violet))',
            width: `${phaseT * 100}%`,
            borderRadius: 1,
            boxShadow: '0 0 8px rgba(0,217,160,0.5)',
            transition: 'width 0.1s linear',
          }} />
        </div>
      </div>

      {/* Bottom stats */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
        borderTop: '1px solid var(--border-subtle)',
      }}>
        {[
          { val: `${47 + Math.floor(tick * 0.4)}`, label: 'handled tonight' },
          { val: '< 90s', label: 'avg response' },
          { val: '0', label: 'human touches' },
        ].map((s, i) => (
          <div key={i} style={{
            textAlign: 'center', padding: '10px 8px',
            borderRight: i < 2 ? '1px solid var(--border-subtle)' : 'none',
          }}>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace',
              fontSize: 16, fontWeight: 700, lineHeight: 1,
              color: i === 2 ? 'var(--accent-mint)' : 'var(--text-primary)',
            }}>{s.val}</div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
              color: 'var(--text-tertiary)', marginTop: 3,
            }}>{s.label}</div>
          </div>
        ))}
      </div>

      <style>{`
        @keyframes av-blink { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes av-ring  { 0%,100%{transform:scale(1);opacity:0.3} 50%{transform:scale(1.08);opacity:0.15} }
        @keyframes av-bounce { 0%,80%,100%{transform:translateY(0)} 40%{transform:translateY(-4px)} }
      `}</style>
    </div>
  );
}

Object.assign(window, { AutomationViz });
