// security.jsx — Security overview. Self-contained Nav + Footer + BookCallModal mount.
// Visual: two-column shell. Left rail = sticky numbered TOC. Right = content.
const { useState, useEffect, useRef } = React;

// ── Logo ──────────────────────────────────────────────────────────
function LegalLogoMark({ size = 26 }) {
  return (
    <img
      src="/img/echo-logo.jpeg"
      alt="Echo"
      width={size}
      height={size}
      style={{ display: 'block', borderRadius: 4, objectFit: 'contain' }}
    />
  );
}

// ── Verticals dropdown ────────────────────────────────────────────
function LegalVerticalsDropdown({ onPhoto }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const closeTimer = useRef(null);
  const hoverOpen = () => { clearTimeout(closeTimer.current); setOpen(true); };
  const hoverClose = () => { closeTimer.current = setTimeout(() => setOpen(false), 120); };

  useEffect(() => {
    const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  const items = [
    { label: 'Carriers',            sub: 'Asset-based · LTL · TL',           href: '/' },
    { label: 'Oracle ERP',          sub: 'Fusion · NetSuite · JD Edwards',    href: '/erp' },
    { label: 'Freight & Logistics', sub: 'Brokers · Freight forwarders',      href: '/freight' },
    { label: 'Regenerative Health', sub: 'Clinics · Wellness · Aesthetics',   href: '/health' },
  ];

  const linkColor = onPhoto ? 'rgba(244,240,232,0.72)' : 'var(--muted)';
  const linkHover = onPhoto ? '#F4F0E8' : 'var(--ink)';

  return (
    <div ref={ref} style={{ position: 'relative' }} onMouseEnter={hoverOpen} onMouseLeave={hoverClose}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 0,
          fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.1em',
          color: open ? linkHover : linkColor,
          textTransform: 'uppercase', transition: 'color 0.2s',
          fontWeight: 500, display: 'flex', alignItems: 'center', gap: 5,
        }}
      >
        Verticals
        <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}><path d="M6 9l6 6 6-6"/></svg>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 14px)', left: '50%', transform: 'translateX(-50%)',
          background: 'var(--bg)', border: '1px solid var(--hairline)', borderRadius: 12,
          padding: '8px', minWidth: 240,
          boxShadow: '0 20px 60px rgba(0,0,0,0.22)', zIndex: 200,
        }}>
          {items.map(item => (
            <a key={item.href} href={item.href} onClick={() => setOpen(false)} style={{
              display: 'flex', flexDirection: 'column', gap: 2,
              padding: '11px 14px', borderRadius: 8,
              textDecoration: 'none', color: 'inherit',
              transition: 'background 0.15s',
            }}>
              <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, fontWeight: 600, color: 'var(--ink)', letterSpacing: '0.04em' }}>{item.label}</span>
              <span style={{ fontSize: 11, color: 'var(--muted)' }}>{item.sub}</span>
            </a>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Nav ───────────────────────────────────────────────────────────
function LegalNav({ scrolled }) {
  const onPhoto = !scrolled;
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      background: scrolled ? '#0A1612' : 'transparent',
      borderBottom: scrolled ? '1px solid var(--hairline)' : '1px solid transparent',
      transition: 'all 0.4s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 48px', height: 68, display: 'flex', alignItems: 'center', gap: 40 }}>
        <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          <LegalLogoMark size={26} />
          <span style={{
            fontFamily: 'var(--ff-display)',
            fontSize: 19, fontWeight: 500, letterSpacing: '-0.01em',
            color: onPhoto ? '#F4F0E8' : 'var(--ink)',
            transition: 'color 0.4s',
          }}>Echo</span>
        </a>
        <div style={{ flex: 1, display: 'flex', gap: 32, alignItems: 'center' }}>
          <LegalVerticalsDropdown onPhoto={onPhoto} />
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <a href="#book" data-open-book-call className="echo-cta--nav">
            <span className="echo-cta__dot" />
            <span>Get a demo</span>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ── Footer ────────────────────────────────────────────────────────
function LegalVerticalsRow() {
  const items = [
    { href: '/', label: 'Carriers' },
    { href: '/erp', label: 'Oracle ERP' },
    { href: '/freight', label: 'Freight & Logistics' },
    { href: '/health', label: 'Regenerative Health' },
  ];
  return (
    <div style={{ borderTop: '1px solid var(--hairline)', padding: '16px 0 18px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
      <style>{`.legal-vert-link{color:var(--muted);text-decoration:none;border-bottom:1px solid transparent;transition:color 200ms ease,border-color 200ms ease}.legal-vert-link:hover{color:var(--ink);border-bottom-color:var(--ink)}`}</style>
      <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>Verticals</span>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        {items.map((v, i) => (
          <span key={v.href} style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <a href={v.href} className="legal-vert-link" style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{v.label}</a>
            {i < items.length - 1 && <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--hairline)' }}>·</span>}
          </span>
        ))}
      </div>
    </div>
  );
}

function LegalFooter() {
  return (
    <footer className="plate-section" style={{ padding: '40px 0 60px' }}>
      <div className="glass-plate glass-plate--rounded" style={{ maxWidth: 1240, margin: '0 auto', padding: '48px 56px 32px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 32, flexWrap: 'wrap', marginBottom: 32 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
              <LegalLogoMark size={26} />
              <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 13, fontWeight: 500, letterSpacing: '0.05em' }}>Echo</span>
            </div>
            <p style={{ fontFamily: 'var(--ff-display)', fontSize: 16, color: 'var(--ink)', lineHeight: 1.5, maxWidth: 320, fontWeight: 400, letterSpacing: '-0.01em' }}>
              AI agents for back-office teams.<br/>
              <span style={{ color: 'var(--muted)', fontStyle: 'italic', fontWeight: 300 }}>Built on your stack. Owned by you.</span>
            </p>
          </div>
          <a href="#book" data-open-book-call style={{
            fontFamily: 'var(--ff-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
            color: '#F4F0E8',
            background: 'linear-gradient(180deg, #3B82F6 0%, #2563EB 100%)',
            padding: '10px 18px', borderRadius: 8,
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontWeight: 600,
            boxShadow: '0 4px 14px rgba(37,99,235,0.3)',
            border: '1px solid rgba(96,165,250,0.5)',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#7DC9A8', boxShadow: '0 0 6px rgba(125,201,168,0.85)' }}></span>
            Get a demo
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
          </a>
        </div>
        <LegalVerticalsRow />
        <div style={{ borderTop: '1px solid var(--hairline)', paddingTop: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 14, flexWrap: 'wrap', fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.07em' }}>
            <span>© 2026 ELITE CAPITAL INC.</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <a href="/privacy.html" className="legal-vert-link">Privacy</a>
              <span style={{ color: 'var(--hairline)' }}>·</span>
              <a href="/terms.html" className="legal-vert-link">Terms</a>
              <span style={{ color: 'var(--hairline)' }}>·</span>
              <a href="/security.html" className="legal-vert-link">Security</a>
              <span style={{ color: 'var(--hairline)' }}>·</span>
              <a href="mailto:jay@echoagents.io" className="legal-vert-link">Contact</a>
            </span>
          </span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.07em' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#7DC9A8', boxShadow: '0 0 6px rgba(125,201,168,0.6)', animation: 'pulse 2.4s ease-in-out infinite' }} />
              All systems operational
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6, fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.07em' }}>
              SOC 2
              <span style={{ fontSize: 9, opacity: 0.7 }}>(Type II in progress)</span>
            </span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── Section component ─────────────────────────────────────────────
function LegalSection({ id, num, title, children, registerRef }) {
  const ref = useRef(null);
  useEffect(() => {
    if (registerRef) registerRef(id, ref);
  }, [id]);
  return (
    <section
      id={id}
      ref={ref}
      style={{
        scrollMarginTop: 96,
        paddingTop: 8,
        paddingBottom: 56,
        borderBottom: '1px solid var(--hairline)',
      }}
    >
      <div style={{
        fontFamily: 'var(--ff-mono)',
        fontSize: 11,
        letterSpacing: '0.16em',
        textTransform: 'uppercase',
        color: 'var(--muted)',
        marginBottom: 12,
      }}>
        <span style={{ color: 'var(--accent)' }}>{num}</span>
        <span style={{ margin: '0 8px', color: 'var(--hairline-strong)' }}>·</span>
        <span>{title}</span>
      </div>
      <h2 style={{
        fontFamily: 'var(--ff-display)',
        fontSize: 26,
        fontWeight: 500,
        letterSpacing: '-0.015em',
        color: 'var(--ink)',
        lineHeight: 1.2,
        marginBottom: 20,
      }}>{title}</h2>
      <div className="legal-body">{children}</div>
    </section>
  );
}

// ── TOC with scrollspy ────────────────────────────────────────────
function LegalToc({ items, activeId }) {
  return (
    <nav style={{
      position: 'sticky',
      top: 96,
      alignSelf: 'start',
      paddingRight: 8,
    }}>
      <div style={{
        fontFamily: 'var(--ff-mono)',
        fontSize: 10,
        letterSpacing: '0.16em',
        textTransform: 'uppercase',
        color: 'var(--muted)',
        marginBottom: 18,
      }}>Contents</div>
      <ol style={{ listStyle: 'none', padding: 0, margin: 0 }}>
        {items.map(item => {
          const active = item.id === activeId;
          return (
            <li key={item.id} style={{ position: 'relative', paddingLeft: 14 }}>
              <span style={{
                position: 'absolute',
                left: 0,
                top: 12,
                width: 3,
                height: 18,
                borderRadius: 2,
                background: active ? 'var(--accent)' : 'transparent',
                transition: 'background 0.2s',
              }} />
              <a
                href={`#${item.id}`}
                style={{
                  display: 'block',
                  padding: '8px 0',
                  fontFamily: 'var(--ff-mono)',
                  fontSize: 11,
                  letterSpacing: '0.06em',
                  textTransform: 'uppercase',
                  color: active ? 'var(--ink)' : 'var(--muted)',
                  fontWeight: active ? 600 : 400,
                  textDecoration: 'none',
                  transition: 'color 0.2s',
                }}
                onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--ink-soft)'; }}
                onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'var(--muted)'; }}
              >
                <span style={{ color: active ? 'var(--accent)' : 'var(--muted-soft)', marginRight: 8 }}>{item.num}</span>
                {item.title}
              </a>
            </li>
          );
        })}
      </ol>
    </nav>
  );
}

// ── Compliance badge row ──────────────────────────────────────────
function ComplianceRow() {
  const badges = [
    { label: 'SOC 2 Type I',  sub: 'Achieved Aug 2025' },
    { label: 'SOC 2 Type II', sub: 'In progress' },
    { label: 'HIPAA',         sub: 'BAA on request' },
    { label: 'PIPEDA',        sub: 'Compliant' },
    { label: 'GDPR · CCPA',   sub: 'See Privacy Policy' },
  ];
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
      gap: 12,
      marginBottom: 8,
    }}>
      {badges.map(b => (
        <div key={b.label} style={{
          border: '1px solid var(--hairline)',
          borderRadius: 12,
          padding: '16px 18px',
          background: 'rgba(15, 22, 28, 0.5)',
        }}>
          <div style={{
            fontFamily: 'var(--ff-mono)',
            fontSize: 11,
            letterSpacing: '0.1em',
            textTransform: 'uppercase',
            color: 'var(--ink)',
            fontWeight: 600,
            marginBottom: 4,
          }}>{b.label}</div>
          <div style={{
            fontFamily: 'var(--ff-mono)',
            fontSize: 10,
            letterSpacing: '0.06em',
            color: 'var(--muted)',
          }}>{b.sub}</div>
        </div>
      ))}
    </div>
  );
}

// ── Per-agent scope table ─────────────────────────────────────────
function AgentScopeTable() {
  const rows = [
    { agent: 'Triage',  domain: 'Email and Teams',     scopes: 'Mail.Read.Shared, Mail.Send.Shared, ChannelMessage.Send (Teams escalation), read scopes on the assigned TMS / ERP / EHR' },
    { agent: 'Docs',    domain: 'Document handling',   scopes: 'Files.Read.All for attachments, write scopes on TMS / ERP / EHR for posting POD, BOL, invoice, vendor doc, intake or consent records' },
    { agent: 'Cal',     domain: 'Scheduling',          scopes: 'Calendar.ReadWrite on the assigned mailbox, write scopes on OpenDock or the EHR scheduler' },
    { agent: 'Ledger',  domain: 'AR and finance',      scopes: 'Read scopes on TMS / ERP / EHR billing, write scopes for posting AR records, journals, claims, or detention entries' },
    { agent: 'Audit',   domain: 'Control evidence',    scopes: 'Read-only across Oracle GRC and the ERP audit trail. No write scopes.' },
    { agent: 'Recover', domain: 'Collections',         scopes: 'Read scopes on McLeod AR and factoring records, write scopes for posting collection notes and status updates' },
    { agent: 'Intake',  domain: 'Patient intake',      scopes: 'Read and write scopes on the EHR intake module via HL7 or FHIR where supported' },
    { agent: 'Quote',   domain: 'Rate quoting',        scopes: 'Read scopes on McLeod, DAT, and Greenscreens.ai, write scopes for posting quote records and tender responses' },
  ];
  return (
    <div style={{ border: '1px solid var(--hairline)', borderRadius: 12, overflow: 'hidden', marginBottom: 8 }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '0.6fr 0.9fr 2fr',
        background: 'var(--surface)',
      }}>
        {['AGENT', 'DOMAIN', 'SCOPES REQUESTED'].map(h => (
          <div key={h} style={{
            padding: '12px 18px',
            fontFamily: 'var(--ff-mono)',
            fontSize: 10,
            letterSpacing: '0.12em',
            color: 'var(--muted)',
            borderBottom: '1px solid var(--hairline)',
          }}>{h}</div>
        ))}
      </div>
      {rows.map((r, i) => (
        <div key={r.agent} style={{
          display: 'grid',
          gridTemplateColumns: '0.6fr 0.9fr 2fr',
          borderBottom: i < rows.length - 1 ? '1px solid var(--hairline)' : 'none',
        }}>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink)', fontWeight: 600 }}>{r.agent}</div>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink-soft)' }}>{r.domain}</div>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.5 }}>{r.scopes}</div>
        </div>
      ))}
    </div>
  );
}

// ── Per-vertical data-flow card grid ──────────────────────────────
function VerticalFlowGrid() {
  const flows = [
    {
      label: 'Carriers',
      source: 'Outlook · Teams · Trimble TruckMate · OpenDock · Samsara / Motive',
      action: 'Quote, dispatch, POD posting, detention claims, AR follow-up',
      audit: 'Case record + tool call log in Postgres inside your Azure tenant',
    },
    {
      label: 'Oracle ERP',
      source: 'Outlook · Teams · Oracle Fusion or NetSuite · Oracle GRC',
      action: 'Invoice extraction, journal posting, AR / AP, control evidence',
      audit: 'SOX-relevant case record + GRC-linked audit entry',
    },
    {
      label: 'Freight & Logistics',
      source: 'Outlook · Teams · McLeod · DAT · Greenscreens.ai · EDI 204 / 210 / 214',
      action: 'Tender response, rate quoting, settlement, collections',
      audit: 'Case record + EDI message ID + tool call log',
    },
    {
      label: 'Regenerative Health',
      source: 'Outlook · Teams · EHR (athenahealth, Epic) via HL7 or FHIR',
      action: 'Patient intake, scheduling, chart updates, claims',
      audit: 'PHI-redacted case record + BAA-scoped retention',
    },
  ];
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
      gap: 12,
      marginBottom: 8,
    }}>
      {flows.map(f => (
        <div key={f.label} style={{
          border: '1px solid var(--hairline)',
          borderRadius: 12,
          padding: '18px 18px',
          background: 'rgba(15, 22, 28, 0.5)',
        }}>
          <div style={{
            fontFamily: 'var(--ff-mono)',
            fontSize: 11,
            letterSpacing: '0.1em',
            textTransform: 'uppercase',
            color: 'var(--accent)',
            fontWeight: 600,
            marginBottom: 12,
          }}>{f.label}</div>
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 4 }}>Source</div>
            <div style={{ fontSize: 12, color: 'var(--ink-soft)', lineHeight: 1.45 }}>{f.source}</div>
          </div>
          <div style={{ marginBottom: 10 }}>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 4 }}>Action</div>
            <div style={{ fontSize: 12, color: 'var(--ink-soft)', lineHeight: 1.45 }}>{f.action}</div>
          </div>
          <div>
            <div style={{ fontFamily: 'var(--ff-mono)', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 4 }}>Audit</div>
            <div style={{ fontSize: 12, color: 'var(--ink-soft)', lineHeight: 1.45 }}>{f.audit}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Sub-processor table ───────────────────────────────────────────
function SubprocessorTable() {
  const rows = [
    { name: 'Anthropic',        purpose: 'Claude Sonnet 4.6 inference', region: 'United States' },
    { name: 'Microsoft Azure',  purpose: 'Runtime, Key Vault, Postgres', region: 'Your tenant, your region' },
    { name: 'Microsoft Graph',  purpose: 'Mailbox and Teams access',     region: 'Your tenant' },
    { name: 'Vercel',           purpose: 'Marketing site hosting',       region: 'United States' },
    { name: 'Formspree',        purpose: 'Marketing form intake',        region: 'United States' },
    { name: 'Google Workspace', purpose: 'Echo team inbox and scheduling', region: 'United States' },
  ];
  return (
    <div style={{ border: '1px solid var(--hairline)', borderRadius: 12, overflow: 'hidden', marginBottom: 8 }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1.4fr 1.4fr',
        background: 'var(--surface)',
      }}>
        {['VENDOR', 'PURPOSE', 'REGION'].map(h => (
          <div key={h} style={{
            padding: '12px 18px',
            fontFamily: 'var(--ff-mono)',
            fontSize: 10,
            letterSpacing: '0.12em',
            color: 'var(--muted)',
            borderBottom: '1px solid var(--hairline)',
          }}>{h}</div>
        ))}
      </div>
      {rows.map((r, i) => (
        <div key={r.name} style={{
          display: 'grid',
          gridTemplateColumns: '1fr 1.4fr 1.4fr',
          borderBottom: i < rows.length - 1 ? '1px solid var(--hairline)' : 'none',
        }}>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>{r.name}</div>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink-soft)' }}>{r.purpose}</div>
          <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--ink-soft)' }}>{r.region}</div>
        </div>
      ))}
    </div>
  );
}

// ── Page body ─────────────────────────────────────────────────────
function SecurityContent() {
  const sections = [
    { id: 'architecture',     num: '01', title: 'Architecture' },
    { id: 'residency',        num: '02', title: 'Data residency' },
    { id: 'encryption',       num: '03', title: 'Encryption' },
    { id: 'authentication',   num: '04', title: 'Authentication and access' },
    { id: 'agent-scopes',     num: '05', title: 'Per-agent scopes' },
    { id: 'vertical-flows',   num: '06', title: 'Per-vertical data flows' },
    { id: 'reasoning',        num: '07', title: 'The reasoning layer' },
    { id: 'safety',           num: '08', title: 'Safety and human approval' },
    { id: 'logging',          num: '09', title: 'Logging and audit' },
    { id: 'pii',              num: '10', title: 'PII minimization and retention' },
    { id: 'reliability',      num: '11', title: 'Idempotency and reliability' },
    { id: 'hipaa',            num: '12', title: 'HIPAA-specific safeguards' },
    { id: 'sox',              num: '13', title: 'Financial workflows (SOX)' },
    { id: 'compliance',       num: '14', title: 'Compliance' },
    { id: 'sub-processors',   num: '15', title: 'Sub-processors' },
    { id: 'nda-docs',         num: '16', title: 'What we share under NDA' },
    { id: 'vuln-reporting',   num: '17', title: 'Vulnerability reporting' },
    { id: 'incident',         num: '18', title: 'Incident response' },
    { id: 'pen-testing',      num: '19', title: 'Penetration testing' },
    { id: 'rollback',         num: '20', title: 'Rollback runbook' },
    { id: 'updates',          num: '21', title: 'Updates' },
  ];

  const refs = useRef({});
  const registerRef = (id, ref) => { refs.current[id] = ref; };
  const [activeId, setActiveId] = useState(sections[0].id);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries.filter(e => e.isIntersecting);
        if (visible.length > 0) {
          visible.sort((a, b) => a.target.getBoundingClientRect().top - b.target.getBoundingClientRect().top);
          setActiveId(visible[0].target.id);
        }
      },
      { rootMargin: '-96px 0px -55% 0px', threshold: 0 }
    );
    sections.forEach(s => {
      const node = refs.current[s.id] && refs.current[s.id].current;
      if (node) observer.observe(node);
    });
    return () => observer.disconnect();
  }, []);

  return (
    <section className="plate-section" style={{ paddingTop: 120 }}>
      <div className="glass-plate glass-plate--rounded" style={{ maxWidth: 1240, margin: '0 auto', padding: '64px 64px 48px' }}>
        <div style={{ marginBottom: 48 }}>
          <span style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--accent)', letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 500 }}>Trust</span>
          <h1 style={{
            fontFamily: 'var(--ff-display)',
            fontSize: 56, fontWeight: 500, letterSpacing: '-0.025em',
            color: 'var(--ink)', lineHeight: 1.02,
            marginTop: 14, marginBottom: 16,
          }}>Security</h1>
          <p style={{ fontFamily: 'var(--ff-mono)', fontSize: 11, color: 'var(--muted)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
            Effective May 17, 2026 · Elite Capital Inc. · Toronto, Ontario
          </p>
          <p style={{
            fontFamily: 'var(--ff-body)',
            fontSize: 16,
            color: 'rgba(244,240,232,0.78)',
            lineHeight: 1.65,
            marginTop: 22,
            maxWidth: 720,
          }}>
            Echo runs inside your Microsoft Azure tenant. Customer data stays in your tenant. This page describes the controls behind that statement.
          </p>
        </div>

        <div className="legal-layout" style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 64, alignItems: 'start' }}>
          <LegalToc items={sections} activeId={activeId} />

          <div>
            <LegalSection id="architecture" num="01" title="Architecture" registerRef={registerRef}>
              <p>Echo agents run inside your Microsoft Azure tenant or an equivalent buyer-approved environment. Echo's service does not host your data.</p>
              <p>Your source systems stay inside your boundary: Outlook shared inboxes, Microsoft Teams, Trimble TruckMate, your EHR, your ERP. Echo reads and writes through APIs you grant scopes to.</p>
              <p>The Echo service in your tenant runs three layers:</p>
              <ul>
                <li><strong>A LangGraph orchestrator</strong> that coordinates each agent's workflow.</li>
                <li><strong>Postgres</strong> for case state, idempotency keys, extracted fields, audit records, and metrics.</li>
                <li><strong>Deterministic backend tools</strong> that perform every customer-visible action with schemas and audit logs.</li>
              </ul>
            </LegalSection>

            <LegalSection id="residency" num="02" title="Data residency" registerRef={registerRef}>
              <p>Customer operational data stays in your tenant, in your region. Microsoft Azure is the runtime. Postgres is co-located with the runtime.</p>
              <p>Marketing site form submissions on echoagents.io are processed by Vercel and Formspree in the United States.</p>
              <p>Echo Agents has no production database that holds customer operational data outside your tenant.</p>
            </LegalSection>

            <LegalSection id="encryption" num="03" title="Encryption" registerRef={registerRef}>
              <ul>
                <li><strong>In transit:</strong> TLS 1.2 or higher for every external connection, including Microsoft Graph, TruckMate APIs, Anthropic, and every other integration.</li>
                <li><strong>At rest:</strong> customer data is encrypted within your Azure tenant using Azure-managed keys, or customer-managed keys per your policy.</li>
                <li><strong>Secrets:</strong> stored in Azure Key Vault or your equivalent buyer-approved secret store. Secrets are never in source code or Postgres.</li>
              </ul>
            </LegalSection>

            <LegalSection id="authentication" num="04" title="Authentication and access" registerRef={registerRef}>
              <ul>
                <li><strong>Echo team access:</strong> Microsoft Entra ID single sign-on with phishing-resistant MFA enforced on every account.</li>
                <li><strong>Customer-side SSO:</strong> through your existing identity provider.</li>
                <li><strong>Microsoft Graph scopes:</strong> the Echo service in your tenant uses application permissions scoped to the mailboxes and Teams channels you assign per agent. Pickup-write and send-as permissions are scoped per agent and per mailbox.</li>
                <li><strong>Least privilege:</strong> production access is granted on request, time-bound, and revoked automatically. No shared admin credentials.</li>
                <li><strong>Background checks:</strong> every Echo employee and contractor passes a background check and signs a confidentiality agreement before touching customer environments.</li>
              </ul>
            </LegalSection>

            <LegalSection id="agent-scopes" num="05" title="Per-agent scopes" registerRef={registerRef}>
              <p>Each agent requests only the scopes its job requires. Scopes are reviewed and approved by your admin before the agent is deployed and revoked when the agent is paused or removed.</p>
              <AgentScopeTable />
              <p>Not every agent runs in every vertical. Triage is universal. Audit is ERP-only. Recover and Quote are Freight-only. Intake is Health-only. The full agent and vertical map lives on each <a href="/">vertical page</a>.</p>
            </LegalSection>

            <LegalSection id="vertical-flows" num="06" title="Per-vertical data flows" registerRef={registerRef}>
              <p>The architecture is the same across verticals. The source systems and the audit record schema vary by industry.</p>
              <VerticalFlowGrid />
            </LegalSection>

            <LegalSection id="reasoning" num="07" title="The reasoning layer" registerRef={registerRef}>
              <p>Classification and structured extraction use Claude Sonnet 4.6 from Anthropic, called through the LangGraph orchestrator. Anthropic does not train on customer inputs.</p>
              <p>The model produces strict JSON. A validation layer rejects malformed or incomplete outputs before any customer-visible action.</p>
              <p>The model does not send emails, create orders, or call APIs directly. All backend actions are performed by deterministic Echo tools with schemas and audit logs.</p>
            </LegalSection>

            <LegalSection id="safety" num="08" title="Safety and human approval" registerRef={registerRef}>
              <p>Draft-first by default. Auto-send stays off until measured accuracy meets your threshold.</p>
              <p>Auto-send is gated by feature flags on four dimensions: intent type, customer tier, confidence threshold, and backend result quality.</p>
              <p>Human approval gates fire on ambiguous, high-value, incomplete, frustrated, exception, and policy-sensitive cases.</p>
              <p>The autonomy level (read-only, suggest, auto-execute, auto-execute with audit) is set per agent and per workflow.</p>
            </LegalSection>

            <LegalSection id="logging" num="09" title="Logging and audit" registerRef={registerRef}>
              <p>Every inbound message becomes a case record. The audit trail covers:</p>
              <ul>
                <li>State transitions across the workflow.</li>
                <li>The version of extracted data the model produced.</li>
                <li>Backend tool call status and payload references.</li>
                <li>Draft and send IDs from Microsoft Graph.</li>
                <li>Teams escalation IDs.</li>
                <li>Human approvals and overrides.</li>
                <li>Latency and error category for each step.</li>
              </ul>
              <p>Your compliance team can query the full audit trail at any time. The decision log posts to your designated Teams audit channel as it happens.</p>
              <p>Production access by Echo staff is logged and reviewable by your team on request.</p>
            </LegalSection>

            <LegalSection id="pii" num="10" title="PII minimization and retention" registerRef={registerRef}>
              <p>Logs are minimized to drop free-text customer body content where the workflow allows.</p>
              <p>Postgres stores case state, extracted fields, audit records, and metrics. It does not store full email bodies or PHI unless your contract explicitly approves longer retention.</p>
              <p>Retention is configurable per customer and per data class. Defaults are short. Auditable case records are retained for the audit window your compliance team requests.</p>
            </LegalSection>

            <LegalSection id="reliability" num="11" title="Idempotency and reliability" registerRef={registerRef}>
              <p>Idempotency controls prevent duplicate replies from Microsoft Graph retries. Every action carries an idempotency key.</p>
              <p>Reply-in-thread behavior uses Microsoft Graph createReply and reply APIs, preserving the original thread context for the customer.</p>
              <p>Dead-letter handling captures failed messages and replays them once the underlying issue is resolved.</p>
            </LegalSection>

            <LegalSection id="hipaa" num="12" title="HIPAA-specific safeguards" registerRef={registerRef}>
              <p>Echo Agents operates as a Business Associate for health vertical customers. A signed Business Associate Agreement is in place before any PHI is processed.</p>
              <ul>
                <li><strong>EHR access:</strong> HL7 or FHIR connectors where the EHR supports them. Scopes are limited to the patient records and workflows your team assigns to each agent.</li>
                <li><strong>PHI logging redaction:</strong> PHI fields are redacted from operational logs and case state by default. The audit trail records that a PHI field existed and was processed, without storing the field value.</li>
                <li><strong>Customer-controlled retention:</strong> clinical case data retention is set in the BAA. Defaults are short.</li>
                <li><strong>Workforce:</strong> Echo staff with potential PHI access complete HIPAA workforce training and sign HIPAA-specific confidentiality terms.</li>
              </ul>
            </LegalSection>

            <LegalSection id="sox" num="13" title="Financial workflows (SOX)" registerRef={registerRef}>
              <p>For ERP customers operating under SOX, the Audit and Ledger agents are designed to fit existing control frameworks.</p>
              <ul>
                <li><strong>Tamper-evident audit trail:</strong> every action that affects a financial control writes an immutable record with the agent ID, the change set, the source document reference, and the user or scope that authorized the run.</li>
                <li><strong>Segregation of duties:</strong> enforced at the scope level. The Audit agent runs read-only against Oracle GRC and the ERP audit trail. The Ledger agent holds the write scopes needed to post AR records and journals. The two roles never share scopes.</li>
                <li><strong>Control evidence:</strong> the Audit agent assembles control-test evidence on a schedule your compliance team sets, ready for the external auditor.</li>
              </ul>
            </LegalSection>

            <LegalSection id="compliance" num="14" title="Compliance" registerRef={registerRef}>
              <ComplianceRow />
              <p style={{ marginTop: 16 }}>SOC 2 Type I achieved (August 2025). Type II in progress. Reports are available under NDA.</p>
              <p>HIPAA: Business Associate Agreements are signed before any PHI is processed. Health vertical customers operate under a BAA from day one.</p>
              <p>PIPEDA, GDPR, and CCPA obligations are covered in the Privacy Policy.</p>
            </LegalSection>

            <LegalSection id="sub-processors" num="15" title="Sub-processors" registerRef={registerRef}>
              <p>Vendors that touch customer or prospect data:</p>
              <SubprocessorTable />
              <p>Microsoft Azure, Microsoft Graph, and Anthropic touch live customer data. Vercel, Formspree, and Google Workspace only touch marketing data captured through echoagents.io.</p>
              <p>If we add or change a sub-processor, we update this page and notify active customers by email.</p>
            </LegalSection>

            <LegalSection id="nda-docs" num="16" title="What we share under NDA" registerRef={registerRef}>
              <p>The following documents are available under NDA. Email <a href="mailto:security@echoagents.io">security@echoagents.io</a> to request a copy.</p>
              <ul>
                <li>SOC 2 Type I report (current). SOC 2 Type II bridge letters as Type II progresses.</li>
                <li>Third-party penetration test report (current).</li>
                <li>Data Protection Impact Assessment (DPIA) for EU and UK deployments.</li>
                <li>Completed vendor security questionnaires (SIG Lite, CAIQ, custom buyer questionnaires).</li>
                <li>Network and trust diagrams scoped to your deployment.</li>
              </ul>
              <p>Items covered in your contract live there: the Master Services Agreement, the Data Processing Addendum, the Business Associate Agreement for healthcare customers, and the workflow-level scope and retention schedules.</p>
            </LegalSection>

            <LegalSection id="vuln-reporting" num="17" title="Vulnerability reporting" registerRef={registerRef}>
              <p>Email <a href="mailto:security@echoagents.io">security@echoagents.io</a> with a clear description and reproduction steps.</p>
              <p>We acknowledge reports within 1 business day and respond with triage within 5 business days.</p>
              <p>Please do not run automated scanners against production or attempt to access data that is not yours. Coordinated disclosure only.</p>
            </LegalSection>

            <LegalSection id="incident" num="18" title="Incident response" registerRef={registerRef}>
              <p>Customers impacted by a confirmed security incident are notified within 72 hours of confirmation. This aligns with the GDPR Article 33 timing standard.</p>
              <p>The notification covers:</p>
              <ul>
                <li>What happened, in plain language.</li>
                <li>Which categories of data were involved.</li>
                <li>When we detected and confirmed it.</li>
                <li>Containment and remediation actions taken or planned.</li>
                <li>The point of contact for follow-up.</li>
              </ul>
              <p>Post-incident, we publish a written root-cause analysis to affected customers and update internal controls.</p>
            </LegalSection>

            <LegalSection id="pen-testing" num="19" title="Penetration testing" registerRef={registerRef}>
              <p>Annual third-party penetration testing covers the agent runtime, the Teams audit feed, and the customer-facing API surface. Critical and high findings are remediated before the report closes.</p>
              <p>The current report is available under NDA. Email <a href="mailto:security@echoagents.io">security@echoagents.io</a> to request a copy.</p>
            </LegalSection>

            <LegalSection id="rollback" num="20" title="Rollback runbook" registerRef={registerRef}>
              <p>If you need to halt automation, the runbook covers three steps:</p>
              <ul>
                <li>Disable auto-send.</li>
                <li>Fall back to drafts only.</li>
                <li>Pause ingestion.</li>
              </ul>
              <p>The runbook is documented in every customer's onboarding and rehearsed before any agent is set to auto-execute.</p>
            </LegalSection>

            <LegalSection id="updates" num="21" title="Updates" registerRef={registerRef}>
              <p>We update this page when our security posture changes (new controls, new sub-processors, new certifications). Active customers receive an email summary of material changes. Past versions are available on request.</p>
            </LegalSection>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── App ───────────────────────────────────────────────────────────
function SecurityApp() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', 'dark');
  }, []);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <>
      <LegalNav scrolled={scrolled} />
      <main>
        <SecurityContent />
      </main>
      <LegalFooter />
      {typeof BookCallModal !== 'undefined' && <BookCallModal />}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<SecurityApp />);
