/* ── BRAINS RELAY ─────────────────────────────────────────────
   SA-only control panel. Keeps the platform synced with external
   sources of truth (compliance bodies, WP core, plugin vendors,
   scanner engines, search engines, APIs). Two policy modes per
   feed — "Auto-apply" (safe changes) or "Queue for SA review".

   Mounted inside Brains → Relay tab. Customer-facing output is a
   single subtle footer note in Scanner ("Scan engine v4.10 · 4d ago").
   Nothing else leaks to lower-role UIs by design. */
function BrainsRelay() {
  const { useState } = React;
  const Icon = window.Icon; // Babel scope isolation — alias globals
  const [policyFilter, setPolicyFilter] = useState('all'); // all|auto|queued
  const [openFeed, setOpenFeed] = useState(null);

  // ── 7 feed categories ──────────────────────────────────────
  const FEEDS = [
    {
      id:'compliance', cat:'Compliance', icon:'shield', color:'var(--red)',
      name:'ADA / WCAG / 508',
      sources:['w3.org/WAI/standards-guidelines/wcag', 'ada.gov', 'section508.gov', 'access-board.gov'],
      checkEvery:'weekly', lastCheck:'2d ago', nextCheck:'in 5d', status:'ok',
      policy:'queued', delta:0, version:(window.WPSB && window.WPSB.CONSTANTS && window.WPSB.CONSTANTS.WCAG.DISPLAY) || 'WCAG 2.1 AA',
      affects:['Scanner rules','ADA narrative tokens','VPAT template','Compliance Statement'],
      desc:'Tracks WCAG updates, DOJ rulemakings, state-level digital accessibility laws. Changes here drive Scanner rule updates and proposal narrative language.',
    },
    {
      id:'wpcore', cat:'WordPress Core', icon:'globe', color:'#21759b',
      name:'WordPress · Core',
      sources:['wordpress.org/download/releases','make.wordpress.org/core','core.trac.wordpress.org'],
      checkEvery:'daily', lastCheck:'4h ago', nextCheck:'in 20h', status:'ok',
      policy:'auto', delta:1, version:'6.7.2',
      affects:['Plugin compat matrix','Hosting plan recommendations','Minimum PHP enforcement'],
      desc:'Release cadence, deprecations, security patches, minimum PHP/MySQL requirements. Drives plugin compat warnings.',
    },
    {
      id:'wpsbplugin', cat:'WPSB Plugin', icon:'plugin', color:'var(--beam)',
      name:'WP Site Beam · Plugin',
      sources:['internal: github.com/wpsitebeam/plugin','internal: release channel'],
      checkEvery:'on-push', lastCheck:'17m ago', nextCheck:'continuous', status:'ok',
      policy:'auto', delta:0, version:'1.4.3',
      affects:['Customer download page','Changelog','Scanner data pipeline','Push-to-WP writes'],
      desc:'Our own plugin releases. Automatic propagation to every customer-facing download link + changelog and in-app update nudges.',
    },
    {
      id:'scanner', cat:'Scanner Engine', icon:'scanner', color:'var(--orange)',
      name:'axe-core · Lighthouse · Pa11y',
      sources:['github.com/dequelabs/axe-core','github.com/GoogleChrome/lighthouse','pa11y.org'],
      checkEvery:'weekly', lastCheck:'1d ago', nextCheck:'in 6d', status:'warn',
      policy:'queued', delta:2, version:'axe 4.10.3 · LH 12.3 · Pa11y 8.0',
      affects:['Scanner scoring','Customer evidence appendix','Scan engine footer note'],
      desc:'The actual scan libraries. Version bumps can change scoring — always queued for SA review so we can diff findings before customers see them.',
    },
    {
      id:'techstack', cat:'Tech Stack', icon:'stack', color:'var(--purple)',
      name:'Elementor · Ally · Gravity · ACF · JetEngine · CrocoBlock · FileBird',
      sources:['elementor.com/changelog','alyant.com','gravityforms.com','advancedcustomfields.com','crocoblock.com/changelog','wpfilebird.com'],
      checkEvery:'daily', lastCheck:'8h ago', nextCheck:'in 16h', status:'warn',
      policy:'queued', delta:3, version:'mixed — see detail',
      affects:['Kit Builder compat','Site Builder templates','Plugin recommendations','Hosting requirements'],
      desc:'Our recommended plugin stack. New releases, security advisories, breaking changes. Drives Kit Builder theme generation + Site Builder scaffolding.',
    },
    {
      id:'searchseo', cat:'Search / SEO', icon:'search', color:'var(--green)',
      name:'Google · Bing · Schema.org · Core Web Vitals',
      sources:['developers.google.com/search','schema.org','web.dev/vitals','bing.com/webmasters'],
      checkEvery:'weekly', lastCheck:'3d ago', nextCheck:'in 4d', status:'ok',
      policy:'queued', delta:1, version:'CWV 2026.1',
      affects:['Content SEO scoring','SEO recommendations','Lighthouse integration'],
      desc:'Algorithm updates, schema additions, Core Web Vitals threshold changes. Flag so Content SEO scoring stays honest.',
    },
    {
      id:'thirdparty', cat:'Third-party APIs', icon:'link', color:'var(--warn)',
      name:'GHL · Stripe · Plaid · Woo · DocuSign',
      sources:['developers.gohighlevel.com','stripe.com/docs/changelog','plaid.com/docs/changelog','developer.woocommerce.com','developers.docusign.com'],
      checkEvery:'daily', lastCheck:'6h ago', nextCheck:'in 18h', status:'ok',
      policy:'queued', delta:0, version:'—',
      affects:['Integrations panel','Payment flows','Proposal e-sign','CRM push'],
      desc:'API versioning from integrated services. Breaking changes here quietly break features — we alert before a deprecation lands.',
    },
  ];

  // ── Relay log (chronological, newest first) ────────────────
  const LOG = [
    { id:1, feed:'WordPress Core', ts:'4h ago',  kind:'update', severity:'info',
      msg:'WordPress 6.7.2 released · security fix (CVE-2026-12483) in block editor',
      action:'Auto-propagated to plugin compat matrix · 1,428 customer sites flagged for update nudge',
      policy:'auto-applied' },
    { id:2, feed:'axe-core',       ts:'1d ago',  kind:'update', severity:'warn',
      msg:'axe-core 4.10.3 → 4.11.0 · new rule: nested-interactive (A level)',
      action:'Queued · SA review required before scoring update rolls to customers',
      policy:'queued' },
    { id:3, feed:'Elementor',      ts:'1d ago',  kind:'security', severity:'high',
      msg:'Elementor Pro 3.26.1 · XSS patch · exploit active in the wild',
      action:'Push urgent update notice to all sites running < 3.26.1 (412 affected)',
      policy:'queued' },
    { id:4, feed:'WPSB Plugin',    ts:'17m ago', kind:'release', severity:'info',
      msg:'WPSB 1.4.3 shipped · adds File Map push-back + File Library dedup',
      action:'Auto-updated download URL, changelog, and in-app update banner',
      policy:'auto-applied' },
    { id:5, feed:'WCAG',           ts:'2d ago',  kind:'guidance', severity:'info',
      msg:'W3C published working draft of WCAG 3.0 (Silver) · not yet normative',
      action:'Queued · documentation team reviews, no scanner rule changes',
      policy:'queued' },
    { id:6, feed:'CrocoBlock',     ts:'8h ago',  kind:'update', severity:'info',
      msg:'JetEngine 3.7.0 · new REST relation endpoint · backward compatible',
      action:'Updated Kit Builder template manifest · no user action',
      policy:'auto-applied' },
    { id:7, feed:'Google Search',  ts:'3d ago',  kind:'guidance', severity:'warn',
      msg:'Core Web Vitals INP threshold tightened · 200ms now "good" (was 250ms)',
      action:'Queued · Content SEO scoring + Lighthouse gates need re-tuning',
      policy:'queued' },
    { id:8, feed:'Stripe',         ts:'6h ago',  kind:'deprecation', severity:'warn',
      msg:'Stripe API 2024-04-10 sunset in 90d · our Billing calls affected',
      action:'Queued · Dev team upgrade path documented in Docs & Wiki',
      policy:'queued' },
  ];

  // ── Version matrix (us vs each dep) ────────────────────────
  const MATRIX = [
    { dep:'WordPress Core',        ours:'6.7.1',    latest:'6.7.2',   status:'behind', lag:'2d' },
    { dep:'axe-core',              ours:'4.10.3',   latest:'4.11.0',  status:'review', lag:'1d' },
    { dep:'Lighthouse',            ours:'12.3.0',   latest:'12.3.0',  status:'current', lag:'—' },
    { dep:'Elementor Pro',         ours:'3.26.0',   latest:'3.26.1',  status:'behind', lag:'1d' },
    { dep:'Gravity Forms',         ours:'2.8.14',   latest:'2.8.14',  status:'current', lag:'—' },
    { dep:'ACF Pro',               ours:'6.4.2',    latest:'6.4.2',   status:'current', lag:'—' },
    { dep:'JetEngine',             ours:'3.6.4',    latest:'3.7.0',   status:'review', lag:'8h' },
    { dep:'CrocoBlock Full',       ours:'2.14.0',   latest:'2.14.0',  status:'current', lag:'—' },
    { dep:'Ally Accessibility',    ours:'5.2.1',    latest:'5.2.1',   status:'current', lag:'—' },
    { dep:'FileBird',              ours:'6.3.2',    latest:'6.3.2',   status:'current', lag:'—' },
    { dep:'WPSB Plugin',           ours:'1.4.3',    latest:'1.4.3',   status:'current', lag:'—' },
    { dep:'Stripe API',            ours:'2024-04-10', latest:'2026-02-01', status:'deprecation', lag:'90d' },
  ];

  const statusTone = (s) => ({
    current:'ok', behind:'warn', review:'beam', deprecation:'bad',
  })[s] || '';
  const statusLabel = (s) => ({
    current:'CURRENT', behind:'BEHIND', review:'SA REVIEW', deprecation:'DEPRECATING',
  })[s] || s.toUpperCase();

  // ── Count metrics ──────────────────────────────────────────
  const totalDelta = FEEDS.reduce((a,f)=> a + f.delta, 0);
  const queuedFeeds = FEEDS.filter(f => f.policy === 'queued').length;
  const autoFeeds   = FEEDS.filter(f => f.policy === 'auto').length;
  const matrixBehind = MATRIX.filter(m => m.status !== 'current').length;

  return (
    <div>
      {/* ── Summary strip ─────────────────────────────────────── */}
      <div className="box info" style={{ marginBottom:14 }}>
        <Icon name="shield" size={16}/>
        <div>
          <strong>SA-only control plane.</strong> Keeps our platform synced with external sources of truth — compliance bodies, WP core, plugin vendors, scanner engines. Customer-facing surfaces receive a single subtle footer note with the current scanner engine version; no other relay data leaks downstream.
        </div>
      </div>

      <div className="grid grid-4" style={{ marginBottom:16 }}>
        <div className="stat">
          <div className="stat-lbl">Feeds monitored</div>
          <div className="stat-val">{FEEDS.length}</div>
          <div className="mono" style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:4 }}>across 7 categories</div>
        </div>
        <div className="stat">
          <div className="stat-lbl">Pending deltas</div>
          <div className="stat-val" style={{ color: totalDelta > 0 ? 'var(--warn)' : 'var(--green)' }}>{totalDelta}</div>
          <div className="mono" style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:4 }}>changes detected, not yet applied</div>
        </div>
        <div className="stat">
          <div className="stat-lbl">Auto vs queued</div>
          <div className="stat-val">{autoFeeds}<span style={{ fontSize:'.7rem', color:'var(--dim)', fontWeight:400 }}> / {queuedFeeds} queued</span></div>
          <div className="mono" style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:4 }}>policy mix</div>
        </div>
        <div className="stat">
          <div className="stat-lbl">Stack versions</div>
          <div className="stat-val" style={{ color: matrixBehind > 0 ? 'var(--warn)' : 'var(--green)' }}>{MATRIX.length - matrixBehind}/{MATRIX.length}</div>
          <div className="mono" style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:4 }}>current</div>
        </div>
      </div>

      {/* ── Feed cards ────────────────────────────────────────── */}
      <div className="card" style={{ marginBottom:16 }}>
        <div className="card-head">
          <h2 className="card-title"><Icon name="radio" size={14}/>&nbsp;Monitored feeds</h2>
          <div style={{ display:'flex', gap:6 }}>
            <div className="tw-seg" role="tablist" style={{ display:'inline-flex' }}>
              <button role="tab" aria-selected={policyFilter==='all'}    className={policyFilter==='all'?'active':''}    onClick={()=>setPolicyFilter('all')}>All</button>
              <button role="tab" aria-selected={policyFilter==='auto'}   className={policyFilter==='auto'?'active':''}   onClick={()=>setPolicyFilter('auto')}>Auto</button>
              <button role="tab" aria-selected={policyFilter==='queued'} className={policyFilter==='queued'?'active':''} onClick={()=>setPolicyFilter('queued')}>Queued</button>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Forcing refresh on all feeds…', 'beam')}>
              <Icon name="refresh" size={12}/>Force refresh all
            </button>
          </div>
        </div>
        <div className="card-body" style={{ padding:0 }}>
          <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(340px, 1fr))', gap:1, background:'var(--border)' }}>
            {FEEDS.filter(f => policyFilter === 'all' || f.policy === policyFilter).map(f => (
              <div key={f.id} style={{ background:'var(--surface)', padding:14, cursor:'pointer',
                                        borderTop: openFeed === f.id ? `2px solid ${f.color}` : 'none' }}
                   onClick={() => setOpenFeed(openFeed === f.id ? null : f.id)}>
                <div style={{ display:'flex', alignItems:'flex-start', gap:10 }}>
                  <div style={{ width:32, height:32, borderRadius:8, background: f.color+'22', color: f.color,
                                display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                    <Icon name={f.icon} size={15}/>
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:3 }}>
                      <span style={{ fontSize:'.62rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700 }}>{f.cat}</span>
                      {f.delta > 0 && (
                        <span style={{ fontSize:'.6rem', padding:'2px 6px', borderRadius:3, background:'var(--warn-dim)', color:'var(--warn)', fontWeight:700, fontFamily:'var(--font-mono)' }}>
                          +{f.delta} Δ
                        </span>
                      )}
                      <span style={{ flex:1 }}/>
                      <span className={`tag ${f.policy === 'auto' ? 'ok' : 'warn'}`} style={{ fontSize:'.58rem' }}>
                        {f.policy === 'auto' ? 'AUTO' : 'QUEUED'}
                      </span>
                    </div>
                    <div style={{ fontSize:'.8rem', fontWeight:600, marginBottom:4, overflow:'hidden', textOverflow:'ellipsis' }} title={f.name}>{f.name}</div>
                    <div style={{ fontSize:'.7rem', color:'var(--dim)', fontFamily:'var(--font-mono)', display:'flex', gap:10 }}>
                      <span>✓ {f.lastCheck}</span>
                      <span>→ {f.nextCheck}</span>
                    </div>
                    <div style={{ fontSize:'.72rem', color:'var(--text)', marginTop:6, fontFamily:'var(--font-mono)' }}>
                      <span style={{ color:'var(--dim)' }}>version </span>{f.version}
                    </div>
                  </div>
                </div>

                {openFeed === f.id && (
                  <div style={{ marginTop:12, paddingTop:12, borderTop:'1px dashed var(--border)' }}>
                    <div style={{ fontSize:'.74rem', color:'var(--muted)', lineHeight:1.5, marginBottom:10 }}>
                      {f.desc}
                    </div>
                    <div style={{ fontSize:'.64rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:4 }}>Sources</div>
                    <div style={{ fontSize:'.7rem', fontFamily:'var(--font-mono)', color:'var(--beam)', marginBottom:10, display:'flex', flexDirection:'column', gap:2 }}>
                      {f.sources.map(s => <span key={s}>· {s}</span>)}
                    </div>
                    <div style={{ fontSize:'.64rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:4 }}>Affects</div>
                    <div style={{ display:'flex', flexWrap:'wrap', gap:4, marginBottom:12 }}>
                      {f.affects.map(a => <span key={a} className="tag" style={{ fontSize:'.6rem' }}>{a}</span>)}
                    </div>
                    <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                      <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); window.wpsbToast?.(`Re-checking ${f.name}…`, 'beam'); }}>
                        <Icon name="refresh" size={11}/>Re-check now
                      </button>
                      <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); window.wpsbToast?.(`Policy flipped to ${f.policy === 'auto' ? 'queued' : 'auto'}`, 'ok'); }}>
                        <Icon name="settings" size={11}/>Policy: {f.policy === 'auto' ? 'Auto-apply' : 'Queue for review'}
                      </button>
                      <button className="btn btn-ghost btn-sm" onClick={(e) => { e.stopPropagation(); window.wpsbToast?.('Propagation map opened', 'info'); }}>
                        <Icon name="share" size={11}/>Propagation map
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Two-column: Relay log + Version matrix ────────────── */}
      <div className="grid" style={{ gridTemplateColumns:'1.3fr 1fr', gap:14, marginBottom:16 }}>
        {/* Relay log */}
        <div className="card">
          <div className="card-head">
            <h2 className="card-title"><Icon name="activity" size={14}/>&nbsp;Relay log</h2>
            <div style={{ display:'flex', gap:6 }}>
              <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Exported log as JSONL', 'ok')}>
                <Icon name="download" size={12}/>Export
              </button>
              <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Piped to sub-brain: Wiki + Docs', 'ok')}>
                <Icon name="brain" size={12}/>Pipe to sub-brains
              </button>
            </div>
          </div>
          <div className="card-body" style={{ padding:0, maxHeight:460, overflowY:'auto' }}>
            {LOG.map(e => (
              <div key={e.id} style={{ padding:'12px 16px', borderBottom:'1px solid var(--border)', display:'flex', gap:12 }}>
                <div style={{ flexShrink:0, width:8, height:8, borderRadius:'50%', marginTop:6,
                              background: e.severity === 'high' ? 'var(--red)' : e.severity === 'warn' ? 'var(--warn)' : 'var(--beam)' }}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:3 }}>
                    <span style={{ fontSize:'.68rem', fontWeight:700, color:'var(--text)' }}>{e.feed}</span>
                    <span className="tag" style={{ fontSize:'.58rem',
                           background: e.kind === 'security' ? 'rgba(220,38,38,.12)' : e.kind === 'deprecation' ? 'var(--warn-dim)' : 'var(--surface-2)',
                           color:     e.kind === 'security' ? 'var(--red)' : e.kind === 'deprecation' ? 'var(--warn)' : 'var(--muted)',
                           border:    e.kind === 'security' ? '1px solid rgba(220,38,38,.3)' : e.kind === 'deprecation' ? '1px solid var(--warn-dim)' : '1px solid var(--border)' }}>
                      {e.kind.toUpperCase()}
                    </span>
                    <span style={{ flex:1 }}/>
                    <span className="mono" style={{ fontSize:'.62rem', color:'var(--dim)' }}>{e.ts}</span>
                  </div>
                  <div style={{ fontSize:'.78rem', color:'var(--text)', marginBottom:4 }}>{e.msg}</div>
                  <div style={{ fontSize:'.7rem', color:'var(--muted)', fontFamily:'var(--font-mono)', display:'flex', gap:6, alignItems:'center' }}>
                    <span style={{ color: e.policy === 'auto-applied' ? 'var(--green)' : 'var(--warn)' }}>
                      {e.policy === 'auto-applied' ? '● auto-applied' : '◐ queued'}
                    </span>
                    <span style={{ color:'var(--dim)' }}>·</span>
                    <span>{e.action}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Version matrix */}
        <div className="card">
          <div className="card-head">
            <h2 className="card-title"><Icon name="stack" size={14}/>&nbsp;Stack version matrix</h2>
          </div>
          <div className="card-body" style={{ padding:0 }}>
            <table className="table" style={{ fontSize:'.74rem' }}>
              <thead>
                <tr>
                  <th scope="col">Dependency</th>
                  <th scope="col" style={{ textAlign:'right' }}>Ours</th>
                  <th scope="col" style={{ textAlign:'right' }}>Latest</th>
                  <th scope="col">Status</th>
                </tr>
              </thead>
              <tbody>
                {MATRIX.map(m => (
                  <tr key={m.dep}>
                    <td style={{ fontWeight:500, fontSize:'.72rem' }}>{m.dep}</td>
                    <td className="mono" style={{ textAlign:'right', fontSize:'.68rem', color: m.status === 'current' ? 'var(--green)' : 'var(--warn)' }}>{m.ours}</td>
                    <td className="mono" style={{ textAlign:'right', fontSize:'.68rem', color:'var(--muted)' }}>{m.latest}</td>
                    <td>
                      <span className={`tag ${statusTone(m.status)}`} style={{ fontSize:'.56rem' }}>
                        {statusLabel(m.status)}
                      </span>
                      {m.lag !== '—' && <span style={{ fontSize:'.62rem', color:'var(--dim)', marginLeft:4, fontFamily:'var(--font-mono)' }}>· {m.lag}</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* ── Propagation map (visual) ──────────────────────────── */}
      <div className="card" style={{ marginBottom:16 }}>
        <div className="card-head">
          <h2 className="card-title"><Icon name="share" size={14}/>&nbsp;Propagation map</h2>
          <span className="tag sa">SA ONLY</span>
        </div>
        <div className="card-body">
          <div style={{ fontSize:'.74rem', color:'var(--muted)', marginBottom:14 }}>
            Which customer-facing features each relay feed affects. A change at the left ripples to every feature on the right.
          </div>
          <div style={{ position:'relative', display:'grid', gridTemplateColumns:'220px 1fr 260px', gap:0, alignItems:'stretch', minHeight:380, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, overflow:'hidden' }}>
            {/* Left: feeds */}
            <div style={{ padding:'14px 0', borderRight:'1px solid var(--border)' }}>
              <div style={{ padding:'0 14px 8px', fontSize:'.6rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700 }}>Feeds</div>
              {FEEDS.map((f, i) => (
                <div key={f.id} style={{ padding:'9px 14px', display:'flex', alignItems:'center', gap:8, borderLeft:`3px solid ${f.color}`, marginBottom:3, background:'var(--surface)', fontSize:'.72rem', fontWeight:500 }}>
                  <Icon name={f.icon} size={12}/>
                  <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{f.cat}</span>
                </div>
              ))}
            </div>

            {/* Middle: SVG connectors */}
            <svg viewBox="0 0 200 420" preserveAspectRatio="none" style={{ width:'100%', height:'100%' }}>
              {FEEDS.map((f, i) => {
                const y1 = 24 + i * 40;
                const targets = [0, 1, 2, 3, 4, 5].filter((_, ti) => (i + ti) % 3 !== 0);
                return targets.map((ti, ii) => {
                  const y2 = 24 + ti * 50;
                  return (
                    <path key={`${f.id}-${ti}`}
                          d={`M 0 ${y1} C 100 ${y1}, 100 ${y2}, 200 ${y2}`}
                          stroke={f.color} strokeWidth="1" fill="none" opacity="0.35"/>
                  );
                });
              })}
              {FEEDS.map((f, i) => (
                <circle key={f.id + '-dot'} cx="0" cy={24 + i * 40} r="3" fill={f.color}/>
              ))}
              {['Scanner','Proposals','Kit Builder','Site Builder','Content SEO','Integrations','Footer'].map((_, i) => (
                <circle key={i} cx="200" cy={24 + i * 50} r="3" fill="var(--beam)"/>
              ))}
            </svg>

            {/* Right: customer features */}
            <div style={{ padding:'14px 0', borderLeft:'1px solid var(--border)' }}>
              <div style={{ padding:'0 14px 8px', fontSize:'.6rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700 }}>Customer features</div>
              {[
                { name:'Scanner',        sub:'scoring · evidence · engine footer' },
                { name:'Proposals',      sub:'ADA narrative · legal framework' },
                { name:'Kit Builder',    sub:'template compat · stack config' },
                { name:'Site Builder',   sub:'scaffolds · plugin recos' },
                { name:'Content SEO',    sub:'CWV thresholds · schema' },
                { name:'Integrations',   sub:'Stripe/GHL/Plaid versions' },
                { name:'Footer notices', sub:'engine version · plugin version' },
              ].map((t, i) => (
                <div key={t.name} style={{ padding:'10px 14px', marginBottom:3, background:'var(--surface)', borderRight:'3px solid var(--beam)' }}>
                  <div style={{ fontSize:'.74rem', fontWeight:600 }}>{t.name}</div>
                  <div style={{ fontSize:'.64rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>{t.sub}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── Sub-brain routing ─────────────────────────────────── */}
      <div className="card" style={{ marginBottom:16 }}>
        <div className="card-head">
          <h2 className="card-title"><Icon name="brain" size={14}/>&nbsp;Sub-brain routing</h2>
          <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Relay deltas automatically spawn entries in downstream sub-brains</div>
        </div>
        <div className="card-body">
          <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:10 }}>
            {[
              { name:'Docs & Wiki',     icon:'wiki',    color:'var(--beam)',    queue:'+7 pending', desc:'Auto-drafts changelog summary + developer notes from relay events.' },
              { name:'Support Brain',   icon:'support', color:'var(--purple)',        queue:'+3 pending', desc:'Preps canned replies for likely customer tickets about each change.' },
              { name:'Estimator Brain', icon:'calc',    color:'var(--orange)',  queue:'+1 pending', desc:'Updates proposal copy templates when compliance framework shifts.' },
              { name:'Scanner Brain',   icon:'scanner', color:'var(--red)',     queue:'+2 pending', desc:'Pulls new axe rules into scoring dictionary; queues SA review.' },
              { name:'Brand Scanner',   icon:'brand',   color:'var(--green)',   queue:'idle',       desc:'No inputs from relay today.' },
            ].map(b => (
              <div key={b.name} style={{ padding:12, borderRadius:8, background:'var(--surface-2)', border:'1px solid var(--border)' }}>
                <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
                  <div style={{ width:26, height:26, borderRadius:6, background: b.color+'22', color: b.color, display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon name={b.icon} size={12}/>
                  </div>
                  <div style={{ fontSize:'.78rem', fontWeight:600 }}>{b.name}</div>
                  <span style={{ flex:1 }}/>
                  <span className="mono" style={{ fontSize:'.6rem', color: b.queue === 'idle' ? 'var(--dim)' : 'var(--warn)' }}>{b.queue}</span>
                </div>
                <div style={{ fontSize:'.7rem', color:'var(--muted)', lineHeight:1.45 }}>{b.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Security & isolation notice */}
      <div className="box warn">
        <Icon name="shield" size={16}/>
        <div>
          <strong>Isolation guarantees:</strong> Relay feeds, logs, policies, and sub-brain routing are SA-role only. Customer, Partner, Marketing, Dev, and Admin roles have no read/write access. The single customer-visible effect is the engine-version footer note on Scanner reports — everything else is locked down for IP/security/privacy protection.
        </div>
      </div>
    </div>
  );
}

window.BrainsRelay = BrainsRelay;
