// Abstract systems/AI visuals — no robots, no clichés. Subtle spatial depth.

// Animated "systems mesh" for hero
const SystemsMesh = ({ className = '' }) => {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Node positions in a soft constellation
  const nodes = [
    { id: 'src-a', x: 80,  y: 120, label: 'SALES_DATA',   kind: 'source' },
    { id: 'src-b', x: 80,  y: 220, label: 'ERP',           kind: 'source' },
    { id: 'src-c', x: 80,  y: 320, label: 'CRM',           kind: 'source' },
    { id: 'src-d', x: 80,  y: 420, label: 'DOCS',          kind: 'source' },
    { id: 'h-1',   x: 280, y: 170, label: 'NORMALISE',    kind: 'proc' },
    { id: 'h-2',   x: 280, y: 310, label: 'ENRICH',        kind: 'proc' },
    { id: 'h-3',   x: 280, y: 430, label: 'INDEX',         kind: 'proc' },
    { id: 'core',  x: 460, y: 280, label: 'AT · CORE',     kind: 'core' },
    { id: 'a-1',   x: 640, y: 170, label: 'COPILOT',       kind: 'out' },
    { id: 'a-2',   x: 640, y: 280, label: 'AUTOMATIONS',   kind: 'out' },
    { id: 'a-3',   x: 640, y: 390, label: 'DASHBOARDS',    kind: 'out' },
  ];

  const edges = [
    ['src-a','h-1'], ['src-b','h-1'], ['src-b','h-2'],
    ['src-c','h-2'], ['src-d','h-3'],
    ['h-1','core'], ['h-2','core'], ['h-3','core'],
    ['core','a-1'], ['core','a-2'], ['core','a-3'],
  ];
  const n = Object.fromEntries(nodes.map(x => [x.id, x]));

  return (
    <svg viewBox="0 0 760 540" className={className} style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="edgeGrad" x1="0" x2="1" y1="0" y2="0">
          <stop offset="0%" stopColor="var(--edge-bg)" />
          <stop offset="50%" stopColor="var(--green)" stopOpacity="0.55" />
          <stop offset="100%" stopColor="var(--edge-bg)" />
        </linearGradient>
        <radialGradient id="coreGrad" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="rgba(162,187,85,0.45)" />
          <stop offset="60%" stopColor="rgba(162,187,85,0.08)" />
          <stop offset="100%" stopColor="rgba(162,187,85,0)" />
        </radialGradient>
        <filter id="soft"><feGaussianBlur stdDeviation="0.5" /></filter>
      </defs>

      {/* Grid background */}
      <g opacity="0.5">
        {Array.from({length: 14}).map((_, i) => (
          <line key={'v'+i} x1={i*56} y1="0" x2={i*56} y2="540" stroke="var(--grid-line-soft)" />
        ))}
        {Array.from({length: 10}).map((_, i) => (
          <line key={'h'+i} x1="0" y1={i*56} x2="760" y2={i*56} stroke="var(--grid-line-soft)" />
        ))}
      </g>

      {/* Core halo */}
      <circle cx={n.core.x} cy={n.core.y} r="110" fill="url(#coreGrad)" />

      {/* Edges */}
      {edges.map(([a, b], i) => {
        const A = n[a], B = n[b];
        const mx = (A.x + B.x) / 2;
        const my = (A.y + B.y) / 2 - 12;
        const d = `M${A.x} ${A.y} Q ${mx} ${my} ${B.x} ${B.y}`;
        const phase = (t * 0.6 + i * 0.13) % 1;
        return (
          <g key={i}>
            <path d={d} stroke="var(--edge-bg)" strokeWidth="1" fill="none" />
            <path d={d} stroke="url(#edgeGrad)" strokeWidth="1" fill="none" strokeDasharray="3 120" strokeDashoffset={-phase * 160} />
          </g>
        );
      })}

      {/* Nodes */}
      {nodes.map(node => {
        const isCore = node.kind === 'core';
        const r = isCore ? 46 : 5;
        const fill = isCore ? 'var(--core-fill)' : 'var(--node-fill)';
        const stroke = isCore ? 'var(--green)' : 'var(--node-stroke)';
        return (
          <g key={node.id}>
            {isCore && (
              <circle cx={node.x} cy={node.y} r="68" fill="none" stroke="rgba(162,187,85,0.25)" strokeDasharray="2 4" />
            )}
            <circle cx={node.x} cy={node.y} r={r} fill={fill} stroke={stroke} strokeWidth={isCore ? 1.2 : 1} />
            {isCore && (
              <text x={node.x} y={node.y + 4} textAnchor="middle"
                fontFamily="JetBrains Mono, monospace" fontSize="11" fill="var(--fg)" letterSpacing="0.08em">
                {node.label}
              </text>
            )}
            {!isCore && (
              <text x={node.x + (node.kind === 'source' ? -10 : 10)} y={node.y + 4}
                textAnchor={node.kind === 'source' ? 'end' : 'start'}
                fontFamily="JetBrains Mono, monospace" fontSize="9.5"
                fill={node.kind === 'proc' ? 'var(--fg-2)' : 'var(--fg-3)'} letterSpacing="0.1em">
                {node.label}
              </text>
            )}
          </g>
        );
      })}

      {/* Live indicator */}
      <g transform="translate(680, 50)">
        <circle cx="0" cy="0" r="3" fill="var(--green)">
          <animate attributeName="opacity" values="1;0.3;1" dur="1.8s" repeatCount="indefinite" />
        </circle>
        <text x="10" y="4" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="var(--fg-3)" letterSpacing="0.14em">
          LIVE · 04 SYSTEMS
        </text>
      </g>
    </svg>
  );
};

// Tiny dashboard preview card used on Hero
const MiniDashboard = () => {
  const bars = [38, 52, 44, 68, 57, 72, 66, 81, 74, 88, 79, 92];
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setNow(new Date()), 60000);
    return () => clearInterval(id);
  }, []);
  const time = now.toLocaleTimeString('en-ZA', { hour: '2-digit', minute: '2-digit' });
  return (
    <div style={{
      background: 'var(--bg-1)', border: '1px solid var(--line)',
      borderRadius: '16px', padding: '18px', width: '100%',
      boxShadow: 'var(--card-shadow)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--green)', animation: 'pulseDot 1.8s infinite' }} />
          <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.14em' }}>OPS · {time} SAST</span>
        </div>
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-4)' }}>v2.14</span>
      </div>
      <div style={{ fontSize: 11, color: 'var(--fg-3)', marginBottom: 4 }}>Queue throughput · last 12h</div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 56, marginBottom: 14 }}>
        {bars.map((h, i) => (
          <div key={i} style={{
            flex: 1, height: h + '%',
            background: i === bars.length - 1 ? 'var(--green)' : 'var(--bar-muted)',
            borderRadius: '3px 3px 0 0'
          }} />
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
        {[
          { k: 'Actions / hr', v: '1,284', d: '+18%' },
          { k: 'Success',      v: '99.4%', d: '+0.3' },
          { k: 'P95 latency',  v: '620ms', d: '-12%' },
        ].map(m => (
          <div key={m.k} style={{ background: 'var(--bg-2)', borderRadius: 10, padding: '10px 12px' }}>
            <div className="mono" style={{ fontSize: 9, color: 'var(--fg-4)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{m.k}</div>
            <div style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>{m.v}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--green)' }}>{m.d}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// Spatial depth "card" with abstract AI planes — used for a system case study
const SpatialPlanes = ({ hue = '#A2BB55', label = 'SPATIAL COMPUTE' }) => {
  return (
    <div style={{ position: 'relative', width: '100%', aspectRatio: '16/10', background: 'var(--bg-1)', borderRadius: 14, overflow: 'hidden', border: '1px solid var(--line)' }}>
      <div className="bg-grid" style={{ position: 'absolute', inset: 0, opacity: 0.5 }} />
      {[0,1,2,3].map(i => (
        <div key={i} style={{
          position: 'absolute',
          inset: `${8 + i*6}% ${8 + i*8}%`,
          border: `1px solid var(--hairline)`,
          opacity: 0.4 + i * 0.2,
          borderRadius: 12,
          background: i === 3 ? `linear-gradient(135deg, ${hue}22, transparent 60%)` : 'transparent',
          transform: `perspective(900px) rotateX(${18 - i*2}deg) rotateY(${-8 + i*2}deg) translateZ(${i*8}px)`,
          boxShadow: i === 3 ? `inset 0 0 0 1px ${hue}44` : 'none'
        }}/>
      ))}
      <div style={{ position: 'absolute', right: 14, bottom: 12 }}>
        <span className="mono" style={{ fontSize: 10, color: 'var(--fg-3)', letterSpacing: '0.18em' }}>{label}</span>
      </div>
    </div>
  );
};

// Small sparkline
const Spark = ({ values, color = '#A2BB55' }) => {
  const max = Math.max(...values), min = Math.min(...values);
  const range = max - min || 1;
  const W = 120, H = 32;
  const pts = values.map((v, i) => {
    const x = (i / (values.length - 1)) * W;
    const y = H - ((v - min) / range) * H;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`}>
      <polyline fill="none" stroke={color} strokeWidth="1.5" points={pts} />
      <circle cx={W} cy={H - ((values[values.length-1] - min) / range) * H} r="2.5" fill={color} />
    </svg>
  );
};

Object.assign(window, { SystemsMesh, MiniDashboard, SpatialPlanes, Spark });
