// SETTINGS PLATFORM — Profile · Account · Preferences · Notifications
const Ts_p = window.ArbiterTokens;

function SettingsProfile({ data }) {
  const stg = window.__stg;
  const p = data.profile;
  const Card = window.SettingsSectionCard;
  const Row = window.SettingsRow;

  return (
    <div>
      <div style={stg.split(380)}>
        {/* Avatar + Identity */}
        <div style={stg.card}>
          <div style={stg.cardH}>Profile</div>
          <div style={{ ...stg.cardBody, display: 'flex', gap: '18px', alignItems: 'center' }}>
            <div style={{
              width: '84px', height: '84px', borderRadius: '50%',
              background: 'linear-gradient(135deg, #334155, #475569)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: '32px', fontWeight: 700, letterSpacing: '-0.02em',
              flexShrink: 0, boxShadow: '0 4px 14px rgba(0,0,0,0.18)',
            }}>{p.avatarInitials}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: '18px', fontWeight: 700, color: Ts_p.color.text.primary, letterSpacing: '-0.01em' }}>{p.name}</div>
              <div style={{ fontSize: '12px', color: Ts_p.color.text.secondary, marginTop: '2px' }}>{p.title}</div>
              <div style={{ fontSize: '11px', color: Ts_p.color.text.tertiary, marginTop: '6px' }}>Joined {p.joined} · Last sign-in {p.lastSignIn}</div>
              <div style={{ display: 'flex', gap: '6px', marginTop: '10px' }}>
                <button style={stg.btnSecondary}>Change photo</button>
                <button style={stg.btnGhost}>Remove</button>
              </div>
            </div>
          </div>
        </div>

        {/* Bar admissions */}
        <div style={stg.card}>
          <div style={stg.cardH}>
            <span>Bar admissions · {p.barAdmissions.length}</span>
            <button style={stg.btnSecondary}>+ Add</button>
          </div>
          <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
            {p.barAdmissions.map(state => (
              <div key={state} style={{
                display: 'grid', gridTemplateColumns: '1fr auto auto', gap: '10px', alignItems: 'center',
                padding: '10px 12px', background: Ts_p.color.bg.secondary, borderRadius: '6px', border: `1px solid ${Ts_p.color.border.light}`,
              }}>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Ts_p.color.text.primary }}>{state}</div>
                  <div style={{ fontSize: '10px', color: Ts_p.color.text.tertiary, fontFamily: Ts_p.font.mono }}>Bar # {p.barNumbers[state === 'California' ? 'CA' : state === 'New York' ? 'NY' : 'DC']}</div>
                </div>
                <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Active</span>
                <button style={stg.btnGhost}>Edit</button>
              </div>
            ))}
          </div>
        </div>
      </div>

      <Card title="Contact">
        <Row label="Work email"       hint="This is also your sign-in identity">
          <input defaultValue={p.email} style={{ ...stg.input, width: '320px' }} />
        </Row>
        <Row label="Phone"            hint="Used for 2FA fallback and outbound calls"><input defaultValue={p.phone} style={{ ...stg.input, width: '220px' }} /></Row>
        <Row label="Office"           hint="Default billing location"><input defaultValue={p.office} style={{ ...stg.input, width: '260px' }} /></Row>
        <Row label="Time zone"        hint="Used across calendar, time entries, deadlines">
          <select defaultValue={p.timezone} style={{ ...stg.select, width: '260px' }}>
            {['America/Los_Angeles','America/New_York','America/Chicago','America/Denver','Europe/London','Asia/Singapore','Asia/Tokyo'].map(z => <option key={z}>{z}</option>)}
          </select>
        </Row>
        <Row label="Language"         hint="UI language; date + number formats follow locale">
          <select defaultValue={p.language} style={{ ...stg.select, width: '200px' }}>
            {['en-US','en-GB','fr-FR','de-DE','es-ES','ja-JP','zh-CN'].map(l => <option key={l}>{l}</option>)}
          </select>
        </Row>
      </Card>
    </div>
  );
}

function SettingsAccount({ data }) {
  const stg = window.__stg;
  const a = data.account;
  const Card = window.SettingsSectionCard;
  const Row = window.SettingsRow;

  return (
    <div>
      <div style={stg.stripKpi}>
        <div style={stg.stat}><span style={stg.statLabel}>Password strength</span><span style={{ ...stg.statValue, color: stg.emerald }}>{a.password.strength}</span><span style={stg.statDelta}>Rotates in {a.password.expiresIn} d</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>MFA</span><span style={stg.statValue}>{a.mfa.enabled ? 'On' : 'Off'}</span><span style={stg.statDelta}>{a.mfa.method}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Backup codes</span><span style={stg.statValue}>{a.mfa.backupCodes}</span><span style={stg.statDelta}>of 10 remaining</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>Active sessions</span><span style={stg.statValue}>{a.sessions.length}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>SSO</span><span style={stg.statValue}>{a.sso.enabled ? a.sso.idp : 'Off'}</span><span style={stg.statDelta}>Last sync {a.sso.lastSync}</span></div>
        <div style={stg.stat}><span style={stg.statLabel}>API keys</span><span style={stg.statValue}>{a.apiKeys.length}</span></div>
      </div>

      <Card title="Password & sign-in" action={<button style={stg.btnSecondary}>Change password</button>}>
        <Row label="Last changed" hint={`Strength: ${a.password.strength} · must rotate every 90 days`}>
          <span style={{ fontSize: '12px', color: Ts_p.color.text.secondary, fontFamily: Ts_p.font.mono }}>{a.password.lastChanged}</span>
        </Row>
        <Row label="Multi-factor authentication" hint={`Method: ${a.mfa.method} (${a.mfa.appName}) · SMS fallback: ${a.mfa.phone}`}>
          <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Enabled</span>
          <button style={stg.btnSecondary}>Reconfigure</button>
        </Row>
        <Row label="Backup codes" hint="One-time codes for when you lose access to your authenticator"><button style={stg.btnSecondary}>Regenerate</button></Row>
        <Row label="SSO — Okta" hint={`IdP: ${a.sso.idp} · Entity ${a.sso.entityId}`}>
          <span style={{ ...stg.tag, ...stg.statusPill('ok') }}>Linked</span>
          <button style={stg.btnSecondary}>Manage</button>
        </Row>
        <Row label="Passkeys (WebAuthn)" hint="Hardware keys, Touch ID, Windows Hello"><button style={stg.btnSecondary}>+ Add passkey</button></Row>
      </Card>

      <Card title={`Active sessions · ${a.sessions.length}`} action={<button style={stg.btnDanger}>Sign out all others</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Device</th>
              <th style={stg.th}>Browser</th>
              <th style={stg.th}>Location</th>
              <th style={stg.th}>IP</th>
              <th style={stg.th}>Last active</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {a.sessions.map(s => (
              <tr key={s.id}>
                <td style={{ ...stg.td, fontWeight: 600 }}>
                  {s.device}
                  {s.current && <span style={{ ...stg.tag, ...stg.statusPill('ok'), marginLeft: '8px' }}>this device</span>}
                  {s.flagged && <span style={{ ...stg.tag, ...stg.statusPill('warn'), marginLeft: '8px' }}>! flagged</span>}
                </td>
                <td style={{ ...stg.td, color: Ts_p.color.text.secondary, fontSize: '11px' }}>{s.browser}</td>
                <td style={{ ...stg.td, color: Ts_p.color.text.secondary, fontSize: '11px' }}>{s.location}</td>
                <td style={{ ...stg.td, fontFamily: Ts_p.font.mono, color: Ts_p.color.text.tertiary, fontSize: '11px' }}>{s.ip}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_p.color.text.tertiary }}>{s.lastActive}</td>
                <td style={{ ...stg.td, textAlign: 'right' }}>
                  {!s.current && <button style={stg.btnDanger}>Revoke</button>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      <Card title={`Personal API keys · ${a.apiKeys.length}`} action={<button style={stg.btnPrimary}>+ Generate key</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Key ID</th>
              <th style={stg.th}>Name</th>
              <th style={stg.th}>Prefix</th>
              <th style={stg.th}>Scopes</th>
              <th style={stg.th}>Rate limit</th>
              <th style={stg.th}>Created</th>
              <th style={stg.th}>Last used</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {a.apiKeys.map(k => (
              <tr key={k.id}>
                <td style={{ ...stg.td, fontFamily: Ts_p.font.mono, fontWeight: 700, color: stg.steelDeep }}>{k.id}</td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{k.name} {k.warning && <span style={{ ...stg.tag, ...stg.statusPill('warn'), marginLeft: '6px' }}>legacy</span>}</td>
                <td style={{ ...stg.td, fontFamily: Ts_p.font.mono, color: Ts_p.color.text.tertiary }}>{k.prefix}•••</td>
                <td style={stg.td}>
                  {k.scopes.map(sc => <span key={sc} style={{ ...stg.tag, background: Ts_p.color.bg.secondary, color: Ts_p.color.text.secondary, fontFamily: Ts_p.font.mono, marginRight: '3px' }}>{sc}</span>)}
                </td>
                <td style={{ ...stg.td, fontFamily: Ts_p.font.mono, textAlign: 'right', color: Ts_p.color.text.secondary }}>{k.rateLimit}/m</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_p.color.text.tertiary, fontFamily: Ts_p.font.mono }}>{k.created}</td>
                <td style={{ ...stg.td, fontSize: '11px', color: Ts_p.color.text.tertiary }}>{k.lastUsed}</td>
                <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                  <button style={stg.btnGhost}>Rotate</button>
                  <button style={stg.btnDanger}>Revoke</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>
    </div>
  );
}

function SettingsPreferences({ data }) {
  const stg = window.__stg;
  const p = data.preferences;
  const Card = window.SettingsSectionCard;
  const Row = window.SettingsRow;
  const Toggle = window.SettingsToggle;
  const { useState } = React;
  const [prefs, setPrefs] = useState(p);
  const set = (k, v) => setPrefs({ ...prefs, [k]: v });

  return (
    <div>
      <Card title="Appearance">
        <Row label="Theme" hint="Light, dark, or follow system">
          <div style={{ display: 'flex', gap: '4px' }}>
            {['light','dark','system'].map(t => (
              <button key={t} onClick={() => set('theme', t)}
                style={{ ...stg.btnSecondary, background: prefs.theme === t ? stg.steelDeep : Ts_p.color.bg.card, color: prefs.theme === t ? '#fff' : Ts_p.color.text.secondary, borderColor: prefs.theme === t ? stg.steelDeep : Ts_p.color.border.medium, textTransform: 'capitalize' }}>
                {t}
              </button>
            ))}
          </div>
        </Row>
        <Row label="Density" hint="Compact trades row height for more data on screen">
          <div style={{ display: 'flex', gap: '4px' }}>
            {['compact','default','spacious'].map(t => (
              <button key={t} onClick={() => set('density', t)}
                style={{ ...stg.btnSecondary, background: prefs.density === t ? stg.steelDeep : Ts_p.color.bg.card, color: prefs.density === t ? '#fff' : Ts_p.color.text.secondary, borderColor: prefs.density === t ? stg.steelDeep : Ts_p.color.border.medium, textTransform: 'capitalize' }}>
                {t}
              </button>
            ))}
          </div>
        </Row>
        <Row label="Layout" hint="Sidebar or top navigation">
          <div style={{ display: 'flex', gap: '4px' }}>
            {['sidebar','topnav'].map(t => (
              <button key={t} onClick={() => set('layout', t)}
                style={{ ...stg.btnSecondary, background: prefs.layout === t ? stg.steelDeep : Ts_p.color.bg.card, color: prefs.layout === t ? '#fff' : Ts_p.color.text.secondary, borderColor: prefs.layout === t ? stg.steelDeep : Ts_p.color.border.medium }}>
                {t === 'sidebar' ? 'Sidebar' : 'Top nav'}
              </button>
            ))}
          </div>
        </Row>
        <Row label="Accent color" hint="Surfaces through charts, badges, primary buttons">
          <div style={{ display: 'flex', gap: '6px' }}>
            {[{k:'navy',c:'#0A1628'},{k:'steel',c:'#334155'},{k:'ocean',c:'#2563EB'},{k:'emerald',c:'#059669'},{k:'plum',c:'#7C3AED'}].map(opt => (
              <button key={opt.k} onClick={() => set('accentColor', opt.k)}
                style={{ width: '24px', height: '24px', borderRadius: '50%', background: opt.c, border: prefs.accentColor === opt.k ? '2px solid #fff' : '2px solid transparent', boxShadow: prefs.accentColor === opt.k ? `0 0 0 2px ${opt.c}` : 'none', cursor: 'pointer', padding: 0 }} />
            ))}
          </div>
        </Row>
      </Card>

      <Card title="Formats & locale">
        <Row label="Date format">
          <select defaultValue={p.dateFormat} style={{ ...stg.select, width: '180px' }}>{['MM/DD/YYYY','DD/MM/YYYY','YYYY-MM-DD','D MMM YYYY'].map(f => <option key={f}>{f}</option>)}</select>
        </Row>
        <Row label="Time format">
          <div style={{ display: 'flex', gap: '4px' }}>
            {['12h','24h'].map(t => (
              <button key={t} style={{ ...stg.btnSecondary, background: prefs.timeFormat === t ? stg.steelDeep : Ts_p.color.bg.card, color: prefs.timeFormat === t ? '#fff' : Ts_p.color.text.secondary, borderColor: prefs.timeFormat === t ? stg.steelDeep : Ts_p.color.border.medium }} onClick={() => set('timeFormat', t)}>{t}</button>
            ))}
          </div>
        </Row>
        <Row label="Week starts on">
          <select defaultValue={p.firstDayOfWeek} style={{ ...stg.select, width: '140px' }}>{['Sunday','Monday','Saturday'].map(d => <option key={d}>{d}</option>)}</select>
        </Row>
        <Row label="Currency">
          <select defaultValue={p.currency} style={{ ...stg.select, width: '120px' }}>{['USD','GBP','EUR','SGD','JPY','CAD'].map(c => <option key={c}>{c}</option>)}</select>
        </Row>
        <Row label="Number format">
          <select defaultValue={p.numberFormat} style={{ ...stg.select, width: '150px' }}>{['1,234.56','1.234,56','1 234,56'].map(n => <option key={n}>{n}</option>)}</select>
        </Row>
      </Card>

      <Card title="Workspace">
        <Row label="Start page" hint="The view Arbiter opens to when you sign in">
          <select defaultValue={p.startPage} style={{ ...stg.select, width: '200px' }}>{['dashboard','matters','calendar','tasks','documents','billing'].map(s => <option key={s}>{s}</option>)}</select>
        </Row>
        <Toggle label="Keyboard shortcuts" hint="Cmd-K command palette, per-view shortcuts" on={prefs.keyboardShortcuts} onChange={v => set('keyboardShortcuts', v)} />
        <Toggle label="Sound effects" hint="Confirmation sounds for filings, timer events" on={prefs.soundEffects} onChange={v => set('soundEffects', v)} />
        <Toggle label="Reduced motion" hint="Disable animated transitions and chart motion" on={prefs.reducedMotion} onChange={v => set('reducedMotion', v)} />
        <Toggle label="High-contrast mode" hint="Boost color contrast for WCAG AAA compliance" on={prefs.highContrast} onChange={v => set('highContrast', v)} />
      </Card>
    </div>
  );
}

function SettingsNotifications({ data }) {
  const stg = window.__stg;
  const n = data.notifications;
  const Card = window.SettingsSectionCard;
  const Toggle = window.SettingsToggle;
  const Row = window.SettingsRow;

  return (
    <div>
      <Card title="Delivery channels">
        <div style={stg.cardGrid(260)}>
          {n.channels.map(c => (
            <div key={c.id} style={{
              padding: '14px', border: `1px solid ${c.on ? stg.steelBorder : Ts_p.color.border.light}`,
              borderRadius: '8px', background: c.on ? stg.steelBg : Ts_p.color.bg.card, margin: '8px',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_p.color.text.primary }}>{c.label}</div>
                <div style={stg.toggle(c.on)}><div style={stg.toggleKnob(c.on)} /></div>
              </div>
              <div style={{ fontSize: '11px', color: Ts_p.color.text.tertiary, fontFamily: Ts_p.font.mono }}>{c.dest}</div>
            </div>
          ))}
        </div>
      </Card>

      <div style={stg.split(400)}>
        <Card title="Quiet hours">
          <Toggle label="Enable quiet hours" hint="Mute push + SMS during your quiet window" on={n.quietHours.enabled} />
          <Row label="From"><input type="time" defaultValue={n.quietHours.start} style={{ ...stg.input, width: '140px' }} /></Row>
          <Row label="To"><input type="time" defaultValue={n.quietHours.end} style={{ ...stg.input, width: '140px' }} /></Row>
          <Toggle label="Apply on weekends" hint="Extends quiet hours to Saturday + Sunday" on={n.quietHours.weekends} />
        </Card>
        <Card title="Daily digest">
          <Toggle label="Enable digest" hint="One email summarizing all low-priority events" on={n.digest.enabled} />
          <Row label="Cadence">
            <select defaultValue={n.digest.cadence} style={{ ...stg.select, width: '160px' }}>{['daily','weekly','never'].map(c => <option key={c}>{c}</option>)}</select>
          </Row>
          <Row label="Delivery time"><input type="time" defaultValue={n.digest.time} style={{ ...stg.input, width: '140px' }} /></Row>
        </Card>
      </div>

      <Card title={`Event rules · ${n.eventRules.length}`} action={<button style={stg.btnSecondary}>+ Add rule</button>}>
        <div style={stg.tableWrap}>
        <table style={stg.tableFixed}>
          <thead>
            <tr>
              <th style={stg.th}>Enabled</th>
              <th style={stg.th}>Event</th>
              <th style={stg.th}>Severity</th>
              <th style={stg.th}>Channels</th>
              <th style={stg.th}></th>
            </tr>
          </thead>
          <tbody>
            {n.eventRules.map(r => (
              <tr key={r.id}>
                <td style={stg.td}><div style={stg.toggle(r.on)}><div style={stg.toggleKnob(r.on)} /></div></td>
                <td style={{ ...stg.td, fontWeight: 600 }}>{r.event}</td>
                <td style={stg.td}><span style={{ ...stg.tag, background: `${stg.severityColor(r.severity)}15`, color: stg.severityColor(r.severity) }}>{r.severity}</span></td>
                <td style={stg.td}>{r.channels.map(ch => <span key={ch} style={{ ...stg.tag, background: Ts_p.color.bg.secondary, color: Ts_p.color.text.secondary, marginRight: '3px' }}>{ch}</span>)}</td>
                <td style={{ ...stg.td, textAlign: 'right' }}><button style={stg.btnGhost}>Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      </Card>

      {/* #13 — Slack / Teams per-event channel routing */}
      <SlackTeamsRoutingCard />
    </div>
  );
}

function SlackTeamsRoutingCard() {
  const stg = window.__stg;
  const Card = window.SettingsSectionCard;
  const infra = window.__stg_infra || {};
  const toast = (infra.useToast && infra.useToast()) || { push: () => {} };

  const [workspaces, setWorkspaces] = React.useState([
    { id: 'slack-firm',    platform: 'Slack',         name: 'saadein-law.slack.com',    connected: true,  events30d: 28412 },
    { id: 'teams-firm',    platform: 'Microsoft Teams', name: 'Saadein Law · Tenant',    connected: true,  events30d: 12081 },
    { id: 'slack-clients', platform: 'Slack',         name: 'client-connect.slack.com', connected: false, events30d: 0     },
  ]);

  const [routes, setRoutes] = React.useState([
    { id: 'R1', event: 'matter.opened',         sev: 'info',  platform: 'Slack', channel: '#matters-new',             throttle: 'none',    mention: '',             test: 'idle' },
    { id: 'R2', event: 'matter.closed',         sev: 'info',  platform: 'Slack', channel: '#matters-new',             throttle: 'none',    mention: '',             test: 'idle' },
    { id: 'R3', event: 'deadline.approaching',  sev: 'warn',  platform: 'Slack', channel: '#litigation-deadlines',    throttle: 'digest-15m', mention: '@here',     test: 'idle' },
    { id: 'R4', event: 'invoice.overdue',       sev: 'warn',  platform: 'Teams', channel: 'Finance › Collections',    throttle: 'none',    mention: '',             test: 'idle' },
    { id: 'R5', event: 'security.login.failed', sev: 'warn',  platform: 'Teams', channel: 'IT › Security alerts',     throttle: 'digest-5m', mention: '@SecOps',    test: 'idle' },
    { id: 'R6', event: 'security.mfa.disabled', sev: 'high',  platform: 'Slack', channel: '#security-alerts',         throttle: 'none',    mention: '@security-oncall', test: 'idle' },
    { id: 'R7', event: 'hold.custodian.ack',    sev: 'info',  platform: 'Teams', channel: 'Compliance › Holds',       throttle: 'digest-60m', mention: '',         test: 'idle' },
    { id: 'R8', event: 'integration.failed',    sev: 'high',  platform: 'Slack', channel: '#platform-oncall',         throttle: 'none',    mention: '@oncall',      test: 'idle' },
  ]);

  const slackChannels = ['#matters-new', '#litigation-deadlines', '#security-alerts', '#platform-oncall', '#finance-collections', '#dev-null'];
  const teamsChannels = ['IT › Security alerts', 'Finance › Collections', 'Compliance › Holds', 'Partners › Digest', 'Platform › Oncall'];

  function updateRoute(id, patch) {
    setRoutes(rs => rs.map(r => r.id === id ? { ...r, ...patch } : r));
  }
  function testRoute(r) {
    updateRoute(r.id, { test: 'pending' });
    setTimeout(() => {
      updateRoute(r.id, { test: 'ok' });
      toast.push({ kind: 'success', title: `Test posted to ${r.channel}`, message: `${r.platform} · ${r.event}` });
    }, 700);
  }

  return (
    <React.Fragment>
      <Card
        title="Slack / Teams workspaces"
        action={<button style={stg.btnSecondary} onClick={() => toast.push({ kind: 'info', title: 'OAuth launched', message: 'Complete auth in popup' })}>+ Connect workspace</button>}
      >
        <div style={stg.cardGrid(260)}>
          {workspaces.map(w => (
            <div key={w.id} style={{
              padding: '14px', margin: '8px',
              border: `1px solid ${w.connected ? stg.steelBorder : Ts_p.color.border.light}`,
              borderRadius: '8px', background: w.connected ? stg.steelBg : Ts_p.color.bg.card,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                <div style={{ fontSize: '10px', fontWeight: 700, color: stg.steelDeep, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{w.platform}</div>
                <span style={{ ...stg.tag, background: w.connected ? stg.emeraldBg : Ts_p.color.bg.secondary, color: w.connected ? stg.emerald : Ts_p.color.text.tertiary }}>{w.connected ? 'Connected' : 'Not linked'}</span>
              </div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: Ts_p.color.text.primary }}>{w.name}</div>
              <div style={{ fontSize: '11px', color: Ts_p.color.text.tertiary, fontFamily: Ts_p.font.mono, marginTop: '4px' }}>{w.connected ? `${w.events30d.toLocaleString()} posts / 30d` : '—'}</div>
              <div style={{ display: 'flex', gap: '4px', marginTop: '8px' }}>
                {w.connected
                  ? (<>
                      <button style={stg.btnGhost} onClick={() => toast.push({ kind: 'success', title: `Test message sent to ${w.name}` })}>Test</button>
                      <button style={stg.btnGhost}>Scopes</button>
                      <button style={stg.btnGhost} onClick={() => setWorkspaces(ws => ws.map(x => x.id === w.id ? { ...x, connected: false } : x))}>Disconnect</button>
                    </>)
                  : (<button style={stg.btnSecondary} onClick={() => { setWorkspaces(ws => ws.map(x => x.id === w.id ? { ...x, connected: true } : x)); toast.push({ kind: 'success', title: `Connected ${w.name}` }); }}>Connect</button>)}
              </div>
            </div>
          ))}
        </div>
      </Card>

      <Card title={`Per-event channel routing · ${routes.length}`} action={<button style={stg.btnPrimary} onClick={() => toast.push({ kind: 'info', title: 'New route builder opened' })}>+ Route</button>}>
        <div style={stg.tableWrap}>
          <table style={stg.tableFixed}>
            <thead>
              <tr>
                <th style={stg.th}>Event</th>
                <th style={stg.th}>Severity</th>
                <th style={stg.th}>Platform</th>
                <th style={stg.th}>Channel</th>
                <th style={stg.th}>Throttle / digest</th>
                <th style={stg.th}>Mention</th>
                <th style={stg.th}></th>
              </tr>
            </thead>
            <tbody>
              {routes.map(r => {
                const channels = r.platform === 'Slack' ? slackChannels : teamsChannels;
                return (
                  <tr key={r.id}>
                    <td style={{ ...stg.td, fontFamily: Ts_p.font.mono, fontSize: '11px', fontWeight: 600, color: stg.steelDeep }}>{r.event}</td>
                    <td style={stg.td}><span style={{ ...stg.tag, background: `${stg.severityColor(r.sev)}15`, color: stg.severityColor(r.sev) }}>{r.sev}</span></td>
                    <td style={stg.td}>
                      <select value={r.platform} onChange={e => updateRoute(r.id, { platform: e.target.value, channel: e.target.value === 'Slack' ? slackChannels[0] : teamsChannels[0] })}
                        style={{ ...stg.select, width: '110px', fontSize: '11px' }}>
                        <option>Slack</option><option>Teams</option>
                      </select>
                    </td>
                    <td style={stg.td}>
                      <select value={r.channel} onChange={e => updateRoute(r.id, { channel: e.target.value })}
                        style={{ ...stg.select, width: '200px', fontFamily: Ts_p.font.mono, fontSize: '11px' }}>
                        {channels.map(c => <option key={c}>{c}</option>)}
                      </select>
                    </td>
                    <td style={stg.td}>
                      <select value={r.throttle} onChange={e => updateRoute(r.id, { throttle: e.target.value })}
                        style={{ ...stg.select, width: '150px', fontSize: '11px' }}>
                        <option value="none">No throttle</option>
                        <option value="digest-5m">Digest · 5m</option>
                        <option value="digest-15m">Digest · 15m</option>
                        <option value="digest-60m">Digest · 60m</option>
                        <option value="digest-daily">Digest · daily</option>
                        <option value="rate-10pm">Rate-limit · 10/min</option>
                      </select>
                    </td>
                    <td style={stg.td}>
                      <input value={r.mention} placeholder="e.g. @here" onChange={e => updateRoute(r.id, { mention: e.target.value })}
                        style={{ ...stg.input, width: '130px', fontFamily: Ts_p.font.mono, fontSize: '11px' }} />
                    </td>
                    <td style={{ ...stg.td, textAlign: 'right', whiteSpace: 'nowrap' }}>
                      <button style={stg.btnGhost} onClick={() => testRoute(r)} disabled={r.test === 'pending'}>
                        {r.test === 'pending' ? '● …' : r.test === 'ok' ? 'ok Test' : 'Test'}
                      </button>
                      <button style={stg.btnGhost}>Filter</button>
                      <button style={stg.btnGhost}>×</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div style={{ padding: '10px 16px', borderTop: `1px solid ${Ts_p.color.border.light}`, background: Ts_p.color.bg.secondary, fontSize: '11px', color: Ts_p.color.text.tertiary }}>
          Routes evaluate in order; first match wins. Digest windows coalesce into a single post per window. High-severity events ignore digest and fire immediately.
        </div>
      </Card>
    </React.Fragment>
  );
}

window.SettingsProfile = SettingsProfile;
window.SettingsAccount = SettingsAccount;
window.SettingsPreferences = SettingsPreferences;
window.SettingsNotifications = SettingsNotifications;
