// ESIGN PLATFORM — tab views (default Arbiter platform style) — FULL FEATURE SET
const { useState: useEsV, useMemo: useEsMemo } = React;
const Tv = window.ArbiterTokens;

// ── Helpers ────────────────────────────────────────────────────────────────────

function EsStatusBadge({ status }) {
  const es = window.__es;
  const s = es.envelopeStatus(status);
  return <span style={{ ...es.tag, background: s.bg, color: s.color }}>{s.label}</span>;
}

function EsSignerBadge({ status }) {
  const es = window.__es;
  const s = es.signerStatus(status);
  return <span style={{ ...es.tag, background: s.bg, color: s.color, fontSize: '10px' }}>{status}</span>;
}

function EsRiskPill({ level }) {
  const es = window.__es;
  const map = {
    'High':   { bg: es.crimsonBg, color: es.crimson },
    'Medium': { bg: es.amberBg,   color: es.amber   },
    'Low':    { bg: es.emeraldBg, color: es.emerald },
  };
  const s = map[level] || map.Low;
  return <span style={{ ...es.tag, background: s.bg, color: s.color }}>{level}</span>;
}

function EsGovStagePill({ stage }) {
  const es = window.__es;
  const map = {
    'Published':   { bg: es.emeraldBg, color: es.emerald },
    'In Review':   { bg: es.amberBg,   color: es.amber   },
    'Draft':       { bg: es.slateBg,   color: es.slate   },
    'Deprecated':  { bg: es.crimsonBg, color: es.crimson },
  };
  const s = map[stage] || map.Draft;
  return <span style={{ ...es.tag, background: s.bg, color: s.color }}>{stage}</span>;
}

function EsPrivilegePill({ label, wall }) {
  const es = window.__es;
  if (!label || label === 'None' || label === 'External') {
    return <span style={{ ...es.tag, background: es.slateBg, color: es.slate }}>{label || 'External'}</span>;
  }
  const color = wall ? es.crimson : es.violet;
  const bg = wall ? es.crimsonBg : es.violetBg;
  return <span style={{ ...es.tag, background: bg, color }}>{wall ? ' ' : ''}{label}</span>;
}

function EsRecipientRow({ r }) {
  const es = window.__es;
  const roleColor = { Signer: es.indigo, Approver: es.violet, CC: es.slate, 'Form Filler': es.teal, Witness: es.teal, Testator: es.indigo }[r.role] || es.slate;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 0', borderBottom: `1px solid ${Tv.color.border.light}` }}>
      <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: `${roleColor}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 700, color: roleColor, flexShrink: 0 }}>
        {r.name.split(' ').map(w => w[0]).join('').slice(0, 2)}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: '12px', fontWeight: 600, color: Tv.color.text.primary }}>{r.name}</div>
        <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.email}</div>
      </div>
      <span style={{ fontSize: '10px', color: roleColor, fontWeight: 500, background: `${roleColor}12`, padding: '2px 7px', borderRadius: '8px' }}>{r.role}</span>
      {r.status && <EsSignerBadge status={r.status} />}
      {r.signedAt && <span style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{new Date(r.signedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>}
    </div>
  );
}

function EsMetric({ label, value, delta, deltaColor }) {
  const es = window.__es;
  return (
    <div style={es.stat}>
      <div style={es.statLabel}>{label}</div>
      <div style={es.statValue}>{value}</div>
      {delta && <div style={{ ...es.statDelta, color: deltaColor || es.emerald }}>{delta}</div>}
    </div>
  );
}

// ── INBOX ──────────────────────────────────────────────────────────────────────

function EsInbox() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [selected, setSelected] = useEsV(null);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 380px' : '1fr', gap: '20px' }}>
      <div>
        <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: '13px', fontWeight: 600, color: Tv.color.text.primary }}>Documents requiring your signature</div>
          <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{data.inbox.length} item{data.inbox.length !== 1 ? 's' : ''}</span>
        </div>
        {data.inbox.map(env => {
          const myRec = env.recipients[0];
          const isSelected = selected?.id === env.id;
          const daysLeft = env.expiresAt ? Math.ceil((new Date(env.expiresAt) - new Date()) / 86400000) : null;
          const nudge = data.nudgeLadders.find(n => n.envelopeId === env.id);
          return (
            <div key={env.id} onClick={() => setSelected(isSelected ? null : env)}
              style={{ background: Tv.color.bg.card, border: `1px solid ${isSelected ? es.indigo : Tv.color.border.light}`, borderRadius: '10px', padding: '16px', marginBottom: '10px', cursor: 'pointer', transition: 'border-color 0.15s' }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '10px' }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tv.color.text.primary, marginBottom: '3px' }}>{env.subject}</div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.secondary, display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                    <span>From: <strong>{env.sender}</strong></span>
                    <EsPrivilegePill label={env.privilege} wall={env.ethicalWall} />
                    {env.matterId && <span style={{ color: es.indigo, fontWeight: 500 }}>{env.matter}</span>}
                  </div>
                </div>
                <EsSignerBadge status={myRec.status} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
                <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{env.pages} pages · {env.fields} fields</span>
                {env.hasRedlines && (
                  <span style={{ fontSize: '10px', fontWeight: 600, color: es.amber, background: es.amberBg, padding: '2px 8px', borderRadius: '8px', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                    <I.Redline size={10} color={es.amber} /> Redlines
                  </span>
                )}
                {env.notarized && (
                  <span style={{ fontSize: '10px', fontWeight: 600, color: es.violet, background: es.violetBg, padding: '2px 8px', borderRadius: '8px', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                    <I.Gavel size={10} color={es.violet} /> Notary
                  </span>
                )}
                {nudge && (
                  <span style={{ fontSize: '10px', fontWeight: 600, color: es.teal, background: es.tealBg, padding: '2px 8px', borderRadius: '8px', display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                    <I.Bell size={10} color={es.teal} /> Nudge {nudge.attempts}x · {nudge.channel}
                  </span>
                )}
                {daysLeft !== null && (
                  <span style={{ fontSize: '10px', fontWeight: 600, color: daysLeft <= 3 ? es.crimson : es.amber, background: daysLeft <= 3 ? es.crimsonBg : es.amberBg, padding: '2px 8px', borderRadius: '8px' }}>
                    Expires {daysLeft}d
                  </span>
                )}
                <span style={{ marginLeft: 'auto', fontSize: '11px', color: Tv.color.text.tertiary }}>{new Date(env.sentAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                <button style={{ ...es.btnPrimary, padding: '5px 12px', fontSize: '11px' }} onClick={e => e.stopPropagation()}>
                  <I.Signature size={11} color="#fff" strokeWidth={1.75} /> Sign Now
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {selected && <EsEnvelopeDetail env={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

function EsEnvelopeDetail({ env, onClose }) {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const redlines = data.redlines.filter(r => r.envelopeId === env.id);
  const pay = data.payments.find(p => p.envelopeId === env.id);
  const cert = data.courtCertificates[env.id];

  return (
    <div style={es.card}>
      <div style={{ ...es.cardH, background: es.indigoBg, borderBottom: `1px solid ${es.indigoBorder}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <I.Envelope size={14} color={es.indigo} strokeWidth={1.75} />
          <span style={{ color: es.indigo }}>Envelope Detail</span>
        </div>
        <button onClick={onClose} style={{ ...es.btnIcon, width: '22px', height: '22px' }}><I.X size={10} color={Tv.color.text.secondary} strokeWidth={2} /></button>
      </div>
      <div style={{ padding: '14px 16px' }}>
        <div style={{ fontSize: '13px', fontWeight: 700, color: Tv.color.text.primary, marginBottom: '4px' }}>{env.subject}</div>
        <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, marginBottom: '12px' }}>{env.matter} · {env.pages} pages · {env.fields} fields</div>

        <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', marginBottom: '14px' }}>
          <EsPrivilegePill label={env.privilege} wall={env.ethicalWall} />
          {env.esignConsent && <span style={{ ...es.tag, background: es.emeraldBg, color: es.emerald }}>ok ESIGN Consent</span>}
          {env.notarized && <span style={{ ...es.tag, background: es.violetBg, color: es.violet }}>Notarized</span>}
          {env.witnessed && <span style={{ ...es.tag, background: es.tealBg, color: es.teal }}>Witnessed</span>}
        </div>

        <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Recipients</div>
        {env.recipients.map(r => <EsRecipientRow key={r.id} r={r} />)}

        {redlines.length > 0 && (
          <>
            <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', margin: '14px 0 8px' }}>Redlines</div>
            {redlines.map(rl => (
              <div key={rl.id} style={{ padding: '8px 10px', background: Tv.color.bg.secondary, borderRadius: '6px', marginBottom: '6px' }}>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.primary }}>{rl.clause}</div>
                <div style={{ fontSize: '11px', color: Tv.color.text.secondary, margin: '2px 0 4px' }}>{rl.summary}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Proposed by {rl.proposer}</span>
                  <span style={{ ...es.tag, background: rl.status === 'Accepted' ? es.emeraldBg : rl.status === 'Rejected' ? es.crimsonBg : es.amberBg, color: rl.status === 'Accepted' ? es.emerald : rl.status === 'Rejected' ? es.crimson : es.amber }}>{rl.status}</span>
                </div>
              </div>
            ))}
          </>
        )}

        {pay && (
          <>
            <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', margin: '14px 0 8px' }}>Payment</div>
            <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px', display: 'flex', alignItems: 'center', gap: '10px' }}>
              <I.Payment size={18} color={es.indigo} strokeWidth={1.5} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tv.color.text.primary }}>{pay.amount}</div>
                <div style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{pay.method}</div>
              </div>
              <span style={{ ...es.tag, background: pay.status === 'Captured' ? es.emeraldBg : es.amberBg, color: pay.status === 'Captured' ? es.emerald : es.amber }}>{pay.status}</span>
            </div>
          </>
        )}

        <div style={{ display: 'flex', gap: '8px', marginTop: '16px' }}>
          <button style={{ ...es.btnPrimary, flex: 1 }}><I.Signature size={12} color="#fff" /> Sign</button>
          {cert && <button style={es.btnSecondary}><I.Download size={11} color={Tv.color.text.secondary} /> Cert</button>}
        </div>
      </div>
    </div>
  );
}

// ── ENVELOPES ──────────────────────────────────────────────────────────────────

function EsEnvelopes() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [filter, setFilter] = useEsV('all');
  const [selected, setSelected] = useEsV(null);

  const filters = [
    { id: 'all', label: 'All' }, { id: 'Sent', label: 'Sent' },
    { id: 'Waiting', label: 'Waiting' }, { id: 'Completed', label: 'Completed' },
    { id: 'Declined', label: 'Declined' }, { id: 'Draft', label: 'Draft' },
  ];

  const filtered = useEsMemo(() => filter === 'all' ? data.envelopes : data.envelopes.filter(e => e.status === filter), [filter]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 380px' : '1fr', gap: '20px' }}>
      <div style={es.card}>
        <div style={{ ...es.cardH, gap: '8px' }}>
          <span>All Envelopes</span>
          <div style={{ display: 'flex', gap: '6px', marginLeft: 'auto' }}>
            {filters.map(f => (
              <button key={f.id} onClick={() => setFilter(f.id)}
                style={{ ...es.filterBtn, ...(filter === f.id ? es.filterBtnActive : {}) }}>{f.label}</button>
            ))}
          </div>
        </div>
        <div style={{ overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={es.th}>Envelope</th>
                <th style={es.th}>Matter</th>
                <th style={es.th}>Privilege</th>
                <th style={es.th}>Status</th>
                <th style={es.th}>Signers</th>
                <th style={es.th}>Flags</th>
                <th style={es.th}>Sent</th>
                <th style={es.th}></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(env => (
                <tr key={env.id} onClick={() => setSelected(env)}
                  style={{ cursor: 'pointer', background: selected?.id === env.id ? es.indigoBg : 'transparent' }}>
                  <td style={es.td}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tv.color.text.primary }}>{env.subject}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono }}>{env.id}</div>
                  </td>
                  <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{env.matter}</td>
                  <td style={es.td}><EsPrivilegePill label={env.privilege} wall={env.ethicalWall} /></td>
                  <td style={es.td}><EsStatusBadge status={env.status} /></td>
                  <td style={{ ...es.td, fontSize: '11px' }}>
                    {env.recipients.filter(r => r.status === 'Signed').length}/{env.recipients.filter(r => r.role !== 'CC').length}
                  </td>
                  <td style={es.td}>
                    <div style={{ display: 'flex', gap: '4px' }}>
                      {env.hasRedlines && <span title="Has redlines"><I.Redline size={14} color={es.amber} /></span>}
                      {env.notarized && <span title="Notarized"><I.Gavel size={14} color={es.violet} /></span>}
                      {env.witnessed && <span title="Witnessed"><I.Witness size={14} color={es.teal} /></span>}
                      {env.paymentLinked && <span title="Payment linked"><I.Payment size={14} color={es.indigo} /></span>}
                    </div>
                  </td>
                  <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>
                    {env.sentAt ? new Date(env.sentAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '—'}
                  </td>
                  <td style={es.td}>
                    {env.status === 'Completed' && <button style={es.btnGhost} onClick={e => e.stopPropagation()}><I.Download size={11} color={es.indigo} /> Cert</button>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      {selected && <EsEnvelopeDetail env={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

// ── COMPOSE ────────────────────────────────────────────────────────────────────

function EsCompose() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [step, setStep] = useEsV(1);
  const steps = [
    { id: 1, label: 'Upload' },
    { id: 2, label: 'AI Detect + Risk Scan' },
    { id: 3, label: 'Recipients + Workflow' },
    { id: 4, label: 'Consent + Send' },
  ];

  return (
    <div>
      {/* Stepper */}
      <div style={{ display: 'flex', gap: '0', marginBottom: '20px', background: Tv.color.bg.card, border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', padding: '4px' }}>
        {steps.map((s, i) => (
          <div key={s.id} onClick={() => setStep(s.id)}
            style={{
              flex: 1, padding: '10px 14px', borderRadius: '6px', cursor: 'pointer',
              background: step === s.id ? es.indigo : 'transparent',
              color: step === s.id ? '#fff' : Tv.color.text.secondary,
              display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px', fontWeight: 600,
            }}>
            <span style={{
              width: '20px', height: '20px', borderRadius: '50%',
              background: step === s.id ? '#fff' : Tv.color.bg.secondary,
              color: step === s.id ? es.indigo : Tv.color.text.tertiary,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 700,
            }}>{s.id}</span>
            {s.label}
          </div>
        ))}
      </div>

      {step === 1 && (
        <div style={es.card}>
          <div style={es.cardH}>Step 1 — Upload Document or Start from Template</div>
          <div style={{ padding: '24px' }}>
            <div style={{ border: `2px dashed ${Tv.color.border.light}`, borderRadius: '10px', padding: '40px', textAlign: 'center' }}>
              <I.Upload size={36} color={es.indigo} strokeWidth={1.25} />
              <div style={{ fontSize: '14px', fontWeight: 700, color: Tv.color.text.primary, marginTop: '12px' }}>Drop files or click to upload</div>
              <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, marginTop: '4px' }}>PDF, DOCX, Pages · up to 25MB per file</div>
              <button style={{ ...es.btnPrimary, marginTop: '16px' }} onClick={() => setStep(2)}><I.Upload size={11} color="#fff" /> Choose File</button>
            </div>
            <div style={{ marginTop: '16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
              {data.templates.slice(0, 6).map(t => (
                <div key={t.id} onClick={() => setStep(2)}
                  style={{ padding: '10px', background: Tv.color.bg.secondary, border: `1px solid ${Tv.color.border.light}`, borderRadius: '8px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <I.Template size={16} color={es.indigo} />
                  <div>
                    <div style={{ fontSize: '11px', fontWeight: 600 }}>{t.name}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{t.uses} uses</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: '16px' }}>
          {/* Field palette + canvas preview */}
          <div style={es.card}>
            <div style={es.cardH}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <I.Sparkle size={14} color={es.indigo} /> AI Auto-Detected Fields
                <span style={{ ...es.tag, background: es.emeraldBg, color: es.emerald }}>12 placed · 94% confidence</span>
              </div>
              <button style={es.btnSecondary}><I.Refresh size={11} color={Tv.color.text.secondary} /> Re-scan</button>
            </div>
            <div style={{ padding: '16px', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '8px' }}>
              {[
                { icon: I.Signature, label: 'Signature', n: 3 },
                { icon: I.Initial, label: 'Initials', n: 4 },
                { icon: I.Calendar, label: 'Date', n: 2 },
                { icon: I.Text, label: 'Text', n: 2 },
                { icon: I.Checkbox, label: 'Checkbox', n: 1 },
              ].map(f => (
                <div key={f.label} style={{ padding: '10px', background: Tv.color.bg.secondary, border: `1px solid ${Tv.color.border.light}`, borderRadius: '6px', textAlign: 'center' }}>
                  <f.icon size={18} color={es.indigo} />
                  <div style={{ fontSize: '11px', fontWeight: 600, marginTop: '4px' }}>{f.label}</div>
                  <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{f.n} placed</div>
                </div>
              ))}
            </div>
            <div style={{ padding: '0 16px 16px' }}>
              <div style={{ height: '280px', background: Tv.color.bg.secondary, borderRadius: '8px', border: `1px solid ${Tv.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: Tv.color.text.tertiary, fontSize: '12px' }}>
                Document Preview · Drag fields to position
              </div>
            </div>
          </div>

          {/* Risk scan sidebar */}
          <div style={es.card}>
            <div style={es.cardH}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <I.Brain size={14} color={es.indigo} /> Clause Risk Scan
              </div>
              <EsRiskPill level="Medium" />
            </div>
            <div style={{ padding: '12px 16px' }}>
              {data.riskScans[0].findings.map((f, i) => (
                <div key={i} style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px', marginBottom: '8px', border: `1px solid ${Tv.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 700, color: Tv.color.text.primary }}>{f.clause}</span>
                    <EsRiskPill level={f.severity} />
                  </div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.secondary, marginBottom: '4px' }}>{f.finding}</div>
                  <div style={{ fontSize: '10px', color: es.indigo, fontStyle: 'italic' }}>→ {f.recommendation}</div>
                </div>
              ))}
              <button style={{ ...es.btnSecondary, width: '100%', justifyContent: 'center', marginTop: '8px' }}><I.Flag size={11} color={Tv.color.text.secondary} /> Escalate to Partner</button>
            </div>
          </div>

          <div style={{ gridColumn: '1 / -1', display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
            <button style={es.btnSecondary} onClick={() => setStep(1)}>Back</button>
            <button style={es.btnPrimary} onClick={() => setStep(3)}>Continue <I.ChevronRight size={11} color="#fff" /></button>
          </div>
        </div>
      )}

      {step === 3 && (
        <div style={es.card}>
          <div style={es.cardH}>Step 3 — Recipients, Routing & Workflow</div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>
              <div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Recipients (in order)</div>
                {[
                  { name: 'David Ashworth', email: 'd.ashworth@meridian.com', role: 'Signer', order: 1 },
                  { name: 'Sarah Redstone', email: 's.redstone@counsel.com', role: 'Signer', order: 2 },
                  { name: 'Robert Chen', email: 'r.chen@counsel.com', role: 'Witness', order: 2 },
                  { name: 'M. Kirkland', email: 'm.kirkland@arbiter.law', role: 'CC', order: null },
                ].map((r, i) => <EsRecipientRow key={i} r={r} />)}
                <button style={{ ...es.btnSecondary, marginTop: '10px' }}><I.UserPlus size={11} color={Tv.color.text.secondary} /> Add Recipient</button>
                <button style={{ ...es.btnSecondary, marginTop: '10px', marginLeft: '6px' }}><I.Witness size={11} color={Tv.color.text.secondary} /> Add Witness</button>
              </div>
              <div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Workflow Auto-Routing</div>
                <div style={{ padding: '12px', background: es.indigoBg, border: `1px solid ${es.indigoBorder}`, borderRadius: '8px', marginBottom: '10px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>
                    <I.Network size={14} color={es.indigo} />
                    <span style={{ fontSize: '12px', fontWeight: 700, color: es.indigo }}>High-Value Contract Approval</span>
                  </div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.secondary }}>Routes contracts &gt; $250K through managing partner before sending</div>
                </div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px', marginTop: '12px' }}>Delegation Check</div>
                <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '11px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
                    <I.Check size={12} color={es.emerald} strokeWidth={2} />
                    <strong>All POAs verified & in effect</strong>
                  </div>
                  <div style={{ color: Tv.color.text.tertiary, fontSize: '10px' }}>Patricia Harmon → Gerald Harmon (Durable POA, valid through)</div>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
              <button style={es.btnSecondary} onClick={() => setStep(2)}>Back</button>
              <button style={es.btnPrimary} onClick={() => setStep(4)}>Continue <I.ChevronRight size={11} color="#fff" /></button>
            </div>
          </div>
        </div>
      )}

      {step === 4 && (
        <div style={es.card}>
          <div style={es.cardH}>Step 4 — ESIGN Consent Ceremony & Send</div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
              <div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>ESIGN Act / UETA Pre-Signature Requirements</div>
                {[
                  { label: 'Consent to electronic signature', done: true },
                  { label: 'Hardware/browser compatibility attestation', done: true },
                  { label: 'Copy of document available for download', done: true },
                  { label: 'Right to withdraw consent explained', done: true },
                  { label: 'Paper option disclosed (cost = $0)', done: true },
                ].map((c, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 0', borderBottom: `1px solid ${Tv.color.border.light}` }}>
                    <I.Check size={14} color={c.done ? es.emerald : Tv.color.text.tertiary} strokeWidth={2} />
                    <span style={{ fontSize: '12px' }}>{c.label}</span>
                  </div>
                ))}
              </div>
              <div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Security & Audit Options</div>
                {[
                  { label: 'Require KBA (knowledge-based auth)', checked: true },
                  { label: 'Require ID verification (driver\'s license)', checked: false },
                  { label: 'Require notary session (RON)', checked: false },
                  { label: 'Enable hash-chain tamper-evidence', checked: true },
                  { label: 'Generate court-ready certificate', checked: true },
                  { label: 'Auto-file to matter on completion', checked: true },
                ].map((o, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 0', borderBottom: `1px solid ${Tv.color.border.light}` }}>
                    <span style={{ width: '14px', height: '14px', borderRadius: '3px', background: o.checked ? es.indigo : Tv.color.bg.secondary, border: `1px solid ${o.checked ? es.indigo : Tv.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      {o.checked && <I.Check size={10} color="#fff" strokeWidth={2.5} />}
                    </span>
                    <span style={{ fontSize: '12px' }}>{o.label}</span>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '20px' }}>
              <button style={es.btnSecondary} onClick={() => setStep(3)}>Back</button>
              <button style={es.btnSecondary}>Save Draft</button>
              <button style={es.btnPrimary}><I.Send size={11} color="#fff" /> Send Envelope</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── TEMPLATES ──────────────────────────────────────────────────────────────────

function EsTemplates() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', marginBottom: '16px' }}>
        <EsMetric label="Templates" value={data.templates.length} />
        <EsMetric label="Published" value={data.templateGovernance.filter(t => t.stage === 'Published').length} delta={`${data.templateGovernance.filter(t => t.stage === 'In Review').length} in review`} deltaColor={es.amber} />
        <EsMetric label="Avg Completion" value="92%" delta="↑ 3% vs last qtr" />
        <EsMetric label="Deprecated" value={data.templateGovernance.filter(t => t.stage === 'Deprecated').length} deltaColor={es.slate} />
      </div>

      <div style={es.card}>
        <div style={es.cardH}>
          <span>Template Library & Governance</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={es.btnSecondary}><I.Filter size={11} color={Tv.color.text.secondary} /> Filter</button>
            <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> New Template</button>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', padding: '16px' }}>
          {data.templateGovernance.map(t => (
            <div key={t.id}
              onClick={() => window.EsOpenBuilder && window.EsOpenBuilder({
                id: t.id, name: t.name, category: t.category,
                pages: (data.templates.find(x => x.name === t.name) || {}).pages || 3,
                fields: (data.templates.find(x => x.name === t.name) || {}).fields || 6,
                requiredFields: (data.templates.find(x => x.name === t.name) || {}).requiredFields || ['signature','date'],
              })}
              onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); window.EsOpenBuilder && window.EsOpenBuilder({ id: t.id, name: t.name, category: t.category, pages: (data.templates.find(x => x.name === t.name) || {}).pages || 3, requiredFields: (data.templates.find(x => x.name === t.name) || {}).requiredFields || ['signature','date'] }); } }}
              role="button" tabIndex={0}
              aria-label={`Open ${t.name} template in builder`}
              onMouseEnter={e => { e.currentTarget.style.borderColor = es.indigo + '66'; e.currentTarget.style.boxShadow = `0 2px 8px ${es.indigo}22`; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = Tv.color.border.light; e.currentTarget.style.boxShadow = 'none'; }}
              style={{ padding: '14px', background: Tv.color.bg.card, border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', cursor: 'pointer', transition: 'border-color 120ms, box-shadow 120ms' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <div style={{ width: '32px', height: '32px', borderRadius: '8px', background: es.indigoBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <I.Template size={16} color={es.indigo} strokeWidth={1.5} />
                  </div>
                  <div>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Tv.color.text.primary }}>{t.name}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{t.category} · v{t.id.slice(-3)}</div>
                  </div>
                </div>
                <EsGovStagePill stage={t.stage} />
              </div>
              <div style={{ fontSize: '11px', color: Tv.color.text.secondary, marginBottom: '10px', minHeight: '30px' }}>{t.description}</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '6px', padding: '8px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                <div>
                  <div style={{ fontSize: '9px', fontWeight: 600, color: Tv.color.text.tertiary, textTransform: 'uppercase' }}>Uses</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tv.color.text.primary }}>{t.uses}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', fontWeight: 600, color: Tv.color.text.tertiary, textTransform: 'uppercase' }}>Complete</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: t.completionRate >= 90 ? es.emerald : t.completionRate >= 80 ? es.amber : es.crimson }}>{t.completionRate ? `${t.completionRate}%` : '—'}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', fontWeight: 600, color: Tv.color.text.tertiary, textTransform: 'uppercase' }}>Time</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tv.color.text.primary }}>{t.avgTimeToSign || '—'}</div>
                </div>
              </div>
              {t.dropOffField && (
                <div style={{ marginTop: '8px', fontSize: '10px', color: es.amber, background: es.amberBg, padding: '4px 8px', borderRadius: '4px' }}>
                  <I.Alert size={10} color={es.amber} /> Drop-off: {t.dropOffField}
                </div>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginTop: '10px', fontSize: '10px', color: Tv.color.text.tertiary }}>
                <I.Lock size={10} color={Tv.color.text.tertiary} /> {t.lockedRegions} locked regions
                {t.approver && <span>· Approved by {t.approver}</span>}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── BULK SEND ──────────────────────────────────────────────────────────────────

function EsBulk() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>
        {data.bulkJobs.map(j => (
          <div key={j.id} style={es.card}>
            <div style={{ padding: '14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 700, color: Tv.color.text.primary }}>{j.name}</div>
                  <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{j.template} · {j.sender}</div>
                </div>
                <EsStatusBadge status={j.status === 'In Progress' ? 'Sent' : j.status} />
              </div>
              {j.sent > 0 && (
                <>
                  <div style={{ display: 'flex', gap: '2px', marginBottom: '8px', height: '6px' }}>
                    <div style={{ flex: j.completed, background: es.emerald, borderRadius: '2px' }} />
                    <div style={{ flex: j.pending, background: es.amber, borderRadius: '2px' }} />
                    <div style={{ flex: j.declined, background: es.crimson, borderRadius: '2px' }} />
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '4px', fontSize: '10px' }}>
                    <div><div style={{ color: Tv.color.text.tertiary, fontSize: '9px', textTransform: 'uppercase' }}>Sent</div><div style={{ fontWeight: 700 }}>{j.sent}</div></div>
                    <div><div style={{ color: es.emerald, fontSize: '9px', textTransform: 'uppercase' }}>Done</div><div style={{ fontWeight: 700, color: es.emerald }}>{j.completed}</div></div>
                    <div><div style={{ color: es.amber, fontSize: '9px', textTransform: 'uppercase' }}>Wait</div><div style={{ fontWeight: 700, color: es.amber }}>{j.pending}</div></div>
                    <div><div style={{ color: es.crimson, fontSize: '9px', textTransform: 'uppercase' }}>Decl</div><div style={{ fontWeight: 700, color: es.crimson }}>{j.declined}</div></div>
                  </div>
                </>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* New bulk wizard */}
      <div style={es.card}>
        <div style={es.cardH}>Create New Bulk Campaign</div>
        <div style={{ padding: '20px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px' }}>
          <div>
            <div style={{ fontSize: '11px', fontWeight: 700, color: es.indigo, textTransform: 'uppercase', marginBottom: '8px' }}>1. Upload CSV & Map Variables</div>
            <div style={{ border: `1px dashed ${Tv.color.border.light}`, borderRadius: '8px', padding: '16px', textAlign: 'center' }}>
              <I.Upload size={20} color={Tv.color.text.tertiary} strokeWidth={1.5} />
              <div style={{ fontSize: '11px', marginTop: '6px' }}>Drop recipients.csv</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginTop: '2px' }}>Mail-merge: {'{{name}}'}, {'{{amount}}'}, etc.</div>
            </div>
            <div style={{ marginTop: '10px', padding: '8px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '10px', color: Tv.color.text.secondary }}>
              <div style={{ fontWeight: 700, marginBottom: '4px' }}>Detected variables</div>
              <div>name · email · amount · due_date · matter_id</div>
            </div>
          </div>
          <div>
            <div style={{ fontSize: '11px', fontWeight: 700, color: es.indigo, textTransform: 'uppercase', marginBottom: '8px' }}>2. Send Window (stagger)</div>
            <div style={{ padding: '12px', background: Tv.color.bg.secondary, borderRadius: '8px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '8px' }}>
                <span>Throughput</span><span style={{ fontWeight: 700 }}>200/hour</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '8px' }}>
                <span>Start</span><span style={{ fontWeight: 700 }}>Mon 9:00 AM PT</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px' }}>
                <span>Est. Complete</span><span style={{ fontWeight: 700 }}>Mon 1:20 PM PT</span>
              </div>
            </div>
            <div style={{ marginTop: '10px', fontSize: '10px', color: Tv.color.text.tertiary }}>Staggered sends avoid spam filtering and allow partial recall if needed.</div>
          </div>
          <div>
            <div style={{ fontSize: '11px', fontWeight: 700, color: es.indigo, textTransform: 'uppercase', marginBottom: '8px' }}>3. Per-Row Failure Handling</div>
            <div style={{ padding: '12px', background: Tv.color.bg.secondary, borderRadius: '8px' }}>
              {[
                { label: 'Invalid email bounces', action: 'Skip + log' },
                { label: 'Missing required variable', action: 'Halt + alert' },
                { label: 'Recipient opt-out flag', action: 'Skip + notify sender' },
                { label: 'Duplicate in 30d', action: 'Skip + flag' },
              ].map((o, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', padding: '4px 0', borderBottom: i < 3 ? `1px solid ${Tv.color.border.light}` : 'none' }}>
                  <span>{o.label}</span><span style={{ color: es.indigo, fontWeight: 600 }}>{o.action}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding: '12px 20px', borderTop: `1px solid ${Tv.color.border.light}`, display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <button style={es.btnSecondary}>Preview 3 Rows</button>
          <button style={es.btnPrimary}><I.Send size={11} color="#fff" /> Schedule Campaign</button>
        </div>
      </div>
    </div>
  );
}

// ── NOTARY (RON / IPEN / Witness) ─────────────────────────────────────────────

function EsNotary() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const s = data.notaryStats;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '10px', marginBottom: '16px' }}>
        <EsMetric label="Sessions (30d)" value={s.sessionsThisMonth} delta={`${s.completed} completed`} />
        <EsMetric label="Scheduled" value={s.scheduled} deltaColor={es.amber} />
        <EsMetric label="Avg Session" value={s.avgSessionTime} />
        <EsMetric label="Commission States" value={s.commissionStates.length} delta={s.commissionStates.join(', ')} deltaColor={es.slate} />
        <div style={es.stat}>
          <div style={es.statLabel}>RON Availability</div>
          <div style={{ ...es.statValue, color: es.emerald, fontSize: '16px', display: 'flex', alignItems: 'center', gap: '6px' }}>
            <I.Check size={14} color={es.emerald} strokeWidth={2.5} /> Live
          </div>
          <div style={es.statDelta}>24/7 notary on-call</div>
        </div>
      </div>

      <div style={es.card}>
        <div style={es.cardH}>
          <span>Notary Sessions</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={es.btnSecondary}><I.Calendar size={11} color={Tv.color.text.secondary} /> Schedule RON</button>
            <button style={es.btnPrimary}><I.Gavel size={12} color="#fff" /> Book Notary</button>
          </div>
        </div>
        {data.notarySessions.map(sess => (
          <div key={sess.id} style={{ borderBottom: `1px solid ${Tv.color.border.light}`, padding: '14px 16px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '10px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                <div style={{ width: '36px', height: '36px', borderRadius: '8px', background: es.violetBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <I.Gavel size={18} color={es.violet} strokeWidth={1.5} />
                </div>
                <div>
                  <div style={{ fontSize: '13px', fontWeight: 700 }}>{sess.subject}</div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>
                    {sess.type} · {new Date(sess.scheduledAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                    {sess.notary && ` · ${sess.notary}`}
                  </div>
                </div>
              </div>
              <span style={{ ...es.tag, background: sess.status === 'Completed' ? es.emeraldBg : sess.status === 'Scheduled' ? es.amberBg : es.slateBg, color: sess.status === 'Completed' ? es.emerald : sess.status === 'Scheduled' ? es.amber : es.slate }}>
                {sess.status}
              </span>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${sess.participants.length}, 1fr)`, gap: '8px' }}>
              {sess.participants.map((p, i) => (
                <div key={i} style={{ padding: '8px 10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 700 }}>{p.name}</span>
                    <span style={{ fontSize: '9px', color: es.indigo, background: es.indigoBg, padding: '1px 6px', borderRadius: '6px' }}>{p.role}</span>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '10px' }}>
                      <I.Fingerprint size={10} color={p.kba === 'Passed' ? es.emerald : p.kba === 'Pending' ? es.amber : Tv.color.text.tertiary} />
                      <span style={{ color: Tv.color.text.secondary }}>KBA: <strong>{p.kba}</strong></span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '10px' }}>
                      <I.IdCard size={10} color={p.id.startsWith('Verified') ? es.emerald : Tv.color.text.tertiary} />
                      <span style={{ color: Tv.color.text.secondary }}>ID: <strong>{p.id}</strong></span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '10px' }}>
                      <I.Webcam size={10} color={p.webcam.includes('Ready') || p.webcam.includes('Recorded') ? es.emerald : Tv.color.text.tertiary} />
                      <span style={{ color: Tv.color.text.secondary }}>A/V: <strong>{p.webcam}</strong></span>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {sess.seal && (
              <div style={{ marginTop: '10px', padding: '10px', background: es.emeraldBg, border: `1px solid ${es.emerald}30`, borderRadius: '6px', fontSize: '11px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontWeight: 700, color: es.emerald, marginBottom: '4px' }}>
                  <I.Seal size={12} color={es.emerald} /> Session Complete · Evidentiary Seal Applied
                </div>
                <div style={{ color: Tv.color.text.secondary, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '8px' }}>
                  <span><strong>Recording:</strong> {sess.recording}</span>
                  <span><strong>Journal:</strong> {sess.journal}</span>
                  <span><strong>Seal:</strong> {sess.seal}</span>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── WORKFLOWS (DAG + Rules + SLA) ─────────────────────────────────────────────

function EsWorkflows() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [selected, setSelected] = useEsV(data.workflows[0]);

  return (
    <div>
      {/* SLA Monitors */}
      <div style={es.card}>
        <div style={es.cardH}>
          <span>Active SLA Monitors</span>
          <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{data.workflowSlaMonitors.length} active</span>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={es.th}>Envelope</th>
              <th style={es.th}>Workflow</th>
              <th style={es.th}>Step</th>
              <th style={es.th}>Due</th>
              <th style={es.th}>Time Left</th>
              <th style={es.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.workflowSlaMonitors.map(s => (
              <tr key={s.id}>
                <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{s.envelope}</td>
                <td style={es.td}>{s.workflow}</td>
                <td style={{ ...es.td, color: Tv.color.text.secondary, fontSize: '11px' }}>{s.step}</td>
                <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{new Date(s.due).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</td>
                <td style={{ ...es.td, fontFamily: Tv.font.mono, fontWeight: 700, color: s.hoursLeft < 0 ? es.crimson : s.hoursLeft < 12 ? es.amber : es.emerald }}>
                  {s.hoursLeft < 0 ? `${Math.abs(s.hoursLeft)}h over` : `${s.hoursLeft}h`}
                </td>
                <td style={es.td}>
                  <span style={{ ...es.tag, background: s.status === 'Breached' ? es.crimsonBg : s.status === 'At Risk' ? es.amberBg : es.emeraldBg, color: s.status === 'Breached' ? es.crimson : s.status === 'At Risk' ? es.amber : es.emerald }}>{s.status}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Workflow list + DAG preview */}
      <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: '16px', marginTop: '16px' }}>
        <div style={es.card}>
          <div style={es.cardH}>
            <span>Workflows</span>
            <button style={es.btnGhost}><I.Plus size={11} color={es.indigo} /> New</button>
          </div>
          {data.workflows.map(w => (
            <div key={w.id} onClick={() => setSelected(w)}
              style={{ padding: '12px 14px', borderBottom: `1px solid ${Tv.color.border.light}`, cursor: 'pointer', background: selected.id === w.id ? es.indigoBg : 'transparent' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                <div style={{ fontSize: '12px', fontWeight: 700 }}>{w.name}</div>
                <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: w.active ? es.emerald : es.slate }} />
              </div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>{w.executions} runs · avg {w.avgSlaHours}h SLA</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.secondary, lineHeight: 1.3 }}>{w.description}</div>
            </div>
          ))}
        </div>

        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <I.Network size={14} color={es.indigo} />
              {selected.name}
            </div>
            <button style={es.btnSecondary}><I.Gear size={11} color={Tv.color.text.secondary} /> Edit</button>
          </div>
          <div style={{ padding: '20px' }}>
            <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, marginBottom: '4px' }}>TRIGGER</div>
            <div style={{ padding: '8px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '12px', marginBottom: '16px' }}>{selected.triggers}</div>

            {/* DAG visualization */}
            <div style={{ padding: '20px 10px', background: Tv.color.bg.secondary, borderRadius: '10px', overflowX: 'auto' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0', minWidth: `${selected.nodes.length * 160}px` }}>
                {selected.nodes.map((n, i) => {
                  const nodeColor = n.type === 'trigger' ? es.indigo : n.type === 'condition' ? es.amber : n.type === 'approver' ? es.violet : n.type === 'parallel' ? es.teal : es.emerald;
                  const nodeBg = n.type === 'trigger' ? es.indigoBg : n.type === 'condition' ? es.amberBg : n.type === 'approver' ? es.violetBg : n.type === 'parallel' ? es.tealBg : es.emeraldBg;
                  return (
                    <React.Fragment key={n.id}>
                      <div style={{ flex: 1, textAlign: 'center' }}>
                        <div style={{ display: 'inline-block', padding: '10px 14px', background: nodeBg, border: `1.5px solid ${nodeColor}50`, borderRadius: '10px', minWidth: '120px' }}>
                          <div style={{ fontSize: '9px', fontWeight: 700, color: nodeColor, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '2px' }}>{n.type}</div>
                          <div style={{ fontSize: '11px', fontWeight: 700, color: Tv.color.text.primary }}>{n.label}</div>
                          {n.sla && <div style={{ fontSize: '9px', color: nodeColor, marginTop: '2px' }}>SLA {n.sla}h</div>}
                        </div>
                      </div>
                      {i < selected.nodes.length - 1 && (
                        <div style={{ width: '24px', height: '2px', background: Tv.color.border.light, position: 'relative' }}>
                          <div style={{ position: 'absolute', right: '-4px', top: '-4px', width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderLeft: `6px solid ${Tv.color.border.light}` }} />
                        </div>
                      )}
                    </React.Fragment>
                  );
                })}
              </div>
            </div>

            <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', margin: '16px 0 8px' }}>Rules</div>
            {selected.rules.map((r, i) => (
              <div key={i} style={{ padding: '8px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', marginBottom: '6px', fontFamily: Tv.font.mono, fontSize: '11px', color: Tv.color.text.secondary, display: 'flex', alignItems: 'center', gap: '8px' }}>
                <I.Branch size={12} color={es.indigo} /> {r}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── INTELLIGENCE (Clause Library + Risk Scanner + AI Training) ────────────────

function EsIntelligence() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const ai = data.aiFieldTraining;

  return (
    <div>
      {/* Top metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', marginBottom: '16px' }}>
        <EsMetric label="Clause Library" value={data.clauseLibrary.length} delta={`${data.clauseLibrary.filter(c => c.status === 'Approved').length} approved`} />
        <EsMetric label="Recent Scans" value={data.riskScans.length} delta={`${data.riskScans.filter(r => r.overallRisk !== 'Low').length} flagged`} deltaColor={es.amber} />
        <EsMetric label="AI Field Accuracy" value={`${ai.accuracy}%`} delta={`↑ ${ai.last30d} corrections (30d)`} />
        <EsMetric label="Total Training" value={ai.totalCorrections.toLocaleString()} delta="corrections ingested" deltaColor={es.slate} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: '16px' }}>
        {/* Clause Library */}
        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Shield size={14} color={es.indigo} /> Clause Library</div>
            <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> Add Clause</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={es.th}>Clause</th>
                <th style={es.th}>Category</th>
                <th style={es.th}>Status</th>
                <th style={es.th}>Uses</th>
                <th style={es.th}>Version</th>
              </tr>
            </thead>
            <tbody>
              {data.clauseLibrary.map(c => (
                <tr key={c.id}>
                  <td style={es.td}>
                    <div style={{ fontSize: '12px', fontWeight: 600 }}>{c.name}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Reviewed {c.lastReviewed} by {c.reviewedBy}</div>
                  </td>
                  <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{c.category}</td>
                  <td style={es.td}>
                    <span style={{ ...es.tag, background: c.status === 'Approved' ? es.emeraldBg : c.status === 'Flagged' ? es.crimsonBg : es.amberBg, color: c.status === 'Approved' ? es.emerald : c.status === 'Flagged' ? es.crimson : es.amber }}>{c.status}</span>
                  </td>
                  <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{c.usage}</td>
                  <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px', color: Tv.color.text.tertiary }}>v{c.version}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Risk Scans + AI Training */}
        <div>
          <div style={es.card}>
            <div style={es.cardH}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Brain size={14} color={es.indigo} /> Recent Risk Scans</div>
            </div>
            {data.riskScans.map(scan => (
              <div key={scan.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tv.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                  <div style={{ fontSize: '12px', fontWeight: 700 }}>{scan.subject}</div>
                  <EsRiskPill level={scan.overallRisk} />
                </div>
                <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>Scanned {new Date(scan.scannedAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })} · {scan.findings.length} findings</div>
                <div style={{ display: 'flex', gap: '4px' }}>
                  {scan.findings.map((f, i) => (
                    <span key={i} style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '6px', background: f.severity === 'High' ? es.crimsonBg : f.severity === 'Medium' ? es.amberBg : es.emeraldBg, color: f.severity === 'High' ? es.crimson : f.severity === 'Medium' ? es.amber : es.emerald }}>
                      {f.severity}: {f.category}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>

          <div style={{ ...es.card, marginTop: '16px' }}>
            <div style={es.cardH}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Sparkle size={14} color={es.indigo} /> AI Field Training</div>
            </div>
            <div style={{ padding: '12px 16px' }}>
              {ai.byField.map(f => (
                <div key={f.field} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '3px' }}>
                    <span style={{ fontWeight: 600 }}>{f.field}</span>
                    <span style={{ fontFamily: Tv.font.mono, fontWeight: 700, color: f.accuracy >= 95 ? es.emerald : f.accuracy >= 90 ? es.amber : es.crimson }}>{f.accuracy}%</span>
                  </div>
                  <div style={{ height: '4px', background: Tv.color.bg.secondary, borderRadius: '2px' }}>
                    <div style={{ height: '100%', width: `${f.accuracy}%`, background: f.accuracy >= 95 ? es.emerald : f.accuracy >= 90 ? es.amber : es.crimson, borderRadius: '2px' }} />
                  </div>
                  <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginTop: '2px' }}>{f.corrections} corrections ingested</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── AUDIT (with Court-Ready Certificate) ──────────────────────────────────────

function EsAudit() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [selected, setSelected] = useEsV(data.envelopes[0]);
  const cert = data.courtCertificates[selected.id];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: '16px' }}>
      <div style={es.card}>
        <div style={es.cardH}>Completed Envelopes</div>
        {data.envelopes.filter(e => e.status === 'Completed').map(env => (
          <div key={env.id} onClick={() => setSelected(env)}
            style={{ padding: '12px 14px', borderBottom: `1px solid ${Tv.color.border.light}`, cursor: 'pointer', background: selected.id === env.id ? es.indigoBg : 'transparent' }}>
            <div style={{ fontSize: '12px', fontWeight: 700, marginBottom: '3px' }}>{env.subject}</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{env.matter} · {new Date(env.completedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</div>
          </div>
        ))}
      </div>

      <div>
        {cert ? (
          <>
            <div style={es.card}>
              <div style={{ ...es.cardH, background: es.indigoBg, borderBottom: `1px solid ${es.indigoBorder}` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: es.indigo }}>
                  <I.Seal size={14} color={es.indigo} /> Court-Ready Certificate of Completion
                </div>
                <button style={es.btnPrimary}><I.Download size={11} color="#fff" /> Download PDF</button>
              </div>
              <div style={{ padding: '16px' }}>
                <div style={{ fontSize: '13px', fontWeight: 700, marginBottom: '4px' }}>{selected.subject}</div>
                <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, marginBottom: '16px' }}>Certificate {cert.id} · Generated {new Date(cert.generatedAt).toLocaleString()}</div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px', marginBottom: '16px' }}>
                  <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: Tv.color.text.tertiary, textTransform: 'uppercase', marginBottom: '3px' }}>SHA-256 Hash</div>
                    <div style={{ fontSize: '11px', fontFamily: Tv.font.mono, wordBreak: 'break-all' }}>{cert.sha256}</div>
                  </div>
                  <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: Tv.color.text.tertiary, textTransform: 'uppercase', marginBottom: '3px' }}>Signing Key</div>
                    <div style={{ fontSize: '11px', fontFamily: Tv.font.mono }}>{cert.signingKeyFingerprint}</div>
                  </div>
                  <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: Tv.color.text.tertiary, textTransform: 'uppercase', marginBottom: '3px' }}>TLS Cipher</div>
                    <div style={{ fontSize: '11px', fontFamily: Tv.font.mono }}>{cert.tlsCipher}</div>
                  </div>
                  <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                    <div style={{ fontSize: '9px', fontWeight: 700, color: Tv.color.text.tertiary, textTransform: 'uppercase', marginBottom: '3px' }}>TOTP Events</div>
                    <div style={{ fontSize: '11px', fontFamily: Tv.font.mono }}>{cert.totpEvents} authenticator challenges</div>
                  </div>
                </div>

                <div style={{ padding: '10px', background: es.emeraldBg, border: `1px solid ${es.emerald}30`, borderRadius: '6px', marginBottom: '16px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
                    <I.Check size={12} color={es.emerald} strokeWidth={2.5} />
                    <span style={{ fontSize: '11px', fontWeight: 700, color: es.emerald }}>Admissibility: {cert.evidentiary.admissibility}</span>
                  </div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.secondary }}>Retention: {cert.evidentiary.retention}</div>
                </div>

                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>
                  <I.Chain size={11} color={es.indigo} /> Tamper-Evident Hash Chain
                </div>
                {cert.hashChain.map(h => (
                  <div key={h.seq} style={{ display: 'grid', gridTemplateColumns: '32px 180px 1fr 100px', gap: '8px', alignItems: 'center', padding: '6px 8px', borderBottom: `1px solid ${Tv.color.border.light}`, fontSize: '11px' }}>
                    <div style={{ fontFamily: Tv.font.mono, fontWeight: 700, color: es.indigo }}>#{h.seq}</div>
                    <div style={{ color: Tv.color.text.tertiary }}>{new Date(h.ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })}</div>
                    <div style={{ fontWeight: 600 }}>{h.event}</div>
                    <div style={{ fontFamily: Tv.font.mono, color: Tv.color.text.tertiary, fontSize: '10px' }}>{h.hash}</div>
                  </div>
                ))}
              </div>
            </div>

            <div style={es.card}>
              <div style={es.cardH}>Event Timeline</div>
              <div style={{ padding: '12px 16px' }}>
                {selected.auditTrail.map((e, i) => (
                  <div key={i} style={{ display: 'flex', gap: '10px', paddingBottom: '10px', marginBottom: '10px', borderBottom: i < selected.auditTrail.length - 1 ? `1px solid ${Tv.color.border.light}` : 'none' }}>
                    <div style={{ width: '6px', height: '6px', borderRadius: '50%', background: es.indigo, marginTop: '5px', flexShrink: 0 }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>
                        <span style={{ fontSize: '12px', fontWeight: 700 }}>{e.event} · {e.actor}</span>
                        <span style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono }}>{new Date(e.ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
                      </div>
                      <div style={{ fontSize: '11px', color: Tv.color.text.secondary }}>{e.detail}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </>
        ) : (
          <div style={es.card}>
            <div style={es.cardH}>Audit Trail</div>
            <div style={{ padding: '16px' }}>
              <div style={{ fontSize: '13px', fontWeight: 700, marginBottom: '8px' }}>{selected.subject}</div>
              {selected.auditTrail.map((e, i) => (
                <div key={i} style={{ padding: '8px 0', borderBottom: `1px solid ${Tv.color.border.light}` }}>
                  <div style={{ fontSize: '12px', fontWeight: 600 }}>{e.event} · {e.actor}</div>
                  <div style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{e.detail}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── INTEGRATIONS (SDK + Webhooks + Apps + Payments) ───────────────────────────

function EsIntegrations() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;

  return (
    <div>
      {/* Connected Apps Grid */}
      <div style={es.card}>
        <div style={es.cardH}>
          <span>Connected Applications</span>
          <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> Browse Marketplace</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', padding: '16px' }}>
          {data.connectedApps.map(a => (
            <div key={a.id} style={{ padding: '14px', border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', background: Tv.color.bg.secondary }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                <div style={{ width: '32px', height: '32px', borderRadius: '8px', background: a.status === 'Connected' ? es.emeraldBg : es.slateBg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: a.status === 'Connected' ? es.emerald : es.slate, fontWeight: 700, fontSize: '12px' }}>
                  {a.name.slice(0, 2).toUpperCase()}
                </div>
                <span style={{ ...es.tag, background: a.status === 'Connected' ? es.emeraldBg : es.slateBg, color: a.status === 'Connected' ? es.emerald : es.slate }}>{a.status}</span>
              </div>
              <div style={{ fontSize: '12px', fontWeight: 700, marginBottom: '2px' }}>{a.name}</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>{a.category}</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.secondary, lineHeight: 1.3 }}>{a.description}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '16px', marginTop: '16px' }}>
        {/* Webhooks */}
        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Webhook size={14} color={es.indigo} /> Webhooks</div>
            <button style={es.btnGhost}><I.Plus size={11} color={es.indigo} /> New</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={es.th}>Name</th>
                <th style={es.th}>Events</th>
                <th style={es.th}>Status</th>
                <th style={es.th}>Last Fired</th>
              </tr>
            </thead>
            <tbody>
              {data.webhooks.map(w => (
                <tr key={w.id}>
                  <td style={es.td}>
                    <div style={{ fontSize: '12px', fontWeight: 600 }}>{w.name}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '240px' }}>{w.url}</div>
                  </td>
                  <td style={{ ...es.td, fontSize: '10px' }}>
                    {w.events.map(e => (
                      <span key={e} style={{ display: 'inline-block', background: Tv.color.bg.secondary, padding: '1px 6px', borderRadius: '4px', marginRight: '3px', fontFamily: Tv.font.mono }}>{e}</span>
                    ))}
                  </td>
                  <td style={es.td}>
                    <span style={{ ...es.tag, background: w.active ? es.emeraldBg : es.slateBg, color: w.active ? es.emerald : es.slate }}>
                      {w.active ? 'Active' : 'Paused'}
                    </span>
                    {w.failures > 0 && <div style={{ fontSize: '10px', color: es.crimson, marginTop: '2px' }}>{w.failures} failures</div>}
                  </td>
                  <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{new Date(w.lastFired).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* SDK Keys */}
        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Code size={14} color={es.indigo} /> SDK & API Keys</div>
            <button style={es.btnGhost}><I.Plus size={11} color={es.indigo} /> New Key</button>
          </div>
          {data.sdkKeys.map(k => (
            <div key={k.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tv.color.border.light}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                <div style={{ fontSize: '12px', fontWeight: 700 }}>{k.name}</div>
                <span style={{ ...es.tag, background: es.indigoBg, color: es.indigo }}>{k.type}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '4px' }}>
                <span>Scope: {k.scope}</span>
                <span>{k.requests30d.toLocaleString()} req/30d</span>
              </div>
              <div style={{ fontFamily: Tv.font.mono, fontSize: '10px', color: Tv.color.text.tertiary, background: Tv.color.bg.secondary, padding: '4px 8px', borderRadius: '4px' }}>
                sk_live_{k.id.toLowerCase()}_••••••••••••••
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Payments */}
      <div style={{ ...es.card, marginTop: '16px' }}>
        <div style={es.cardH}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Payment size={14} color={es.indigo} /> Payment-on-Signature</div>
          <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>Via LawPay + Stripe</span>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={es.th}>Envelope</th>
              <th style={es.th}>Client</th>
              <th style={es.th}>Amount</th>
              <th style={es.th}>Method</th>
              <th style={es.th}>Status</th>
              <th style={es.th}>Captured</th>
            </tr>
          </thead>
          <tbody>
            {data.payments.map(p => (
              <tr key={p.id}>
                <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{p.envelopeId}</td>
                <td style={es.td}>{p.client}</td>
                <td style={{ ...es.td, fontFamily: Tv.font.mono, fontWeight: 700 }}>{p.amount}</td>
                <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{p.method}</td>
                <td style={es.td}>
                  <span style={{ ...es.tag, background: p.status === 'Captured' ? es.emeraldBg : p.status === 'Authorization Hold' ? es.amberBg : es.slateBg, color: p.status === 'Captured' ? es.emerald : p.status === 'Authorization Hold' ? es.amber : es.slate }}>{p.status}</span>
                </td>
                <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{p.capturedAt ? new Date(p.capturedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── COMPLIANCE (Posture + Vault + Delegations) ────────────────────────────────

function EsCompliance() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const v = data.vaultSettings;

  return (
    <div>
      {/* Posture Dashboard */}
      <div style={es.card}>
        <div style={es.cardH}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Scale size={14} color={es.indigo} /> Compliance Posture</div>
          <button style={es.btnSecondary}><I.Download size={11} color={Tv.color.text.secondary} /> Export Report</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', padding: '16px' }}>
          {data.compliancePosture.map(c => (
            <div key={c.id} style={{ padding: '12px', border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', background: Tv.color.bg.card }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
                <div style={{ fontSize: '12px', fontWeight: 700 }}>{c.framework}</div>
                <span style={{ ...es.tag, background: c.status === 'Certified' || c.status === 'Qualified' ? es.indigoBg : es.emeraldBg, color: c.status === 'Certified' || c.status === 'Qualified' ? es.indigo : es.emerald }}>{c.status}</span>
              </div>
              <div style={{ fontSize: '22px', fontWeight: 700, letterSpacing: '-0.02em', color: c.score === 100 ? es.emerald : c.score >= 95 ? es.amber : es.crimson }}>{c.score}%</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '8px' }}>{c.controls} controls · {c.findings} finding{c.findings !== 1 ? 's' : ''}</div>
              <div style={{ height: '4px', background: Tv.color.bg.secondary, borderRadius: '2px', marginBottom: '6px' }}>
                <div style={{ height: '100%', width: `${c.score}%`, background: c.score === 100 ? es.emerald : c.score >= 95 ? es.amber : es.crimson, borderRadius: '2px' }} />
              </div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Renewal: {c.renewal}</div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginTop: '16px' }}>
        {/* Zero-Knowledge Vault */}
        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Key size={14} color={es.indigo} /> Zero-Knowledge Envelope Vault</div>
            <span style={{ ...es.tag, background: es.emeraldBg, color: es.emerald }}>Enabled</span>
          </div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px', marginBottom: '14px' }}>
              <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                <div style={es.statLabel}>Matter KEKs</div>
                <div style={es.statValue}>{v.matterKeks}</div>
                <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Key Vault · HSM-backed</div>
              </div>
              <div style={{ padding: '10px', background: Tv.color.bg.secondary, borderRadius: '6px' }}>
                <div style={es.statLabel}>Zero-Know Matters</div>
                <div style={es.statValue}>{v.zeroKnowledgeMatters.length}</div>
                <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{v.zeroKnowledgeMatters.join(', ')}</div>
              </div>
            </div>
            <div style={{ padding: '10px', background: es.indigoBg, border: `1px solid ${es.indigoBorder}`, borderRadius: '6px', marginBottom: '14px', fontSize: '11px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontWeight: 700, color: es.indigo, marginBottom: '3px' }}>
                <I.Refresh size={11} color={es.indigo} /> Key Rotation
              </div>
              {v.keyRotation}
            </div>
            <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Break-Glass Events</div>
            {v.breakGlassEvents.map((e, i) => (
              <div key={i} style={{ padding: '8px 10px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '11px', marginBottom: '6px' }}>
                <div style={{ fontWeight: 700, marginBottom: '2px' }}>{e.actor} · {e.matter}</div>
                <div style={{ color: Tv.color.text.secondary, marginBottom: '2px' }}>{e.reason}</div>
                <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Approved by {e.approvedBy} · {new Date(e.ts).toLocaleString()}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Delegated Signing Authority */}
        <div style={es.card}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Witness size={14} color={es.indigo} /> Delegated Signing Authority</div>
            <button style={es.btnGhost}><I.Plus size={11} color={es.indigo} /> Add POA</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={es.th}>From / To</th>
                <th style={es.th}>Basis</th>
                <th style={es.th}>Effective</th>
                <th style={es.th}>Status</th>
              </tr>
            </thead>
            <tbody>
              {data.delegations.map(d => (
                <tr key={d.id}>
                  <td style={es.td}>
                    <div style={{ fontSize: '11px', fontWeight: 700 }}>{d.from} → {d.to}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{d.scope}</div>
                  </td>
                  <td style={{ ...es.td, fontSize: '11px' }}>
                    <div>{d.basis}</div>
                    <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono }}>{d.docRef}</div>
                  </td>
                  <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>
                    {d.effective}
                    {d.expires && <div style={{ fontSize: '10px' }}>→ {d.expires}</div>}
                  </td>
                  <td style={es.td}>
                    <span style={{ ...es.tag, background: d.status === 'Active' ? es.emeraldBg : es.crimsonBg, color: d.status === 'Active' ? es.emerald : es.crimson }}>{d.status}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── CONTACTS ───────────────────────────────────────────────────────────────────

function EsContacts() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;

  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <span>Signer Contacts</span>
        <div style={{ display: 'flex', gap: '6px' }}>
          <button style={es.btnSecondary}><I.Search size={11} color={Tv.color.text.secondary} /> Search</button>
          <button style={es.btnPrimary}><I.UserPlus size={12} color="#fff" /> Add Contact</button>
        </div>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>Name</th>
            <th style={es.th}>Organization</th>
            <th style={es.th}>Role</th>
            <th style={es.th}>Envelopes</th>
            <th style={es.th}>Delegation</th>
            <th style={es.th}>Last Signed</th>
          </tr>
        </thead>
        <tbody>
          {data.contacts.map(c => {
            const del = data.delegations.find(d => d.from === c.name || d.to === c.name);
            return (
              <tr key={c.id}>
                <td style={es.td}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <div style={{ width: '30px', height: '30px', borderRadius: '50%', background: es.indigoBg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, color: es.indigo }}>
                      {c.name.split(' ').map(w => w[0]).join('').slice(0, 2)}
                    </div>
                    <div>
                      <div style={{ fontSize: '12px', fontWeight: 600 }}>{c.name}</div>
                      <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>{c.email}</div>
                    </div>
                  </div>
                </td>
                <td style={{ ...es.td, fontSize: '11px' }}>{c.org}</td>
                <td style={es.td}><span style={{ ...es.tag, background: es.slateBg, color: es.slate }}>{c.role}</span></td>
                <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{c.envelopes}</td>
                <td style={{ ...es.td, fontSize: '11px' }}>
                  {del ? (
                    <span style={{ ...es.tag, background: del.status === 'Active' ? es.emeraldBg : es.crimsonBg, color: del.status === 'Active' ? es.emerald : es.crimson }}>{del.basis}</span>
                  ) : <span style={{ color: Tv.color.text.tertiary }}>—</span>}
                </td>
                <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{c.lastSigned}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ── ANALYTICS ──────────────────────────────────────────────────────────────────

function EsAnalytics() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const a = data.analytics;
  const maxSent = Math.max(...a.monthly.map(m => m.sent));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', marginBottom: '16px' }}>
        <EsMetric label="This Month" value={a.envelopesThisMonth} delta={`${a.completedThisMonth} completed`} />
        <EsMetric label="Completion Rate" value={`${a.completionRate}%`} delta="↑ 3% vs Mar" />
        <EsMetric label="Avg Turnaround" value={a.avgTurnaround} delta="↓ 2.1h vs Mar" />
        <EsMetric label="Decline Rate" value={`${a.declinedRate}%`} delta="within target" deltaColor={es.slate} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '16px' }}>
        <div style={es.card}>
          <div style={es.cardH}>
            <span>Envelope Volume (6 months)</span>
            <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>Sent vs Completed</span>
          </div>
          <div style={{ padding: '20px' }}>
            <div style={{ display: 'flex', gap: '12px', alignItems: 'flex-end', height: '220px' }}>
              {a.monthly.map(m => (
                <div key={m.month} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '6px' }}>
                  <div style={{ width: '100%', display: 'flex', gap: '3px', alignItems: 'flex-end', height: '180px' }}>
                    <div style={{ flex: 1, background: es.indigoBorder, height: `${(m.sent / maxSent) * 100}%`, borderRadius: '3px 3px 0 0' }} title={`Sent ${m.sent}`} />
                    <div style={{ flex: 1, background: es.emerald, height: `${(m.completed / maxSent) * 100}%`, borderRadius: '3px 3px 0 0' }} title={`Completed ${m.completed}`} />
                  </div>
                  <div style={{ fontSize: '11px', fontWeight: 700 }}>{m.month}</div>
                  <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono }}>{m.sent} / {m.completed}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div>
          <div style={es.card}>
            <div style={es.cardH}>Top Templates</div>
            <div style={{ padding: '12px 16px' }}>
              {data.templates.slice(0, 5).sort((a, b) => b.uses - a.uses).map((t, i) => (
                <div key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderBottom: i < 4 ? `1px solid ${Tv.color.border.light}` : 'none' }}>
                  <div style={{ fontSize: '12px', fontWeight: 600 }}>{t.name}</div>
                  <div style={{ fontSize: '12px', fontFamily: Tv.font.mono, fontWeight: 700, color: es.indigo }}>{t.uses}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ ...es.card, marginTop: '16px' }}>
            <div style={es.cardH}>Status Breakdown</div>
            <div style={{ padding: '12px 16px' }}>
              {['Completed', 'Waiting', 'Sent', 'Declined', 'Expired'].map(status => {
                const count = data.envelopes.filter(e => e.status === status).length;
                const s = es.envelopeStatus(status);
                return (
                  <div key={status} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 0' }}>
                    <I.Dot size={8} color={s.color} />
                    <span style={{ fontSize: '11px', flex: 1 }}>{status}</span>
                    <span style={{ fontSize: '11px', fontFamily: Tv.font.mono, fontWeight: 700 }}>{count}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Pill Sub-Nav (shared across all SignDesk sub-platforms) ───────────────────

function EsSubNav({ views, active, onChange }) {
  const es = window.__es;
  return (
    <div style={{
      display: 'flex', gap: '4px', padding: '6px',
      background: Tv.color.bg.secondary,
      border: `1px solid ${Tv.color.border.light}`,
      borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap',
    }}>
      {views.map(v => {
        const isActive = active === v.id;
        return (
          <button key={v.id} onClick={() => onChange(v.id)} style={{
            padding: '6px 12px', fontSize: '11px', fontWeight: isActive ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: isActive ? es.indigo : 'transparent',
            color: isActive ? '#fff' : Tv.color.text.secondary,
            fontFamily: Tv.font.family, transition: 'all .15s',
            whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: '6px',
          }}>
            {v.icon && <v.icon size={11} color={isActive ? '#fff' : Tv.color.text.tertiary} strokeWidth={1.75} />}
            {v.label}
            {v.badge != null && (
              <span style={{
                fontSize: '9px', fontWeight: 700, padding: '1px 5px', borderRadius: '6px',
                background: isActive ? 'rgba(255,255,255,0.2)' : es.indigoBg,
                color: isActive ? '#fff' : es.indigo,
                fontFamily: Tv.font.mono,
              }}>{v.badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ── WORKFLOWS — split sub-views ───────────────────────────────────────────────

function EsWorkflowsMonitors() {
  const es = window.__es;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <span>Active SLA Monitors</span>
        <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>{data.workflowSlaMonitors.length} active · {data.workflowSlaMonitors.filter(s => s.status === 'Breached').length} breached</span>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>Envelope</th><th style={es.th}>Workflow</th>
            <th style={es.th}>Step</th><th style={es.th}>Due</th>
            <th style={es.th}>Time Left</th><th style={es.th}>Status</th>
          </tr>
        </thead>
        <tbody>
          {data.workflowSlaMonitors.map(s => (
            <tr key={s.id}>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{s.envelope}</td>
              <td style={es.td}>{s.workflow}</td>
              <td style={{ ...es.td, color: Tv.color.text.secondary, fontSize: '11px' }}>{s.step}</td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{new Date(s.due).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</td>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontWeight: 700, color: s.hoursLeft < 0 ? es.crimson : s.hoursLeft < 12 ? es.amber : es.emerald }}>
                {s.hoursLeft < 0 ? `${Math.abs(s.hoursLeft)}h over` : `${s.hoursLeft}h`}
              </td>
              <td style={es.td}>
                <span style={{ ...es.tag, background: s.status === 'Breached' ? es.crimsonBg : s.status === 'At Risk' ? es.amberBg : es.emeraldBg, color: s.status === 'Breached' ? es.crimson : s.status === 'At Risk' ? es.amber : es.emerald }}>{s.status}</span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function EsWorkflowsDesigner() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const [selected, setSelected] = useEsV(data.workflows[0]);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: '16px' }}>
      <div style={es.card}>
        <div style={es.cardH}>
          <span>Workflows</span>
          <button style={es.btnGhost}><I.Plus size={11} color={es.indigo} /> New</button>
        </div>
        {data.workflows.map(w => (
          <div key={w.id} onClick={() => setSelected(w)}
            style={{ padding: '12px 14px', borderBottom: `1px solid ${Tv.color.border.light}`, cursor: 'pointer', background: selected.id === w.id ? es.indigoBg : 'transparent' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
              <div style={{ fontSize: '12px', fontWeight: 700 }}>{w.name}</div>
              <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: w.active ? es.emerald : es.slate }} />
            </div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>{w.executions} runs · avg {w.avgSlaHours}h SLA</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.secondary, lineHeight: 1.3 }}>{w.description}</div>
          </div>
        ))}
      </div>

      <div style={es.card}>
        <div style={es.cardH}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <I.Network size={14} color={es.indigo} /> {selected.name}
          </div>
          <button style={es.btnSecondary}><I.Gear size={11} color={Tv.color.text.secondary} /> Edit</button>
        </div>
        <div style={{ padding: '20px' }}>
          <div style={{ fontSize: '11px', color: Tv.color.text.tertiary, marginBottom: '4px' }}>TRIGGER</div>
          <div style={{ padding: '8px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '12px', marginBottom: '16px' }}>{selected.triggers}</div>
          <div style={{ padding: '20px 10px', background: Tv.color.bg.secondary, borderRadius: '10px', overflowX: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0', minWidth: `${selected.nodes.length * 160}px` }}>
              {selected.nodes.map((n, i) => {
                const nodeColor = n.type === 'trigger' ? es.indigo : n.type === 'condition' ? es.amber : n.type === 'approver' ? es.violet : n.type === 'parallel' ? es.teal : es.emerald;
                const nodeBg = n.type === 'trigger' ? es.indigoBg : n.type === 'condition' ? es.amberBg : n.type === 'approver' ? es.violetBg : n.type === 'parallel' ? es.tealBg : es.emeraldBg;
                return (
                  <React.Fragment key={n.id}>
                    <div style={{ flex: 1, textAlign: 'center' }}>
                      <div style={{ display: 'inline-block', padding: '10px 14px', background: nodeBg, border: `1.5px solid ${nodeColor}50`, borderRadius: '10px', minWidth: '120px' }}>
                        <div style={{ fontSize: '9px', fontWeight: 700, color: nodeColor, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '2px' }}>{n.type}</div>
                        <div style={{ fontSize: '11px', fontWeight: 700, color: Tv.color.text.primary }}>{n.label}</div>
                        {n.sla && <div style={{ fontSize: '9px', color: nodeColor, marginTop: '2px' }}>SLA {n.sla}h</div>}
                      </div>
                    </div>
                    {i < selected.nodes.length - 1 && (
                      <div style={{ width: '24px', height: '2px', background: Tv.color.border.light, position: 'relative' }}>
                        <div style={{ position: 'absolute', right: '-4px', top: '-4px', width: 0, height: 0, borderTop: '5px solid transparent', borderBottom: '5px solid transparent', borderLeft: `6px solid ${Tv.color.border.light}` }} />
                      </div>
                    )}
                  </React.Fragment>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function EsWorkflowsRules() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  const allRules = data.workflows.flatMap(w => w.rules.map(r => ({ rule: r, workflow: w.name, active: w.active })));
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Branch size={14} color={es.indigo} /> Routing Rules</div>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> New Rule</button>
      </div>
      <div style={{ padding: '16px' }}>
        {allRules.map((r, i) => (
          <div key={i} style={{ padding: '12px', background: Tv.color.bg.secondary, borderRadius: '8px', marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '12px' }}>
            <div style={{ width: '28px', height: '28px', borderRadius: '6px', background: r.active ? es.emeraldBg : es.slateBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <I.Branch size={14} color={r.active ? es.emerald : es.slate} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: Tv.font.mono, fontSize: '11px', color: Tv.color.text.primary, marginBottom: '3px' }}>{r.rule}</div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Workflow: <strong>{r.workflow}</strong></div>
            </div>
            <span style={{ ...es.tag, background: r.active ? es.emeraldBg : es.slateBg, color: r.active ? es.emerald : es.slate }}>{r.active ? 'Active' : 'Paused'}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── INTELLIGENCE — split sub-views ────────────────────────────────────────────

function EsIntelClauses() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Shield size={14} color={es.indigo} /> Clause Library</div>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> Add Clause</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>Clause</th><th style={es.th}>Category</th>
            <th style={es.th}>Status</th><th style={es.th}>Uses</th>
            <th style={es.th}>Version</th><th style={es.th}>Last Reviewed</th>
          </tr>
        </thead>
        <tbody>
          {data.clauseLibrary.map(c => (
            <tr key={c.id}>
              <td style={es.td}><div style={{ fontSize: '12px', fontWeight: 600 }}>{c.name}</div></td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{c.category}</td>
              <td style={es.td}>
                <span style={{ ...es.tag, background: c.status === 'Approved' ? es.emeraldBg : c.status === 'Flagged' ? es.crimsonBg : es.amberBg, color: c.status === 'Approved' ? es.emerald : c.status === 'Flagged' ? es.crimson : es.amber }}>{c.status}</span>
              </td>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{c.usage}</td>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px', color: Tv.color.text.tertiary }}>v{c.version}</td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{c.lastReviewed} · {c.reviewedBy}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function EsIntelScans() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div>
      {data.riskScans.map(scan => (
        <div key={scan.id} style={{ ...es.card }}>
          <div style={es.cardH}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <I.Brain size={14} color={es.indigo} /> {scan.subject}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Scanned {new Date(scan.scannedAt).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
              <EsRiskPill level={scan.overallRisk} />
            </div>
          </div>
          <div style={{ padding: '12px 16px' }}>
            {scan.findings.map((f, i) => (
              <div key={i} style={{ padding: '10px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', marginBottom: '6px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                  <span style={{ fontSize: '11px', fontWeight: 700 }}>{f.clause} <span style={{ fontWeight: 400, color: Tv.color.text.tertiary }}>· {f.category}</span></span>
                  <EsRiskPill level={f.severity} />
                </div>
                <div style={{ fontSize: '11px', color: Tv.color.text.secondary, marginBottom: '3px' }}>{f.finding}</div>
                <div style={{ fontSize: '11px', color: es.indigo, fontStyle: 'italic' }}>→ {f.recommendation}</div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function EsIntelTraining() {
  const es = window.__es;
  const I = window.EsIcons;
  const ai = window.ESIGN_DATA.aiFieldTraining;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', alignContent: 'flex-start' }}>
        <EsMetric label="Overall Accuracy" value={`${ai.accuracy}%`} delta="↑ 2.1% (30d)" />
        <EsMetric label="Total Corrections" value={ai.totalCorrections.toLocaleString()} delta="ingested all-time" deltaColor={es.slate} />
        <EsMetric label="Last 30 Days" value={ai.last30d} delta="new corrections" />
        <EsMetric label="Retraining" value="Nightly" delta="next 02:00 UTC" deltaColor={es.slate} />
      </div>
      <div style={es.card}>
        <div style={es.cardH}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Sparkle size={14} color={es.indigo} /> Per-Field Accuracy</div>
        </div>
        <div style={{ padding: '14px 16px' }}>
          {ai.byField.map(f => (
            <div key={f.field} style={{ marginBottom: '14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                <span style={{ fontWeight: 600 }}>{f.field}</span>
                <span style={{ fontFamily: Tv.font.mono, fontWeight: 700, color: f.accuracy >= 95 ? es.emerald : f.accuracy >= 90 ? es.amber : es.crimson }}>{f.accuracy}%</span>
              </div>
              <div style={{ height: '5px', background: Tv.color.bg.secondary, borderRadius: '2px' }}>
                <div style={{ height: '100%', width: `${f.accuracy}%`, background: f.accuracy >= 95 ? es.emerald : f.accuracy >= 90 ? es.amber : es.crimson, borderRadius: '2px' }} />
              </div>
              <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginTop: '2px' }}>{f.corrections} corrections ingested</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── COMPLIANCE — split sub-views ──────────────────────────────────────────────

function EsCompPosture() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Scale size={14} color={es.indigo} /> Compliance Posture</div>
        <button style={es.btnSecondary}><I.Download size={11} color={Tv.color.text.secondary} /> Export Report</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', padding: '16px' }}>
        {data.compliancePosture.map(c => (
          <div key={c.id} style={{ padding: '14px', border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', background: Tv.color.bg.card }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '10px' }}>
              <div style={{ fontSize: '12px', fontWeight: 700 }}>{c.framework}</div>
              <span style={{ ...es.tag, background: c.status === 'Certified' || c.status === 'Qualified' ? es.indigoBg : es.emeraldBg, color: c.status === 'Certified' || c.status === 'Qualified' ? es.indigo : es.emerald }}>{c.status}</span>
            </div>
            <div style={{ fontSize: '22px', fontWeight: 700, letterSpacing: '-0.02em', color: c.score === 100 ? es.emerald : c.score >= 95 ? es.amber : es.crimson }}>{c.score}%</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '8px' }}>{c.controls} controls · {c.findings} finding{c.findings !== 1 ? 's' : ''}</div>
            <div style={{ height: '4px', background: Tv.color.bg.secondary, borderRadius: '2px', marginBottom: '6px' }}>
              <div style={{ height: '100%', width: `${c.score}%`, background: c.score === 100 ? es.emerald : c.score >= 95 ? es.amber : es.crimson, borderRadius: '2px' }} />
            </div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Renewal: {c.renewal}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function EsCompVault() {
  const es = window.__es;
  const I = window.EsIcons;
  const v = window.ESIGN_DATA.vaultSettings;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Key size={14} color={es.indigo} /> Zero-Knowledge Envelope Vault</div>
        <span style={{ ...es.tag, background: es.emeraldBg, color: es.emerald }}>Enabled</span>
      </div>
      <div style={{ padding: '16px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px', marginBottom: '16px' }}>
          <EsMetric label="Matter KEKs" value={v.matterKeks} delta="HSM-backed · Key Vault" deltaColor={es.slate} />
          <EsMetric label="Zero-Knowledge Matters" value={v.zeroKnowledgeMatters.length} delta={v.zeroKnowledgeMatters.join(', ')} deltaColor={es.slate} />
          <EsMetric label="Key Rotation" value="90d" delta="next 2026-06-15" deltaColor={es.slate} />
        </div>
        <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '8px' }}>Break-Glass Events</div>
        {v.breakGlassEvents.map((e, i) => (
          <div key={i} style={{ padding: '10px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '11px', marginBottom: '6px' }}>
            <div style={{ fontWeight: 700, marginBottom: '2px' }}>{e.actor} · {e.matter}</div>
            <div style={{ color: Tv.color.text.secondary, marginBottom: '2px' }}>{e.reason}</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary }}>Approved by {e.approvedBy} · {new Date(e.ts).toLocaleString()}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function EsCompDelegations() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Witness size={14} color={es.indigo} /> Delegated Signing Authority</div>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> Add POA</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>From / To</th><th style={es.th}>Scope</th>
            <th style={es.th}>Basis</th><th style={es.th}>Effective</th>
            <th style={es.th}>Expires</th><th style={es.th}>Status</th>
          </tr>
        </thead>
        <tbody>
          {data.delegations.map(d => (
            <tr key={d.id}>
              <td style={es.td}>
                <div style={{ fontSize: '12px', fontWeight: 700 }}>{d.from} → {d.to}</div>
                <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, fontFamily: Tv.font.mono }}>{d.docRef}</div>
              </td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{d.scope}</td>
              <td style={{ ...es.td, fontSize: '11px' }}>{d.basis}</td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{d.effective}</td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{d.expires || '—'}</td>
              <td style={es.td}>
                <span style={{ ...es.tag, background: d.status === 'Active' ? es.emeraldBg : es.crimsonBg, color: d.status === 'Active' ? es.emerald : es.crimson }}>{d.status}</span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ── INTEGRATIONS — split sub-views ────────────────────────────────────────────

function EsIntegApps() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <span>Connected Applications</span>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> Browse Marketplace</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', padding: '16px' }}>
        {data.connectedApps.map(a => (
          <div key={a.id} style={{ padding: '14px', border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', background: Tv.color.bg.secondary }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
              <div style={{ width: '32px', height: '32px', borderRadius: '8px', background: a.status === 'Connected' ? es.emeraldBg : es.slateBg, display: 'flex', alignItems: 'center', justifyContent: 'center', color: a.status === 'Connected' ? es.emerald : es.slate, fontWeight: 700, fontSize: '12px' }}>
                {a.name.slice(0, 2).toUpperCase()}
              </div>
              <span style={{ ...es.tag, background: a.status === 'Connected' ? es.emeraldBg : es.slateBg, color: a.status === 'Connected' ? es.emerald : es.slate }}>{a.status}</span>
            </div>
            <div style={{ fontSize: '12px', fontWeight: 700, marginBottom: '2px' }}>{a.name}</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>{a.category}</div>
            <div style={{ fontSize: '10px', color: Tv.color.text.secondary, lineHeight: 1.3 }}>{a.description}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function EsIntegWebhooks() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Webhook size={14} color={es.indigo} /> Webhooks</div>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> New Webhook</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>Name</th><th style={es.th}>Endpoint</th>
            <th style={es.th}>Events</th><th style={es.th}>Status</th>
            <th style={es.th}>Last Fired</th>
          </tr>
        </thead>
        <tbody>
          {data.webhooks.map(w => (
            <tr key={w.id}>
              <td style={{ ...es.td, fontSize: '12px', fontWeight: 600 }}>{w.name}</td>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '10px', color: Tv.color.text.tertiary, maxWidth: '260px' }}>
                <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.url}</div>
              </td>
              <td style={{ ...es.td, fontSize: '10px' }}>
                {w.events.map(e => (
                  <span key={e} style={{ display: 'inline-block', background: Tv.color.bg.secondary, padding: '1px 6px', borderRadius: '4px', marginRight: '3px', fontFamily: Tv.font.mono }}>{e}</span>
                ))}
              </td>
              <td style={es.td}>
                <span style={{ ...es.tag, background: w.active ? es.emeraldBg : es.slateBg, color: w.active ? es.emerald : es.slate }}>{w.active ? 'Active' : 'Paused'}</span>
                {w.failures > 0 && <div style={{ fontSize: '10px', color: es.crimson, marginTop: '2px' }}>{w.failures} failures</div>}
              </td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{new Date(w.lastFired).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function EsIntegSdk() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Code size={14} color={es.indigo} /> SDK & API Keys</div>
        <button style={es.btnPrimary}><I.Plus size={12} color="#fff" /> New Key</button>
      </div>
      <div style={{ padding: '16px', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '10px' }}>
        {data.sdkKeys.map(k => (
          <div key={k.id} style={{ padding: '14px', border: `1px solid ${Tv.color.border.light}`, borderRadius: '10px', background: Tv.color.bg.secondary }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
              <div style={{ fontSize: '12px', fontWeight: 700 }}>{k.name}</div>
              <span style={{ ...es.tag, background: es.indigoBg, color: es.indigo }}>{k.type}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tv.color.text.tertiary, marginBottom: '6px' }}>
              <span>Scope: {k.scope}</span>
              <span>{k.requests30d.toLocaleString()} req/30d</span>
            </div>
            <div style={{ fontFamily: Tv.font.mono, fontSize: '10px', color: Tv.color.text.secondary, background: Tv.color.bg.card, padding: '6px 10px', borderRadius: '4px', border: `1px solid ${Tv.color.border.light}` }}>
              sk_live_{k.id.toLowerCase()}_••••••••••••••
            </div>
            <div style={{ fontSize: '10px', color: Tv.color.text.tertiary, marginTop: '6px' }}>Created {k.created} · Last used {k.lastUsed}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function EsIntegPayments() {
  const es = window.__es;
  const I = window.EsIcons;
  const data = window.ESIGN_DATA;
  return (
    <div style={es.card}>
      <div style={es.cardH}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><I.Payment size={14} color={es.indigo} /> Payment-on-Signature</div>
        <span style={{ fontSize: '11px', color: Tv.color.text.tertiary }}>LawPay + Stripe</span>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={es.th}>Envelope</th><th style={es.th}>Client</th>
            <th style={es.th}>Amount</th><th style={es.th}>Method</th>
            <th style={es.th}>Status</th><th style={es.th}>Captured</th>
          </tr>
        </thead>
        <tbody>
          {data.payments.map(p => (
            <tr key={p.id}>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontSize: '11px' }}>{p.envelopeId}</td>
              <td style={es.td}>{p.client}</td>
              <td style={{ ...es.td, fontFamily: Tv.font.mono, fontWeight: 700 }}>{p.amount}</td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.secondary }}>{p.method}</td>
              <td style={es.td}>
                <span style={{ ...es.tag, background: p.status === 'Captured' ? es.emeraldBg : p.status === 'Authorization Hold' ? es.amberBg : es.slateBg, color: p.status === 'Captured' ? es.emerald : p.status === 'Authorization Hold' ? es.amber : es.slate }}>{p.status}</span>
              </td>
              <td style={{ ...es.td, fontSize: '11px', color: Tv.color.text.tertiary }}>{p.capturedAt ? new Date(p.capturedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '—'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

// ── NOTARY — Scheduler sub-view ───────────────────────────────────────────────

function EsNotaryScheduler() {
  const es = window.__es;
  const I = window.EsIcons;
  const s = window.ESIGN_DATA.notaryStats;
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '10px', marginBottom: '16px' }}>
        <EsMetric label="Sessions (30d)" value={s.sessionsThisMonth} delta={`${s.completed} completed`} />
        <EsMetric label="Avg Session" value={s.avgSessionTime} delta="per notary ceremony" deltaColor={es.slate} />
        <EsMetric label="Commission States" value={s.commissionStates.length} delta={s.commissionStates.join(', ')} deltaColor={es.slate} />
        <div style={es.stat}>
          <div style={es.statLabel}>RON Availability</div>
          <div style={{ ...es.statValue, color: es.emerald, fontSize: '16px', display: 'flex', alignItems: 'center', gap: '6px' }}>
            <I.Check size={14} color={es.emerald} strokeWidth={2.5} /> 24/7 Live
          </div>
          <div style={es.statDelta}>On-call notary pool</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        <div style={es.card}>
          <div style={es.cardH}>Schedule New Session</div>
          <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
            {[
              { label: 'Envelope', value: 'Select envelope…', icon: I.Envelope },
              { label: 'Session Type', value: 'RON (Remote Online)', icon: I.Webcam },
              { label: 'Scheduled For', value: 'Apr 24, 2026 · 11:00 AM PT', icon: I.Calendar },
              { label: 'Notary', value: 'Auto-assign nearest commission', icon: I.Gavel },
              { label: 'Participants', value: '2 signers + 0 witnesses', icon: I.Contacts },
            ].map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: '10px', alignItems: 'center' }}>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Tv.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{r.label}</div>
                <div style={{ padding: '8px 12px', background: Tv.color.bg.secondary, borderRadius: '6px', fontSize: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <r.icon size={12} color={es.indigo} />
                  {r.value}
                </div>
              </div>
            ))}
            <button style={{ ...es.btnPrimary, marginTop: '8px', alignSelf: 'flex-end' }}><I.Calendar size={11} color="#fff" /> Schedule Session</button>
          </div>
        </div>

        <div style={es.card}>
          <div style={es.cardH}>Pre-Session Checklist</div>
          <div style={{ padding: '16px' }}>
            {[
              { label: 'Signer identities verified (driver license + face match)', done: true },
              { label: 'KBA questionnaire completed by each signer', done: true },
              { label: 'Webcam + microphone tested', done: false },
              { label: 'Document pre-reviewed by notary', done: true },
              { label: 'Witness roster confirmed (if required)', done: true },
              { label: 'Session recording consent obtained', done: true },
              { label: 'Jurisdictional compliance (notary commission valid in state)', done: true },
              { label: 'Backup communication channel established', done: false },
            ].map((c, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '7px 0', borderBottom: i < 7 ? `1px solid ${Tv.color.border.light}` : 'none' }}>
                <span style={{ width: '16px', height: '16px', borderRadius: '50%', background: c.done ? es.emeraldBg : Tv.color.bg.secondary, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `1px solid ${c.done ? es.emerald : Tv.color.border.light}` }}>
                  {c.done && <I.Check size={10} color={es.emerald} strokeWidth={2.5} />}
                </span>
                <span style={{ fontSize: '11px', color: c.done ? Tv.color.text.primary : Tv.color.text.secondary }}>{c.label}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── HUBS — 7 main sub-platforms with pill sub-nav ─────────────────────────────

function EsDocumentsHub() {
  const [sub, setSub] = useEsV('inbox');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['envelope.created','envelope.sent','envelope.voided','envelope.completed','envelope.declined']) : window.ESIGN_DATA;
  const views = [
    { id: 'inbox',     label: 'Inbox',     icon: I.Inbox,    badge: data.inbox.length },
    { id: 'envelopes', label: 'Envelopes', icon: I.Envelope, badge: data.envelopes.length },
    { id: 'funnel',    label: 'Funnel',    icon: I.Analytics },
    { id: 'audit',     label: 'Audit',     icon: I.Audit },
    { id: 'contacts',  label: 'Contacts',  icon: I.Contacts, badge: data.contacts.length },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'inbox'     && <EsInbox />}
      {sub === 'envelopes' && <EsEnvelopes />}
      {sub === 'funnel'    && window.EsSignerFunnel && <window.EsSignerFunnel />}
      {sub === 'audit'     && <EsAudit />}
      {sub === 'contacts'  && <EsContacts />}
    </div>
  );
}

function EsCreateHub() {
  const [sub, setSub] = useEsV('compose');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['envelope.created']) : window.ESIGN_DATA;
  const views = [
    { id: 'compose',   label: 'Compose',   icon: I.Compose },
    { id: 'templates', label: 'Templates', icon: I.Template, badge: data.templates.length },
    { id: 'bulk',      label: 'Bulk Send', icon: I.Bulk,     badge: data.bulkJobs.length },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'compose'   && <EsCompose />}
      {sub === 'templates' && <EsTemplates />}
      {sub === 'bulk'      && <EsBulk />}
    </div>
  );
}

function EsNotaryHub() {
  const [sub, setSub] = useEsV('sessions');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['notary.scheduled','notary.journalAdded']) : window.ESIGN_DATA;
  const views = [
    { id: 'sessions',  label: 'Sessions',  icon: I.Gavel,    badge: data.notarySessions.length },
    { id: 'scheduler', label: 'Scheduler', icon: I.Calendar },
    { id: 'journal',   label: 'Journal',   icon: I.Audit,    badge: (data.notaryJournal || []).length },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'sessions'  && <EsNotary />}
      {sub === 'scheduler' && <EsNotaryScheduler />}
      {sub === 'journal'   && window.EsNotaryJournal && <window.EsNotaryJournal />}
    </div>
  );
}

function EsWorkflowsHub() {
  const [sub, setSub] = useEsV('runtime');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['workflow.advanced','envelope.sent']) : window.ESIGN_DATA;
  const rules = data.workflows.flatMap(w => w.rules || []).length;
  const views = [
    { id: 'runtime',  label: 'Runtime',      icon: I.Clock,   badge: (data.wfRuntime || []).length },
    { id: 'monitors', label: 'SLA Monitors', icon: I.Clock,   badge: data.workflowSlaMonitors.length },
    { id: 'nudges',   label: 'Nudges',       icon: I.Bell,    badge: data.nudgeLadders.length },
    { id: 'designer', label: 'Designer',     icon: I.Network, badge: data.workflows.length },
    { id: 'rules',    label: 'Rules',        icon: I.Branch,  badge: rules },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'runtime'  && window.EsWorkflowRuntime && <window.EsWorkflowRuntime />}
      {sub === 'monitors' && <EsWorkflowsMonitors />}
      {sub === 'nudges'   && window.EsNudgeEditor && <window.EsNudgeEditor />}
      {sub === 'designer' && <EsWorkflowsDesigner />}
      {sub === 'rules'    && <EsWorkflowsRules />}
    </div>
  );
}

function EsIntelligenceHub() {
  const [sub, setSub] = useEsV('clauses');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['redline.proposed','redline.decided','risk.batchScanned','compose.clauseInserted']) : window.ESIGN_DATA;
  const views = [
    { id: 'clauses',  label: 'Clause Library', icon: I.Shield,  badge: data.clauseLibrary.length },
    { id: 'redlines', label: 'Redlines',       icon: I.Redline, badge: data.redlines.length },
    { id: 'trend',    label: 'Risk Trend',     icon: I.Analytics },
    { id: 'scans',    label: 'Risk Scans',     icon: I.Brain,   badge: data.riskScans.length },
    { id: 'training', label: 'AI Training',    icon: I.Sparkle },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'clauses'  && <EsIntelClauses />}
      {sub === 'redlines' && window.EsRedlineQueue && <window.EsRedlineQueue />}
      {sub === 'trend'    && window.EsRiskTrend && <window.EsRiskTrend />}
      {sub === 'scans'    && <EsIntelScans />}
      {sub === 'training' && <EsIntelTraining />}
    </div>
  );
}

function EsComplianceHub() {
  const [sub, setSub] = useEsV('posture');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['delegation.revoked']) : window.ESIGN_DATA;
  const views = [
    { id: 'posture',     label: 'Posture',     icon: I.Scale,   badge: data.compliancePosture.length },
    { id: 'vault',       label: 'Vault',       icon: I.Key,     badge: data.vaultSettings.matterKeks },
    { id: 'delegations', label: 'Delegations', icon: I.Witness, badge: data.delegations.length },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'posture'     && <EsCompPosture />}
      {sub === 'vault'       && <EsCompVault />}
      {sub === 'delegations' && (window.EsDelegationPanel ? <window.EsDelegationPanel /> : <EsCompDelegations />)}
    </div>
  );
}

function EsIntegrationsHub() {
  const [sub, setSub] = useEsV('apps');
  const I = window.EsIcons;
  const data = window.useEsStore ? window.useEsStore(['payment.captured']) : window.ESIGN_DATA;
  const views = [
    { id: 'apps',     label: 'Apps',     icon: I.Link,    badge: data.connectedApps.length },
    { id: 'webhooks', label: 'Webhooks', icon: I.Webhook, badge: data.webhooks.length },
    { id: 'sdk',      label: 'SDK Keys', icon: I.Code,    badge: data.sdkKeys.length },
    { id: 'payments', label: 'Payments', icon: I.Payment, badge: data.payments.length },
  ];
  return (
    <div>
      <EsSubNav views={views} active={sub} onChange={setSub} />
      {sub === 'apps'     && <EsIntegApps />}
      {sub === 'webhooks' && <EsIntegWebhooks />}
      {sub === 'sdk'      && <EsIntegSdk />}
      {sub === 'payments' && <EsIntegPayments />}
    </div>
  );
}

// ── Exports ────────────────────────────────────────────────────────────────────
window.EsSubNav = EsSubNav;
window.EsInbox = EsInbox;
window.EsEnvelopes = EsEnvelopes;
window.EsCompose = EsCompose;
window.EsTemplates = EsTemplates;
window.EsBulk = EsBulk;
window.EsNotary = EsNotary;
window.EsNotaryScheduler = EsNotaryScheduler;
window.EsWorkflows = EsWorkflows;
window.EsWorkflowsMonitors = EsWorkflowsMonitors;
window.EsWorkflowsDesigner = EsWorkflowsDesigner;
window.EsWorkflowsRules = EsWorkflowsRules;
window.EsIntelligence = EsIntelligence;
window.EsIntelClauses = EsIntelClauses;
window.EsIntelScans = EsIntelScans;
window.EsIntelTraining = EsIntelTraining;
window.EsAudit = EsAudit;
window.EsIntegrations = EsIntegrations;
window.EsIntegApps = EsIntegApps;
window.EsIntegWebhooks = EsIntegWebhooks;
window.EsIntegSdk = EsIntegSdk;
window.EsIntegPayments = EsIntegPayments;
window.EsCompliance = EsCompliance;
window.EsCompPosture = EsCompPosture;
window.EsCompVault = EsCompVault;
window.EsCompDelegations = EsCompDelegations;
window.EsContacts = EsContacts;
window.EsAnalytics = EsAnalytics;
window.EsDocumentsHub = EsDocumentsHub;
window.EsCreateHub = EsCreateHub;
window.EsNotaryHub = EsNotaryHub;
window.EsWorkflowsHub = EsWorkflowsHub;
window.EsIntelligenceHub = EsIntelligenceHub;
window.EsComplianceHub = EsComplianceHub;
window.EsIntegrationsHub = EsIntegrationsHub;
