// hero-flow.jsx — animated automation flow diagram for the hero
// Nodes connected by paths with flowing dots traveling along them.

const HeroFlow = () => {
  const nodes = [
    { id: 'lead', x: 60, y: 40, w: 150, h: 56, label: 'New Lead', sub: 'Form / Ad / Referral', icon: '◉', kind: 'input' },
    { id: 'ai', x: 280, y: 40, w: 150, h: 56, label: 'AI Qualify', sub: 'Score & enrich', icon: '✦', kind: 'ai' },
    { id: 'crm', x: 500, y: 40, w: 150, h: 56, label: 'CRM Update', sub: 'Pipeline → Stage 2', icon: '▤', kind: 'data' },
    { id: 'mail', x: 60, y: 170, w: 150, h: 56, label: 'Send Email', sub: 'Personalized reply', icon: '✉', kind: 'action' },
    { id: 'task', x: 280, y: 170, w: 150, h: 56, label: 'Create Task', sub: 'Owner: Sales', icon: '✓', kind: 'action' },
    { id: 'notify', x: 500, y: 170, w: 150, h: 56, label: 'Notify Team', sub: 'Slack #sales', icon: '◈', kind: 'output' },
  ];

  // edges connect node centers via right-side / left-side ports
  const edges = [
    { from: 'lead', to: 'ai' },
    { from: 'ai', to: 'crm' },
    { from: 'crm', to: 'notify' },
    { from: 'ai', to: 'task' },
    { from: 'lead', to: 'mail' },
    { from: 'task', to: 'notify' },
    { from: 'mail', to: 'task' },
  ];

  const byId = Object.fromEntries(nodes.map(n => [n.id, n]));
  const port = (n, side) => ({
    x: side === 'r' ? n.x + n.w : side === 'l' ? n.x : n.x + n.w / 2,
    y: side === 'b' ? n.y + n.h : side === 't' ? n.y : n.y + n.h / 2
  });

  // Build SVG path between two nodes — pick ports based on relative pos
  const pathFor = (e) => {
    const a = byId[e.from];
    const b = byId[e.to];
    const dx = b.x - a.x;
    const dy = b.y - a.y;
    let p1, p2;
    if (Math.abs(dx) > Math.abs(dy)) {
      p1 = port(a, dx > 0 ? 'r' : 'l');
      p2 = port(b, dx > 0 ? 'l' : 'r');
      const mx = (p1.x + p2.x) / 2;
      return `M ${p1.x} ${p1.y} C ${mx} ${p1.y}, ${mx} ${p2.y}, ${p2.x} ${p2.y}`;
    } else {
      p1 = port(a, dy > 0 ? 'b' : 't');
      p2 = port(b, dy > 0 ? 't' : 'b');
      const my = (p1.y + p2.y) / 2;
      return `M ${p1.x} ${p1.y} C ${p1.x} ${my}, ${p2.x} ${my}, ${p2.x} ${p2.y}`;
    }
  };

  const kindColor = {
    input: 'var(--accent)',
    ai: 'var(--ai)',
    data: 'var(--accent)',
    action: 'var(--success)',
    output: 'var(--accent)'
  };

  const [pulseIdx, setPulseIdx] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setPulseIdx(i => (i + 1) % nodes.length), 900);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="hero-flow">
      <svg viewBox="0 0 720 260" className="hero-flow-svg" preserveAspectRatio="xMidYMid meet">
        <defs>
          <pattern id="flow-grid" width="20" height="20" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="0.6" fill="rgba(255,255,255,0.07)" />
          </pattern>
          <radialGradient id="flow-fade" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="rgba(0,0,0,0)" />
            <stop offset="100%" stopColor="rgba(0,0,0,0.4)" />
          </radialGradient>
        </defs>

        <rect width="720" height="260" fill="url(#flow-grid)" />
        <rect width="720" height="260" fill="url(#flow-fade)" />

        {/* edges */}
        {edges.map((e, i) => {
          const d = pathFor(e);
          const fromKind = byId[e.from].kind;
          const c = kindColor[fromKind];
          return (
            <g key={i}>
              <path d={d} stroke="rgba(255,255,255,0.1)" strokeWidth="1.2" fill="none" />
              <path d={d} stroke={c} strokeWidth="1.2" fill="none" strokeDasharray="3 6" opacity="0.4">
                <animate attributeName="stroke-dashoffset" from="0" to="-18" dur="1.4s" repeatCount="indefinite" />
              </path>
              {/* flowing dot */}
              <circle r="2.5" fill={c} opacity="0.9">
                <animateMotion dur={`${2.4 + (i % 3) * 0.4}s`} repeatCount="indefinite" begin={`${i * 0.3}s`} path={d} />
              </circle>
            </g>
          );
        })}

        {/* nodes */}
        {nodes.map((n, i) => {
          const c = kindColor[n.kind];
          const active = i === pulseIdx;
          return (
            <g key={n.id} transform={`translate(${n.x}, ${n.y})`}>
              <rect
                width={n.w} height={n.h} rx="10"
                fill="rgba(16,22,36,0.92)"
                stroke={active ? c : 'rgba(255,255,255,0.12)'}
                strokeWidth={active ? 1.4 : 1}
                style={{ transition: 'stroke 0.3s' }}
              />
              {active && (
                <rect width={n.w} height={n.h} rx="10" fill="none" stroke={c} strokeWidth="1" opacity="0.4">
                  <animate attributeName="opacity" values="0.6;0;0.6" dur="0.9s" repeatCount="indefinite" />
                </rect>
              )}
              <circle cx="18" cy={n.h / 2} r="11" fill={`color-mix(in oklab, ${c}, transparent 78%)`} />
              <text x="18" y={n.h / 2 + 4} textAnchor="middle" fill={c} fontSize="11" fontFamily="ui-monospace, JetBrains Mono, monospace">{n.icon}</text>
              <text x="38" y="22" fill="var(--text)" fontSize="12" fontWeight="600" fontFamily="ui-sans-serif, system-ui">{n.label}</text>
              <text x="38" y="38" fill="var(--muted)" fontSize="10" fontFamily="ui-monospace, JetBrains Mono, monospace">{n.sub}</text>

              {/* status dot */}
              <circle cx={n.w - 14} cy="14" r="3" fill={active ? c : 'rgba(255,255,255,0.18)'} />
              {active && (
                <circle cx={n.w - 14} cy="14" r="3" fill={c} opacity="0.4">
                  <animate attributeName="r" values="3;7;3" dur="0.9s" repeatCount="indefinite" />
                  <animate attributeName="opacity" values="0.5;0;0.5" dur="0.9s" repeatCount="indefinite" />
                </circle>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
};

window.HeroFlow = HeroFlow;
