// Persistent "live system" backdrop visible behind every section.
// Parallax scroll, animated flow lines, drifting event chips (tickets,
// incidents, logins, trends, releases). Position fixed, z-index 0.
//
// EDIT: tune density, speed, and event chips below.

function Backdrop() {
  const ref = React.useRef(null);

  // Parallax: backdrop scrolls SLOWER than content (translateY negative)
  React.useEffect(() => {
    let raf = 0;
    function update() {
      if (ref.current) {
        // Backdrop moves at 0.35x scroll speed (in opposite direction visually,
        // since we want to see "more system" as you scroll down)
        const y = window.scrollY;
        ref.current.style.transform = `translate3d(0, ${y * -0.35}px, 0)`;
      }
      raf = 0;
    }
    function onScroll() {
      if (!raf) raf = requestAnimationFrame(update);
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    update();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);

  return (
    <div className="so-backdrop" aria-hidden="true">
      <div className="so-backdrop-layer" ref={ref}>
        {/* base grid that scrolls with parallax */}
        <div className="so-backdrop-grid"></div>

        {/* The big n8n-style system canvas. Stretches vertically for several screens. */}
        <svg className="so-backdrop-flow" viewBox="0 0 1920 3600" preserveAspectRatio="xMidYMin meet">
          <defs>
            <pattern id="bg-grid" width="48" height="48" patternUnits="userSpaceOnUse">
              <path d="M 48 0 L 0 0 0 48" fill="none" stroke="var(--grid-line)" strokeWidth="1"/>
            </pattern>
            <radialGradient id="bg-fade" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor="rgba(0,0,0,1)"/>
              <stop offset="100%" stopColor="rgba(0,0,0,0)"/>
            </radialGradient>
          </defs>

          {/* ============ FLOW CHAIN A — top, intake pipeline ============ */}
          <g className="chain" style={{ animationDelay: '0s' }}>
            <FlowChain
              y={420}
              nodes={[
                { label: 'webhook',    x: 100 },
                { label: 'normalize',  x: 320 },
                { label: 'classify',   x: 540 },
                { label: 'enrich',     x: 760 },
                { label: 'route',      x: 980 },
                { label: 'agent.rag',  x: 1200, accent: true },
                { label: 'respond',    x: 1420 },
                { label: 'log',        x: 1640 },
              ]}
            />
            <FlowLabel x={100} y={380} text="intake-triage · n8n#wf_021"/>
          </g>

          {/* ============ FLOW CHAIN B — billing recon ============ */}
          <g className="chain" style={{ animationDelay: '0.6s' }}>
            <FlowChain
              y={1020}
              nodes={[
                { label: 'cron',       x: 180 },
                { label: 'stripe.api', x: 380 },
                { label: 'quickbooks', x: 580 },
                { label: 'diff',       x: 780 },
                { label: 'reconcile',  x: 980, accent: true },
                { label: 'slack',      x: 1180 },
                { label: 'archive',    x: 1380 },
              ]}
            />
            <FlowLabel x={180} y={980} text="billing-recon · n8n#wf_044"/>
          </g>

          {/* ============ FLOW CHAIN C — onboarding bot ============ */}
          <g className="chain" style={{ animationDelay: '1.2s' }}>
            <FlowChain
              y={1620}
              nodes={[
                { label: 'form',         x: 220 },
                { label: 'validate',     x: 420 },
                { label: 'crm.create',   x: 620 },
                { label: 'segment',      x: 820 },
                { label: 'agent.greet',  x: 1020, accent: true },
                { label: 'email',        x: 1220 },
                { label: 'calendar',     x: 1420 },
                { label: 'notion.doc',   x: 1620 },
              ]}
            />
            <FlowLabel x={220} y={1580} text="onboarding-bot · n8n#wf_102"/>
          </g>

          {/* ============ FLOW CHAIN D — anomaly watcher ============ */}
          <g className="chain" style={{ animationDelay: '1.8s' }}>
            <FlowChain
              y={2220}
              nodes={[
                { label: 'prometheus',   x: 120 },
                { label: 'detect',       x: 320, accent: true },
                { label: 'classify',     x: 520 },
                { label: 'pagerduty',    x: 720 },
                { label: 'investigate',  x: 920, accent: true },
                { label: 'propose-fix',  x: 1120 },
                { label: 'audit',        x: 1320 },
              ]}
            />
            <FlowLabel x={120} y={2180} text="anomaly-watcher · n8n#wf_077"/>
          </g>

          {/* ============ FLOW CHAIN E — RAG agent loop ============ */}
          <g className="chain" style={{ animationDelay: '2.4s' }}>
            <FlowChain
              y={2820}
              nodes={[
                { label: 'query',        x: 280 },
                { label: 'embed',        x: 480 },
                { label: 'retrieve',     x: 680, accent: true },
                { label: 'rerank',       x: 880 },
                { label: 'llm.reason',   x: 1080, accent: true },
                { label: 'act',          x: 1280 },
                { label: 'feedback',     x: 1480 },
              ]}
            />
            <FlowLabel x={280} y={2780} text="rag-agent · n8n#wf_118"/>
          </g>

          {/* Cross-chain connectors — vertical bridges showing the system is one */}
          <g stroke="var(--signal-line)" strokeWidth="1" fill="none" strokeDasharray="2 6" opacity="0.5">
            <path d="M 1640 460 Q 1700 700 1180 1060"/>
            <path d="M 1180 1060 Q 1240 1340 1020 1660"/>
            <path d="M 1020 1660 Q 800 1900 320 2260"/>
            <path d="M 1320 2260 Q 1400 2540 1080 2860"/>
          </g>
        </svg>

        {/* ============ EVENT CHIPS — drifting tickets, incidents, logins ============ */}
        <div className="so-backdrop-events">
          <EventChip kind="ticket"   x="6%"   y="280px"  text="TKT-1042 · escalated"      pill="warn"/>
          <EventChip kind="login"    x="82%"  y="540px"  text="login · ops@acme.com"      pill="ok"/>
          <EventChip kind="trend"    x="74%"  y="820px"  text="P95 · 218ms"               trend="down" pill="ok"/>
          <EventChip kind="release"  x="4%"   y="1100px" text="release · v3.4.1"          pill="ok"/>
          <EventChip kind="incident" x="84%"  y="1380px" text="incident · stripe-webhook" pill="danger"/>
          <EventChip kind="trend"    x="6%"   y="1700px" text="SLA · 99.94%"              trend="up" pill="ok"/>
          <EventChip kind="ticket"   x="78%"  y="1980px" text="TKT-1051 · routed"         pill="info"/>
          <EventChip kind="login"    x="8%"   y="2280px" text="login · m.k. · admin"      pill="ok"/>
          <EventChip kind="incident" x="78%"  y="2580px" text="drift · airtable-sync"     pill="warn"/>
          <EventChip kind="trend"    x="6%"   y="2880px" text="cost · −$2.10/h"           trend="down" pill="ok"/>
          <EventChip kind="ticket"   x="80%"  y="3160px" text="TKT-1058 · auto-resolved"  pill="ok"/>
        </div>
      </div>

      {/* Static vignette — does NOT parallax, keeps edges dark */}
      <div className="so-backdrop-vignette"></div>
    </div>
  );
}

/* ---- helpers ---- */
function FlowChain({ y, nodes }) {
  return (
    <g>
      {/* connecting line */}
      <line
        x1={nodes[0].x + 24}
        y1={y}
        x2={nodes[nodes.length - 1].x - 24}
        y2={y}
        stroke="var(--signal)"
        strokeWidth="1.5"
        strokeDasharray="3 5"
        className="so-dash-bg"
        opacity="0.5"
      />
      {/* nodes */}
      {nodes.map((n, i) => (
        <g key={i}>
          <rect
            x={n.x - 38}
            y={y - 16}
            width="76"
            height="32"
            rx="5"
            fill="var(--surface)"
            stroke={n.accent ? 'var(--signal-line)' : 'var(--border-strong)'}
            strokeWidth="1"
          />
          <circle
            cx={n.x - 26}
            cy={y}
            r="2.5"
            fill={n.accent ? 'var(--signal)' : 'var(--ink-muted)'}
          />
          <text
            x={n.x + 4}
            y={y + 4}
            fontFamily="JetBrains Mono, monospace"
            fontSize="11"
            fill="var(--ink-muted)"
            textAnchor="middle"
          >
            {n.label}
          </text>
        </g>
      ))}
    </g>
  );
}

function FlowLabel({ x, y, text }) {
  return (
    <text
      x={x}
      y={y}
      fontFamily="JetBrains Mono, monospace"
      fontSize="10"
      fill="var(--ink-dim)"
      letterSpacing="1"
    >
      {text.toUpperCase()}
    </text>
  );
}

function EventChip({ kind, x, y, text, pill = 'ok', trend }) {
  return (
    <div className={'so-evt so-evt--' + kind} style={{ left: x, top: y }}>
      <span className={'so-evt-pill so-evt-pill--' + pill}>
        {pill === 'ok' && <span className="dot"></span>}
      </span>
      <span className="so-evt-text">{text}</span>
      {trend && (
        <span className={'so-evt-trend so-evt-trend--' + trend}>
          {trend === 'up' ? '↗' : '↘'}
        </span>
      )}
    </div>
  );
}

Object.assign(window, { Backdrop });
