// SETTINGS PLATFORM — Billing Plan · Integrations · API · Webhooks · Email
const Ts_i = window.ArbiterTokens;

function SettingsBilling({ data }) {
  const stg = window.__stg;
  const b = data.billingPlan;
  const Card = window.SettingsSectionCard;

  const pctSeats = Math.round((b.seatsUsed / b.seats) * 100);
  const pctApi   = Math.round((b.usage.apiCallsMonth / b.usage.apiCallsCapMonth) * 100);
  const pctStor  = Math.round((b.usage.storageGb / b.usage.storageCapGb) * 100);

  const bar = (pct, color) => (
    <div style={{ height: '6px', borderRadius: '3px', background: Ts_i.color.border.light, overflow: 'hidden', marginTop: '6px' }}>
      <div style={{ width: `${pct}%`, height: '100%', background: color }} />
    </div>
  );

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Plan</span><span style={{ ...stg.statValue, fontSize: '14px', marginTop: '4px' }}>{b.plan}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Annual</span><span style={stg.statValue}>${(b.planPrice/1000).toFixed(0)}K</span><span style={stg.statDelta}>${b.seatPriceEffective.toLocaleString()}/seat</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Seats used</span><span style={stg.statValue}>{b.seatsUsed}/{b.seats}</span><span style={stg.statDelta}>{pctSeats}%</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Renewal</span><span style={stg.statValue}>{b.renewal}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>API usage</span><span style={stg.statValue}>{pctApi}%</span><span style={stg.statDelta}>{(b.usage.apiCallsMonth/1e6).toFixed(0)}M / {(b.usage.apiCallsCapMonth/1e6).toFixed(0)}M</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Storage</span><span style={stg.statValue}>{pctStor}%</span><span style={stg.statDelta}>{(b.usage.storageGb/1024).toFixed(2)} TB</span></div>
      </div>

      <Card title="Plan includes" action={<button style={stg.btnSecondary}>Contact CSM</button>}>
        <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '10px' }}>
          {b.includes.map(inc => (
            <div key={inc} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 12px', background: Ts_i.color.bg.secondary, borderRadius: '6px' }}>
              <span style={{ color: stg.emerald, fontSize: '16px' }}><Icons.Check size={11}/></span>
              <span style={{ fontSize: '12px', color: Ts_i.color.text.primary, fontWeight: 500 }}>{inc}</span>
            </div>
          ))}
        </div>
      </Card>

      <div style={stg.split(400)}>
        <Card title="Usage this month">
          <div style={{ padding: '14px 16px' }}>
            <div style={{ fontSize: '11px', fontWeight: 700, color: Ts_i.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Seats · {pctSeats}%</div>
            <div style={{ fontSize: '12px', color: Ts_i.color.text.secondary, fontFamily: Ts_i.font.mono, marginTop: '2px' }}>{b.seatsUsed} / {b.seats}</div>
            {bar(pctSeats, stg.steel)}
          </div>
          <div style={{ padding: '14px 16px', borderTop: `1px solid ${Ts_i.color.border.light}` }}>
            <div style={{ fontSize: '11px', fontWeight: 700, color: Ts_i.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>API calls · {pctApi}%</div>
            <div style={{ fontSize: '12px', color: Ts_i.color.text.secondary, fontFamily: Ts_i.font.mono, marginTop: '2px' }}>{b.usage.apiCallsMonth.toLocaleString()} / {b.usage.apiCallsCapMonth.toLocaleString()}</div>
            {bar(pctApi, stg.blue)}
          </div>
          <div style={{ padding: '14px 16px', borderTop: `1px solid ${Ts_i.color.border.light}` }}>
            <div style={{ fontSize: '11px', fontWeight: 700, color: Ts_i.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Storage · {pctStor}%</div>
            <div style={{ fontSize: '12px', color: Ts_i.color.text.secondary, fontFamily: Ts_i.font.mono, marginTop: '2px' }}>{b.usage.storageGb.toLocaleString()} GB / {b.usage.storageCapGb.toLocaleString()} GB</div>
            {bar(pctStor, stg.violet)}
          </div>
        </Card>

        <Card title="Payment method">
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '12px', alignItems: 'center', padding: '12px', background: Ts_i.color.bg.secondary, borderRadius: '8px', marginBottom: '10px' }}>
              <div style={{ width: '48px', height: '32px', borderRadius: '4px', background: '#D4004D', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', fontWeight: 700 }}>ACH</div>
              <div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_i.color.text.primary }}>{b.paymentMethod.bank}</div>
                <div style={{ fontSize: '11px', color: Ts_i.color.text.tertiary, fontFamily: Ts_i.font.mono }}>Account {b.paymentMethod.account}</div>
              </div>
            </div>
            <div style={{ fontSize: '11px', color: Ts_i.color.text.tertiary, marginBottom: '8px' }}>Fallback: {b.paymentMethod.fallback}</div>
            <button style={stg.btnSecondary}>Update method</button>
          </div>
        </Card>
      </div>

      <Card title={`Invoice history · ${b.invoices.length}`} action={<button style={stg.btnSecondary}>Download all (ZIP)</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Invoice</th>
              <th style={stg.th}>Period</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Amount</th>
              <th style={stg.th}>Due</th>
              <th style={stg.th}>Paid</th>
              <th style={stg.th}>Status</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {b.invoices.map(inv => (
              <tr key={inv.id}>
                <td style={{ ...stg.td, fontFamily: Ts_i.font.mono, fontWeight: 700, color: stg.steelDeep }}>{inv.id}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{inv.period}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700 }}>${inv.amount.toLocaleString()}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_i.color.text.tertiary, fontFamily: Ts_i.font.mono }}>{inv.dueDate}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_i.color.text.tertiary, fontFamily: Ts_i.font.mono }}>{inv.paidDate}</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill('ok') }}>{inv.status}</span></td>
                <td style={{ ...stg.td, textAlign: 'right' }}><button style={stg.btnGhost}>PDF</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      <Card title={`Add-ons · ${b.addOns.length}`}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Add-on</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Annual price</th>
              <th style={stg.th}>Active</th>
            </tr>
          </thead>
          <tbody>
            {b.addOns.map(a => (
              <tr key={a.id}>
                <td style={{ ...stg.td, fontWeight: 600 }}>{a.label}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700 }}>${a.price.toLocaleString()}</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(a.active ? 'ok' : 'pending') }}>{a.active ? 'Active' : 'Inactive'}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function SettingsIntegrations({ data }) {
  const stg = window.__stg;
  const infra = window.__stg_infra;
  const { useToast, InfoTip, EmptyState } = infra;
  const toast = useToast();
  const Card = window.SettingsSectionCard;
  const { useState } = React;

  // Extend built-in list with legal-firm must-haves — #18
  const extras = [
    { id: 'INT-CLIO',   name: 'Clio Manage',       category: 'Practice Mgmt', vendor: 'Themis Solutions', icon: 'C', status: 'connected', lastSync: '2m ago', events30d: 18420, owner: 'IT', trust: 'production' },
    { id: 'INT-NETDOC', name: 'NetDocuments',      category: 'DMS',           vendor: 'NetDocuments',     icon: 'N', status: 'connected', lastSync: '5m ago', events30d: 94200, owner: 'Records', trust: 'production' },
    { id: 'INT-IMAN',   name: 'iManage Cloud',     category: 'DMS',           vendor: 'iManage',          icon: 'i', status: 'disabled',  lastSync: '—',       events30d: 0, owner: 'Records', trust: 'dev' },
    { id: 'INT-RELAT',  name: 'Relativity One',    category: 'eDiscovery',    vendor: 'Relativity',       icon: 'R', status: 'connected', lastSync: '1h ago', events30d: 4120, owner: 'Discovery', trust: 'production' },
    { id: 'INT-LOGIK',  name: 'Logikcull',         category: 'eDiscovery',    vendor: 'Logikcull',        icon: 'L', status: 'error',     lastSync: '2h ago', error: 'OAuth token expired · reauthorize', events30d: 312, owner: 'Discovery', trust: 'production' },
    { id: 'INT-IRON',   name: 'Ironclad',          category: 'CLM',           vendor: 'Ironclad',         icon: 'I', status: 'connected', lastSync: '12m ago', events30d: 2140, owner: 'Contracts', trust: 'pilot' },
    { id: 'INT-CW',     name: 'ContractWorks',     category: 'CLM',           vendor: 'SecureDocs',       icon: 'C', status: 'disabled',  lastSync: '—', events30d: 0, owner: 'Contracts', trust: 'dev' },
    { id: 'INT-QB',     name: 'QuickBooks Online', category: 'Accounting',    vendor: 'Intuit',           icon: 'Q', status: 'connected', lastSync: '30m ago', events30d: 840, owner: 'Finance', trust: 'production' },
    { id: 'INT-ELITE',  name: 'Thomson Elite 3E',  category: 'Accounting',    vendor: 'Thomson Reuters',  icon: '3', status: 'connected', lastSync: '1h ago',  events30d: 210, owner: 'Finance', trust: 'production' },
    { id: 'INT-DOCU',   name: 'DocuSign eSignature', category: 'eSign',       vendor: 'DocuSign',         icon: 'D', status: 'connected', lastSync: '8m ago',  events30d: 1820, owner: 'Legal Ops', trust: 'production' },
  ];
  const integrations = [...(data.integrations || []), ...extras.filter(e => !(data.integrations || []).some(i => i.id === e.id))];
  const [cat, setCat] = useState('All');
  const [trustFilter, setTrustFilter] = useState('all');
  const [vault, setVault] = useState(null); // integration id for credential vault
  const [pinging, setPinging] = useState({}); // id -> bool
  const cats = ['All', ...Array.from(new Set(integrations.map(i => i.category)))];
  const list = integrations
    .filter(i => cat === 'All' || i.category === cat)
    .filter(i => trustFilter === 'all' || (i.trust || 'production') === trustFilter);

  const testConnection = (i) => {
    setPinging(p => ({ ...p, [i.id]: true }));
    setTimeout(() => {
      setPinging(p => ({ ...p, [i.id]: false }));
      if (i.status === 'error') {
        toast.push({ kind: 'error', title: `${i.name} still erroring`, message: i.error || 'See logs for details' });
      } else {
        toast.push({ kind: 'success', title: `${i.name} responded in ${60 + Math.floor(Math.random() * 180)}ms`, message: 'All vendor endpoints reachable' });
      }
    }, 900);
  };

  const oauthConnect = (i) => {
    toast.push({ kind: 'info', title: `Opening ${i.vendor} OAuth…`, message: 'Pop-up will redirect back when authorized' });
    setTimeout(() => toast.push({ kind: 'success', title: `${i.name} connected`, message: 'Scopes: read:matters, read:docs, write:events' }), 1400);
  };
  const active = integrations.filter(i => i.status === 'connected').length;
  const errored = integrations.filter(i => i.status === 'error').length;
  const disabled = integrations.filter(i => i.status === 'disabled').length;

  const statusStyle = (s) =>
    s === 'connected' ? stg.statusPill('ok')
    : s === 'error'   ? stg.statusPill('fail')
    : s === 'disabled'? stg.statusPill('pending')
    : stg.statusPill('warn');

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Integrations</span><span style={stg.statValue}>{integrations.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Connected</span><span style={{ ...stg.statValue, color: stg.emerald }}>{active}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Errored</span><span style={{ ...stg.statValue, color: stg.crimson }}>{errored}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Disabled</span><span style={{ ...stg.statValue, color: Ts_i.color.text.tertiary }}>{disabled}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Events 30d</span><span style={stg.statValue}>{((integrations.reduce((s, i) => s + i.events30d, 0)) / 1e6).toFixed(1)}M</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Categories</span><span style={stg.statValue}>{cats.length - 1}</span></div>
      </div>

      <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', flexWrap: 'wrap', alignItems: 'center' }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)}
            style={{ padding: '5px 12px', borderRadius: '14px', border: `1px solid ${cat === c ? stg.steelDeep : Ts_i.color.border.light}`, background: cat === c ? stg.steelBg : Ts_i.color.bg.card, color: cat === c ? stg.steelDeep : Ts_i.color.text.secondary, fontSize: '11px', fontWeight: 500, cursor: 'pointer', fontFamily: Ts_i.font.family }}>
            {c}
          </button>
        ))}
        <span style={{ width: '1px', height: '18px', background: Ts_i.color.border.light, margin: '0 4px' }} />
        {/* Trust filter — #20 (trust levels) */}
        <span style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, marginRight: '2px' }}>Trust:</span>
        {['all','dev','pilot','production'].map(t => (
          <button key={t} onClick={() => setTrustFilter(t)}
            style={{ padding: '3px 8px', borderRadius: '10px', border: `1px solid ${trustFilter === t ? stg.steelDeep : Ts_i.color.border.light}`, background: trustFilter === t ? stg.steelDeep : Ts_i.color.bg.card, color: trustFilter === t ? '#fff' : Ts_i.color.text.secondary, fontSize: '10px', fontWeight: 600, cursor: 'pointer', textTransform: 'capitalize' }}>
            {t}
          </button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={stg.btnSecondary}>Browse marketplace</button>
        <button style={stg.btnPrimary}>+ Custom integration</button>
      </div>

      <div style={stg.cardGrid(320)}>
        {list.map(i => (
          <div key={i.id} style={{ ...stg.card, marginBottom: 0, margin: '4px' }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Ts_i.color.border.light}` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '10px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', minWidth: 0 }}>
                  <div style={{
                    width: '36px', height: '36px', borderRadius: '8px',
                    background: 'linear-gradient(135deg, #334155, #475569)',
                    color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: '16px', fontWeight: 800, flexShrink: 0,
                  }}>{i.icon}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_i.color.text.primary, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{i.name}</div>
                    <div style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: '2px' }}>{i.category}</div>
                  </div>
                </div>
                <span style={{ ...stg.tag, ...statusStyle(i.status) }}>{i.status}</span>
              </div>
              {i.error && <div style={{ marginTop: '8px', padding: '6px 10px', borderRadius: '4px', background: stg.crimsonBg, color: stg.crimson, fontSize: '11px' }}>! {i.error}</div>}
            </div>
            <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '10px' }}>
              <div>
                <div style={stg.sectionLabel}>Vendor</div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_i.color.text.primary, marginTop: '2px' }}>{i.vendor}</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Last sync</div>
                <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_i.color.text.primary, marginTop: '2px', fontFamily: Ts_i.font.mono }}>{i.lastSync}</div>
              </div>
              <div>
                <div style={stg.sectionLabel}>Events 30d</div>
                <div style={{ fontSize: '11px', fontWeight: 700, color: stg.steelDeep, marginTop: '2px', fontFamily: Ts_i.font.mono }}>{i.events30d >= 1000 ? `${(i.events30d/1000).toFixed(0)}K` : i.events30d}</div>
              </div>
            </div>
            <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_i.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '6px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                <span style={{ fontSize: '10px', color: Ts_i.color.text.tertiary }}>Owned by {i.owner}</span>
                {i.trust && (
                  <span style={{
                    fontSize: '9px', padding: '1px 5px', borderRadius: '3px', fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
                    background: i.trust === 'production' ? stg.emeraldBg : i.trust === 'pilot' ? stg.amberBg : stg.steelBg,
                    color: i.trust === 'production' ? stg.emerald : i.trust === 'pilot' ? stg.amber : stg.steelDeep,
                  }}>{i.trust}</span>
                )}
              </div>
              <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                <button style={stg.btnGhost} onClick={() => testConnection(i)} disabled={pinging[i.id]}>{pinging[i.id] ? '● Testing…' : 'Test'}</button>
                <button style={stg.btnGhost} onClick={() => setVault(i)}>Vault</button>
                <button style={stg.btnGhost}>Logs</button>
                <button style={stg.btnSecondary} onClick={() => i.status === 'connected' ? toast.push({ kind: 'info', title: `Opening ${i.name} management…` }) : oauthConnect(i)}>
                  {i.status === 'connected' ? 'Manage' : i.status === 'error' ? 'Reconnect' : 'Connect'}
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Credential vault drawer — #16 */}
      {vault && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9997, background: 'rgba(15,23,42,0.35)', display: 'flex', justifyContent: 'flex-end' }} onClick={() => setVault(null)}>
          <div onClick={e => e.stopPropagation()} style={{ width: '440px', maxWidth: '100%', height: '100%', background: '#fff', boxShadow: '-8px 0 24px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ padding: '14px 18px', borderBottom: `1px solid ${Ts_i.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: '10px', fontWeight: 700, color: Ts_i.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Credential vault</div>
                <div style={{ fontSize: '14px', fontWeight: 700, marginTop: '2px' }}>{vault.name}</div>
              </div>
              <button onClick={() => setVault(null)} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '14px 18px' }}>
              <div style={{ padding: '10px', background: '#FEF3C7', border: '1px solid #F59E0B', borderRadius: '6px', fontSize: '11px', color: '#78350F', marginBottom: '12px' }}>
                 Credentials stored in Azure Key Vault · audit-logged · never displayed in UI
              </div>
              {[
                { label: 'OAuth refresh token', value: '●●●●●●●●···a9f3', rotated: '14d ago', kind: 'secret' },
                { label: 'Client ID', value: 'arbiter-prod-sp', rotated: '2024-11-03', kind: 'public' },
                { label: 'Tenant ID', value: 'b6c9d…-4e2a', rotated: '2024-11-03', kind: 'public' },
                { label: 'Webhook signing secret', value: '●●●●●●●●···c1d7', rotated: '62d ago', kind: 'secret' },
              ].map(c => (
                <div key={c.label} style={{ padding: '10px 0', borderBottom: `1px solid ${Ts_i.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: '11px', fontWeight: 600, color: Ts_i.color.text.primary }}>{c.label}</div>
                    <div style={{ fontFamily: Ts_i.font.mono, fontSize: '11px', color: c.kind === 'secret' ? Ts_i.color.text.tertiary : Ts_i.color.text.secondary, marginTop: '2px' }}>{c.value}</div>
                    <div style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, marginTop: '2px' }}>Rotated {c.rotated}</div>
                  </div>
                  <div style={{ display: 'flex', gap: '4px' }}>
                    <button style={stg.btnGhost} onClick={() => toast.push({ kind: 'info', title: `${c.label} reveal requested`, message: 'Requires 2nd admin approval' })}>Reveal</button>
                    <button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'success', title: `${c.label} rotated` })}>Rotate</button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SettingsAPIWebhooks({ data }) {
  const stg = window.__stg;
  const webhooks = data.webhooks;
  const events = data.eventCatalog;
  const keys = data.account.apiKeys;
  const Card = window.SettingsSectionCard;
  const infra = window.__stg_infra || {};
  const toast = (infra.useToast && infra.useToast()) || { push: () => {} };

  const active = webhooks.filter(w => w.status === 'active').length;
  const failing = webhooks.filter(w => w.status === 'failing').length;
  const totalEvents = webhooks.reduce((s, w) => s + w.success + w.failures, 0);

  // #11 — webhook test-fire + DLQ + replay
  const [testingId, setTestingId] = React.useState(null);
  const [testResult, setTestResult] = React.useState(null);
  const [dlqReplay, setDlqReplay] = React.useState({});
  const [dlqFilter, setDlqFilter] = React.useState('all');

  // Seeded dead-letter queue (no backing data on model — this is the UI)
  const dlq = React.useMemo(() => ([
    { id: 'DLQ-48219', hook: 'matter.opened → CRM', event: 'matter.opened', code: 504, reason: 'Gateway timeout · 10s', age: '4m ago', payloadBytes: 2431, attempts: 3, next: 'in 8m', willRetry: true },
    { id: 'DLQ-48218', hook: 'matter.opened → CRM', event: 'matter.opened', code: 504, reason: 'Gateway timeout · 10s', age: '6m ago', payloadBytes: 2401, attempts: 3, next: 'in 7m', willRetry: true },
    { id: 'DLQ-48217', hook: 'invoice.paid → QuickBooks', event: 'invoice.paid', code: 401, reason: 'Unauthorized · token expired', age: '14m ago', payloadBytes: 1812, attempts: 5, next: '—', willRetry: false },
    { id: 'DLQ-48215', hook: 'document.signed → DMS', event: 'document.signed', code: 'TLS', reason: 'Certificate verify failed', age: '22m ago', payloadBytes: 3087, attempts: 2, next: 'in 12m', willRetry: true },
    { id: 'DLQ-48211', hook: 'user.created → HRIS', event: 'user.created', code: 422, reason: 'Schema validation · missing payroll_id', age: '1h ago', payloadBytes: 1023, attempts: 7, next: '—', willRetry: false },
    { id: 'DLQ-48202', hook: 'matter.opened → CRM', event: 'matter.opened', code: 429, reason: 'Rate limited by Clio', age: '2h ago', payloadBytes: 2156, attempts: 4, next: 'in 22m', willRetry: true },
    { id: 'DLQ-48190', hook: 'invoice.paid → QuickBooks', event: 'invoice.paid', code: 401, reason: 'Unauthorized · token expired', age: '3h ago', payloadBytes: 1804, attempts: 5, next: '—', willRetry: false },
  ]), []);
  const dlqFiltered = dlqFilter === 'all' ? dlq : dlq.filter(d => dlqFilter === 'retry' ? d.willRetry : !d.willRetry);
  const dlqPoison = dlq.filter(d => !d.willRetry).length;

  function fireTest(w) {
    setTestingId(w.id);
    setTestResult(null);
    const t0 = Date.now();
    setTimeout(() => {
      const lat = 180 + Math.floor(Math.random() * 420);
      const ok = Math.random() > (w.status === 'failing' ? 0.6 : 0.08);
      setTestResult({
        id: w.id, name: w.name, ok, status: ok ? 200 : (Math.random() > 0.5 ? 504 : 401),
        latency: lat, ts: new Date().toISOString(),
        traceId: 't_' + Math.random().toString(36).slice(2, 10),
      });
      setTestingId(null);
      toast.push({ kind: ok ? 'success' : 'error', title: ok ? 'Test delivered' : 'Test failed', message: `${w.name} · ${lat}ms · ${ok ? 'HTTP 200' : 'HTTP 504'}` });
    }, 900 + Math.floor(Math.random() * 700));
  }

  function replayOne(d) {
    setDlqReplay(r => ({ ...r, [d.id]: 'pending' }));
    setTimeout(() => {
      setDlqReplay(r => ({ ...r, [d.id]: 'done' }));
      toast.push({ kind: 'success', title: `Replayed ${d.id}`, message: `${d.event} re-queued to ${d.hook}` });
    }, 700);
  }
  function replayAll() {
    const retryable = dlq.filter(d => d.willRetry);
    retryable.forEach(d => { setDlqReplay(r => ({ ...r, [d.id]: 'pending' })); });
    setTimeout(() => {
      retryable.forEach(d => { setDlqReplay(r => ({ ...r, [d.id]: 'done' })); });
      toast.push({ kind: 'success', title: 'Replay triggered', message: `${retryable.length} deliveries re-queued` });
    }, 900);
  }

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>API keys</span><span style={stg.statValue}>{keys.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Webhooks</span><span style={stg.statValue}>{webhooks.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Active</span><span style={{ ...stg.statValue, color: stg.emerald }}>{active}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Failing</span><span style={{ ...stg.statValue, color: stg.crimson }}>{failing}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>DLQ backlog</span><span style={{ ...stg.statValue, color: dlq.length > 0 ? stg.amber : stg.emerald }}>{dlq.length}</span><span style={stg.statDelta}>{dlqPoison} poison</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Events 30d</span><span style={stg.statValue}>{(totalEvents / 1e6).toFixed(2)}M</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Event types</span><span style={stg.statValue}>{events.length}</span></div>
      </div>

      <Card title={`Webhooks · ${webhooks.length}`} action={<button style={stg.btnPrimary}>+ New webhook</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Name</th>
              <th style={stg.th}>URL</th>
              <th style={stg.th}>Event</th>
              <th style={stg.th}>Status</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Success</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Failures</th>
              <th style={stg.th}>Last delivery</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {webhooks.map(w => (
              <tr key={w.id}>
                <td style={{ ...stg.td, fontWeight: 600 }}>{w.name}</td>
                <td style={{ ...stg.td, fontFamily: Ts_i.font.mono, fontSize: '10px', color: Ts_i.color.text.secondary, maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.url}</td>
                <td style={stg.td}><span style={{ ...stg.tag, background: stg.steelBg, color: stg.steelDeep, fontFamily: Ts_i.font.mono }}>{w.event}</span></td>
                <td style={stg.td}>
                  <span style={{ ...stg.tag, ...stg.statusPill(w.status === 'active' ? 'ok' : w.status === 'failing' ? 'fail' : 'pending') }}>{w.status}</span>
                </td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700, color: stg.emerald }}>{w.success.toLocaleString()}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700, color: w.failures > 0 ? stg.crimson : Ts_i.color.text.tertiary }}>{w.failures}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_i.color.text.tertiary }}>{w.last}</td>
                <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                  <button style={stg.btnGhost} onClick={() => fireTest(w)} disabled={testingId === w.id}>{testingId === w.id ? '● Firing…' : ' Test'}</button>
                  <button style={stg.btnGhost}>Logs</button>
                  <button style={stg.btnGhost}>Edit</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
        {testResult && (
          <div style={{ margin: '10px 16px 14px', padding: '10px 12px', borderRadius: '6px',
            background: testResult.ok ? stg.emeraldBg : stg.crimsonBg,
            border: `1px solid ${testResult.ok ? stg.emerald : stg.crimson}`,
            color: testResult.ok ? stg.emerald : stg.crimson,
            fontSize: '11px', display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
            <span style={{ fontWeight: 700 }}>{testResult.ok ? 'ok Test delivered' : 'x Test failed'}</span>
            <span style={{ fontFamily: Ts_i.font.mono }}>{testResult.name}</span>
            <span style={{ fontFamily: Ts_i.font.mono }}>HTTP {testResult.status}</span>
            <span style={{ fontFamily: Ts_i.font.mono }}>{testResult.latency}ms</span>
            <span style={{ fontFamily: Ts_i.font.mono, color: Ts_i.color.text.tertiary }}>trace={testResult.traceId}</span>
            <button style={{ ...stg.btnGhost, marginLeft: 'auto' }} onClick={() => setTestResult(null)}>Dismiss</button>
          </div>
        )}
      </Card>

      {/* #11 — Dead-letter queue with per-row + bulk replay */}
      <Card
        title={`Dead-letter queue · ${dlq.length}`}
        action={
          <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
            <div role="tablist" aria-label="DLQ filter" style={{ display: 'inline-flex', background: Ts_i.color.bg.secondary, borderRadius: '6px', padding: '2px' }}>
              {[{ k: 'all', l: `All (${dlq.length})` }, { k: 'retry', l: `Retryable (${dlq.filter(d => d.willRetry).length})` }, { k: 'poison', l: `Poison (${dlqPoison})` }].map(f => (
                <button key={f.k} role="tab" aria-selected={dlqFilter === f.k} onClick={() => setDlqFilter(f.k)} style={{
                  padding: '4px 10px', borderRadius: '4px', border: 'none', cursor: 'pointer', fontSize: '11px', fontWeight: 600,
                  background: dlqFilter === f.k ? '#fff' : 'transparent',
                  color: dlqFilter === f.k ? Ts_i.color.text.primary : Ts_i.color.text.tertiary,
                  boxShadow: dlqFilter === f.k ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                }}>{f.l}</button>
              ))}
            </div>
            <button style={stg.btnSecondary} onClick={replayAll}>↻ Replay all retryable</button>
          </div>
        }
      >
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>DLQ ID</th>
              <th style={stg.th}>Hook</th>
              <th style={stg.th}>Event</th>
              <th style={stg.th}>Failure</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Attempts</th>
              <th style={stg.th}>Next retry</th>
              <th style={stg.th}>Age</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {dlqFiltered.map(d => {
              const rs = dlqReplay[d.id];
              return (
                <tr key={d.id}>
                  <td style={{ ...stg.td, fontFamily: Ts_i.font.mono, fontWeight: 700, color: stg.steelDeep }}>{d.id}</td>
                  <td style={{ ...stg.td, fontSize: '11px', fontWeight: 600 }}>{d.hook}</td>
                  <td style={stg.td}><span style={{ ...stg.tag, background: stg.steelBg, color: stg.steelDeep, fontFamily: Ts_i.font.mono }}>{d.event}</span></td>
                  <td style={{ ...stg.td, fontSize: '11px' }}>
                    <span style={{ ...stg.tag, background: stg.crimsonBg, color: stg.crimson, fontFamily: Ts_i.font.mono, marginRight: '6px' }}>{d.code}</span>
                    <span style={{ color: Ts_i.color.text.secondary }}>{d.reason}</span>
                  </td>
                  <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700, color: d.attempts >= 5 ? stg.crimson : stg.amber }}>{d.attempts}</td>
                  <td style={{ ...stg.td, fontFamily: Ts_i.font.mono, fontSize: '11px', color: d.willRetry ? stg.emerald : Ts_i.color.text.tertiary }}>{d.next}</td>
                  <td style={{ ...stg.td, fontSize: '11px', color: Ts_i.color.text.tertiary }}>{d.age}</td>
                  <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                    <button style={stg.btnGhost}>Inspect</button>
                    <button style={stg.btnGhost} onClick={() => replayOne(d)} disabled={rs === 'pending'}>
                      {rs === 'pending' ? '● …' : rs === 'done' ? 'ok Replayed' : '↻ Replay'}
                    </button>
                    <button style={stg.btnGhost} title="Drop permanently — requires admin">Drop</button>
                  </td>
                </tr>
              );
            })}
            {dlqFiltered.length === 0 && (
              <tr><td colSpan={8} style={{ ...stg.td, textAlign: 'center', padding: '22px', color: Ts_i.color.text.tertiary, fontSize: '12px' }}>ok Queue empty — no failed deliveries in this filter</td></tr>
            )}
          </tbody>
        </table>
        </div>
        <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_i.color.border.light}`, background: Ts_i.color.bg.secondary, fontSize: '11px', color: Ts_i.color.text.tertiary, display: 'flex', justifyContent: 'space-between' }}>
          <span>Retry policy: exponential backoff · max 7 attempts · 24h TTL before promotion to poison</span>
          <span style={{ fontFamily: Ts_i.font.mono }}>Poison → arbiter-webhooks-dlq-poison (Service Bus)</span>
        </div>
      </Card>

      <Card title={`Event catalog · ${events.length}`}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Event ID</th>
              <th style={stg.th}>Category</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Volume 30d</th>
              <th style={stg.th}>Schema</th>
            </tr>
          </thead>
          <tbody>
            {events.map(e => (
              <tr key={e.id}>
                <td style={{ ...stg.td, fontFamily: Ts_i.font.mono, fontWeight: 700, color: stg.steelDeep }}>{e.id}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_i.color.text.secondary }}>{e.category}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 600 }}>{e.volume.toLocaleString()}</td>
                <td style={stg.td}><span style={{ ...stg.tag, ...stg.statusPill(e.schema === 'stable' ? 'ok' : 'beta') }}>{e.schema}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      <Card title="Developer resources">
        <div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '10px' }}>
          {[
            { t: 'OpenAPI spec',       d: 'api.arbiter.saadein/openapi.yaml' },
            { t: 'TypeScript SDK',     d: 'npm install @arbiter/sdk' },
            { t: 'Python SDK',         d: 'pip install arbiter-sdk' },
            { t: 'Postman collection', d: 'arbiter-v3-collection.json' },
            { t: 'GraphQL explorer',   d: 'api.arbiter.saadein/graphql' },
            { t: 'Changelog',          d: 'docs.arbiter.saadein/changelog' },
          ].map(r => (
            <div key={r.t} style={{ padding: '12px', background: Ts_i.color.bg.secondary, borderRadius: '6px', border: `1px solid ${Ts_i.color.border.light}` }}>
              <div style={{ fontSize: '12px', fontWeight: 700, color: Ts_i.color.text.primary }}>{r.t}</div>
              <div style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, fontFamily: Ts_i.font.mono, marginTop: '4px', marginBottom: '8px' }}>{r.d}</div>
              <button style={stg.btnGhost}>Open →</button>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function CalendarSyncCard() {
  const stg = window.__stg;
  const Card = window.SettingsSectionCard;
  const Row = window.SettingsRow;
  const infra = window.__stg_infra || {};
  const toast = (infra.useToast && infra.useToast()) || { push: () => {} };
  const InfoTip = infra.InfoTip || (() => null);

  const [providers, setProviders] = React.useState([
    { id: 'outlook', name: 'Microsoft 365 · Exchange Online', icon: 'O', connected: true, mailbox: 'matters@saadein.law', lastSync: '2m ago', accountsSynced: 42 },
    { id: 'gsuite',  name: 'Google Workspace',                 icon: 'G', connected: false, mailbox: '—',                 lastSync: '—',   accountsSynced: 0  },
    { id: 'icloud',  name: 'iCloud · CalDAV',                  icon: '◆', connected: false, mailbox: '—',                 lastSync: '—',   accountsSynced: 0  },
  ]);
  const [direction, setDirection] = React.useState('two-way');
  const [scope, setScope] = React.useState({
    matterEvents: true, deadlines: true, hearings: true, depositions: true,
    clientMeetings: true, internalMeetings: false, privateEvents: false, tentative: false,
  });
  const [redact, setRedact] = React.useState({
    titleToCode: true, stripAttendees: true, stripNotes: true, stripAttachments: true, stripLocation: false,
  });
  const [conflictRule, setConflictRule] = React.useState('arbiter-wins');
  const [freshness, setFreshness] = React.useState(5);

  function toggleProvider(p) {
    setProviders(ps => ps.map(x => x.id === p.id ? { ...x, connected: !x.connected } : x));
    toast.push({ kind: p.connected ? 'info' : 'success', title: p.connected ? `${p.name} disconnected` : `${p.name} connected`, message: p.connected ? 'Sync paused; last snapshot retained' : 'Initial sync running in background' });
  }

  const Check = ({ on, label, onChange, hint }) => (
    <label style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '6px 0', cursor: 'pointer' }}>
      <input type="checkbox" checked={on} onChange={onChange} style={{ marginTop: '2px' }} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: '12px', fontWeight: 500, color: Ts_i.color.text.primary }}>{label}</div>
        {hint && <div style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, marginTop: '1px' }}>{hint}</div>}
      </div>
    </label>
  );

  return (
    <Card
      title="Calendar sync"
      action={<span style={{ ...stg.tag, background: providers.some(p => p.connected) ? stg.emeraldBg : stg.steelBg, color: providers.some(p => p.connected) ? stg.emerald : stg.steelDeep }}>{providers.some(p => p.connected) ? 'Active' : 'Not configured'}</span>}
    >
      <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Ts_i.color.border.light}` }}>
        <div style={stg.sectionLabel}>Providers</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '10px', marginTop: '8px' }}>
          {providers.map(p => (
            <div key={p.id} style={{ padding: '10px 12px', border: `1px solid ${p.connected ? stg.emerald : Ts_i.color.border.light}`, borderRadius: '6px', background: p.connected ? stg.emeraldBg : '#fff' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '8px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0 }}>
                  <div style={{ width: '28px', height: '28px', borderRadius: '6px', background: p.connected ? stg.emerald : Ts_i.color.border.medium, color: '#fff', fontSize: '12px', fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{p.icon || '·'}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Ts_i.color.text.primary, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
                    <div style={{ fontSize: '10px', color: Ts_i.color.text.tertiary, fontFamily: Ts_i.font.mono }}>{p.connected ? `${p.accountsSynced} mailboxes · ${p.lastSync}` : 'Not connected'}</div>
                  </div>
                </div>
                <button style={p.connected ? stg.btnGhost : stg.btnSecondary} onClick={() => toggleProvider(p)}>{p.connected ? 'Disconnect' : 'Connect'}</button>
              </div>
            </div>
          ))}
        </div>
      </div>

      <Row label="Sync direction" hint="Choose how events flow between Arbiter matters and the provider">
        <div role="radiogroup" style={{ display: 'inline-flex', gap: '4px', background: Ts_i.color.bg.secondary, borderRadius: '6px', padding: '3px' }}>
          {[
            { k: 'one-way-in',  l: 'Read only · into Arbiter',  d: 'Arbiter reads provider events; does not write back.' },
            { k: 'one-way-out', l: 'Write only · from Arbiter', d: 'Arbiter pushes matter events; ignores changes in provider.' },
            { k: 'two-way',     l: 'Two-way sync',              d: 'Bidirectional; conflicts resolved by rule below.' },
          ].map(o => (
            <button key={o.k} role="radio" aria-checked={direction === o.k} onClick={() => setDirection(o.k)} title={o.d}
              style={{ padding: '5px 10px', fontSize: '11px', fontWeight: 600, border: 'none', borderRadius: '4px', cursor: 'pointer',
                background: direction === o.k ? '#fff' : 'transparent',
                color: direction === o.k ? Ts_i.color.text.primary : Ts_i.color.text.secondary,
                boxShadow: direction === o.k ? '0 1px 3px rgba(0,0,0,0.08)' : 'none' }}>
              {o.l}
            </button>
          ))}
        </div>
      </Row>

      <Row label="Sync scope" hint="Which event types participate in sync">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '0 18px', maxWidth: '520px' }}>
          <Check on={scope.matterEvents}    onChange={e => setScope(s => ({ ...s, matterEvents: e.target.checked }))}    label="Matter events"      hint="Key dates, open/close, milestones" />
          <Check on={scope.deadlines}       onChange={e => setScope(s => ({ ...s, deadlines: e.target.checked }))}       label="Deadlines"           hint="Statutory + matter-level deadlines" />
          <Check on={scope.hearings}        onChange={e => setScope(s => ({ ...s, hearings: e.target.checked }))}        label="Hearings & trials"   hint="Court appearances" />
          <Check on={scope.depositions}     onChange={e => setScope(s => ({ ...s, depositions: e.target.checked }))}     label="Depositions"         hint="Scheduled depositions" />
          <Check on={scope.clientMeetings}  onChange={e => setScope(s => ({ ...s, clientMeetings: e.target.checked }))}  label="Client meetings"     hint="External attendees" />
          <Check on={scope.internalMeetings}onChange={e => setScope(s => ({ ...s, internalMeetings: e.target.checked }))}label="Internal meetings"  hint="All attendees are firm users" />
          <Check on={scope.privateEvents}   onChange={e => setScope(s => ({ ...s, privateEvents: e.target.checked }))}   label="Private events"      hint="Marked Private in provider" />
          <Check on={scope.tentative}       onChange={e => setScope(s => ({ ...s, tentative: e.target.checked }))}       label="Tentative / proposed" hint="Include non-confirmed events" />
        </div>
      </Row>

      <Row label={<span>Redaction<InfoTip text="Privilege-safe titles. Clients on shared calendars never see matter detail." /></span>} hint="What Arbiter strips before pushing to provider">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '0 18px', maxWidth: '520px' }}>
          <Check on={redact.titleToCode}     onChange={e => setRedact(r => ({ ...r, titleToCode: e.target.checked }))}     label="Replace title with matter code" hint='e.g. "MTR-2026-0182 · Hearing"' />
          <Check on={redact.stripAttendees}  onChange={e => setRedact(r => ({ ...r, stripAttendees: e.target.checked }))}  label="Strip attendee list"            hint="Hide client/opposing counsel" />
          <Check on={redact.stripNotes}      onChange={e => setRedact(r => ({ ...r, stripNotes: e.target.checked }))}      label="Strip notes / description"     hint="Body becomes a link back to Arbiter" />
          <Check on={redact.stripAttachments}onChange={e => setRedact(r => ({ ...r, stripAttachments: e.target.checked }))}label="Strip attachments"             hint="Never leaves Arbiter DMS" />
          <Check on={redact.stripLocation}   onChange={e => setRedact(r => ({ ...r, stripLocation: e.target.checked }))}   label="Strip location"                 hint="Court name / room / address" />
        </div>
      </Row>

      <Row label="Conflict resolution" hint="When both sides edit the same event">
        <select value={conflictRule} onChange={e => setConflictRule(e.target.value)} style={{ ...stg.select, width: '260px' }}>
          <option value="arbiter-wins">Arbiter wins (matter data authoritative)</option>
          <option value="provider-wins">Provider wins (user calendar authoritative)</option>
          <option value="newest-wins">Last modified wins</option>
          <option value="prompt">Queue for user review (prompt on conflict)</option>
        </select>
      </Row>

      <Row label="Sync frequency" hint="How often Arbiter polls when webhooks aren't available">
        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
          <input type="range" min={1} max={60} value={freshness} onChange={e => setFreshness(parseInt(e.target.value))} style={{ width: '200px' }} />
          <span style={{ fontFamily: Ts_i.font.mono, fontSize: '12px', fontWeight: 700, color: Ts_i.color.text.primary, minWidth: '56px' }}>{freshness}m</span>
          <span style={{ ...stg.tag, background: stg.steelBg, color: stg.steelDeep }}>push preferred via Graph subscriptions</span>
        </div>
      </Row>

      <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_i.color.border.light}`, background: Ts_i.color.bg.secondary, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
        <span style={{ fontSize: '11px', color: Ts_i.color.text.tertiary }}>Changes apply to all mailboxes in this tenant. Per-user overrides are in <a style={{ color: stg.steelDeep }} href="#/settings/you/account">You → Account</a>.</span>
        <div style={{ display: 'flex', gap: '6px' }}>
          <button style={stg.btnGhost} onClick={() => toast.push({ kind: 'info', title: 'Dry-run complete', message: '1,248 events would sync · 12 redacted titles · 0 conflicts' })}>Preview sync (dry-run)</button>
          <button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'success', title: 'Calendar sync settings saved' })}>Save</button>
        </div>
      </div>
    </Card>
  );
}

function SettingsEmail({ data }) {
  const stg = window.__stg;
  const e = data.email;
  const sigs = data.emailSignatures;
  const Card = window.SettingsSectionCard;
  const Row = window.SettingsRow;

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>SMTP</span><span style={{ ...stg.statValue, color: stg.emerald, fontSize: '14px', marginTop: '4px' }}>{e.smtp.verified ? 'Verified' : 'Unverified'}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>SPF</span><span style={{ ...stg.statValue, color: stg.emerald, fontSize: '14px', marginTop: '4px' }}>{e.spf.status}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>DKIM</span><span style={{ ...stg.statValue, color: stg.emerald, fontSize: '14px', marginTop: '4px' }}>{e.dkim.status}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>DMARC</span><span style={{ ...stg.statValue, color: stg.emerald, fontSize: '14px', marginTop: '4px' }}>{e.dmarc.status}</span><span style={stg.statDelta}>policy: {e.dmarc.policy}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Deliveries 7d</span><span style={stg.statValue}>{e.deliveries7d.toLocaleString()}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Bounces 7d</span><span style={{ ...stg.statValue, color: stg.amber }}>{e.bounces7d}</span></div>
      </div>

      <div style={stg.split(400)}>
        <Card title="SMTP configuration">
          <Row label="Host"><input defaultValue={e.smtp.host} style={{ ...stg.inputMono, width: '260px' }} /></Row>
          <Row label="Port"><input defaultValue={e.smtp.port} style={{ ...stg.inputMono, width: '100px' }} /></Row>
          <Row label="Security"><select defaultValue={e.smtp.security} style={{ ...stg.select, width: '140px' }}>{['STARTTLS','TLS/SSL','None'].map(s => <option key={s}>{s}</option>)}</select></Row>
          <Row label="Username"><input defaultValue={e.smtp.username} style={{ ...stg.inputMono, width: '280px' }} /></Row>
          <Row label="Password"><input type="password" defaultValue="••••••••••••" style={{ ...stg.inputMono, width: '240px' }} /></Row>
        </Card>

        <Card title="DNS records · DKIM / SPF / DMARC">
          <Row label="SPF record" hint={e.spf.record}>
            <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Verified</span>
          </Row>
          <Row label="DKIM selector" hint={`Selector: ${e.dkim.selector}`}>
            <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Verified</span>
            <button style={stg.btnGhost}>Show key</button>
          </Row>
          <Row label="DMARC policy" hint={`policy=${e.dmarc.policy} pct=${e.dmarc.pct} rua=${e.dmarc.rua}`}>
            <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Verified</span>
          </Row>
        </Card>
      </div>

      <Card title="Email defaults">
        <Row label="From name"><input defaultValue={e.defaults.fromName} style={{ ...stg.input, width: '300px' }} /></Row>
        <Row label="From address"><input defaultValue={e.defaults.fromAddr} style={{ ...stg.inputMono, width: '320px' }} /></Row>
        <Row label="Reply-to"><input defaultValue={e.defaults.replyTo} style={{ ...stg.inputMono, width: '260px' }} /></Row>
      </Card>

      {/* #17 — Calendar sync granularity */}
      <CalendarSyncCard />

      <Card title={`Email signatures · ${sigs.length}`} action={<button style={stg.btnSecondary}>+ Signature</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Label</th>
              <th style={stg.th}>Owner</th>
              <th style={{ ...stg.th, textAlign: 'right' }}>Used by</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {sigs.map(s => (
              <tr key={s.id}>
                <td style={{ ...stg.td, fontWeight: 600 }}>{s.label}</td>
                <td style={{ ...stg.td, color: Ts_i.color.text.secondary }}>{s.owner}</td>
                <td style={{ ...stg.td, textAlign: 'right', fontFamily: Ts_i.font.mono, fontWeight: 700 }}>{s.usage}</td>
                <td style={{ ...stg.td, textAlign: 'right' }}><button style={stg.btnGhost}>Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

window.SettingsBilling = SettingsBilling;
window.SettingsIntegrations = SettingsIntegrations;
window.SettingsAPIWebhooks = SettingsAPIWebhooks;
window.SettingsEmail = SettingsEmail;
