// settings-extra-2.jsx — Settings sub-pages part 2/3
// About, Activity Recorder, Agents, Chat behavior, Chrome Relay, Computer Use, Contacts, Data
// Mono · Liquid Glass · macOS chrome

// ═════════════════════════════════════════════════════════════
// Shared helpers (some imported from settings-extra.jsx)
// ═════════════════════════════════════════════════════════════
function S2_StatusDot({ status = 'on', size = 8 }) {
  const colors = { on: '#28c840', warn: '#febc2e', off: '#ff5f57', pending: '#febc2e' };
  return <div style={{ width: size, height: size, borderRadius: size/2, background: colors[status], flexShrink: 0 }} />;
}

function S2_Toggle({ on, dark }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{
      width: 30, height: 18, borderRadius: 9,
      background: on ? t.fg : t.surface2,
      border: `1px solid ${on ? t.fg : t.border}`,
      display: 'flex', alignItems: 'center',
      padding: 1, cursor: 'pointer', flexShrink: 0,
    }}>
      <div style={{
        width: 14, height: 14, borderRadius: 7,
        background: on ? t.bg : t.fg2,
        marginLeft: on ? 12 : 0,
        transition: 'margin-left .15s',
      }} />
    </div>
  );
}

function S2_PageHeader({ dark, title, sub, right }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{ padding: '4px 0 18px', borderBottom: `0.5px solid ${t.border}`, marginBottom: 18, display: 'flex', alignItems: 'flex-end', gap: 16 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.6 }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: t.fg3, marginTop: 4 }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

function S2_Section({ dark, title, sub, children, style = {} }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{ marginBottom: 22, ...style }}>
      {title && <div style={{ fontSize: 11, fontWeight: 600, color: t.fg2, letterSpacing: 0.6, textTransform: 'uppercase', fontFamily: G.mono, marginBottom: 8 }}>{title}</div>}
      {sub && <div style={{ fontSize: 11.5, color: t.fg3, marginBottom: 10, lineHeight: 1.5 }}>{sub}</div>}
      {children}
    </div>
  );
}

function S2_Row({ dark, label, value, right, last }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{
      padding: '12px 14px',
      display: 'flex', alignItems: 'center', gap: 12,
      borderBottom: last ? 'none' : `0.5px solid ${t.border2}`,
    }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: t.fg }}>{label}</div>
        {value && <div style={{ fontSize: 11, color: t.fg3, marginTop: 2 }}>{value}</div>}
      </div>
      {right}
    </div>
  );
}

function S2_Card({ dark, children, style = {} }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{
      background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
      overflow: 'hidden',
      ...style,
    }}>{children}</div>
  );
}


// ═════════════════════════════════════════════════════════════
// A · ABOUT
// ═════════════════════════════════════════════════════════════
function AboutSettings({ dark, state = 'idle' }) {
  const t = dark ? G.d : G.l;
  const versionState = {
    idle:        { tag: '',                  msg: 'You are on the latest stable build.', cta: 'Check for updates' },
    checking:    { tag: 'Checking…',         msg: 'Looking for updates over the secure channel.', cta: 'Cancel', spinning: true },
    available:   { tag: 'Update available',  msg: 'Ghast 2.4.1 is available — 38 MB.',      cta: 'Download & install', accent: true },
    downloading: { tag: 'Downloading 62%',   msg: 'Ghast 2.4.1 · 24 MB / 38 MB · 1.4 MB/s', cta: 'Cancel', progress: 0.62 },
    'ready-restart': { tag: 'Ready to install', msg: 'Update will apply on your next quit, or restart now.', cta: 'Restart now', accent: true },
    failed:      { tag: 'Update failed',     msg: 'Lost connection at 24 MB. Partial download kept — you can resume.', cta: 'Resume', danger: true },
    disabled:    { tag: 'Auto-update off',   msg: "Auto-update is disabled. You'll have to check manually.", cta: 'Enable in General' },
    latest:      { tag: 'Up to date',        msg: 'You are on the latest stable build.', cta: 'Check again' },
  }[state] || {};

  const changelog = [
    { v: '2.4.0', d: 'Mar 28', notes: 'Wallet sub-tabs · Voice button on assistant replies · Chrome Relay reconnect.' },
    { v: '2.3.4', d: 'Mar 14', notes: 'Faster cold-boot · Telegram channel rules editor · MCP store.' },
    { v: '2.3.3', d: 'Mar 02', notes: 'Computer Use safety whitelist · Activity Recorder pause shortcuts.' },
    { v: '2.3.2', d: 'Feb 19', notes: 'Skill marketplace search · Memory pinned-fact UI.' },
    { v: '2.3.1', d: 'Feb 04', notes: 'Provider OAuth flows · DB recovery banner.' },
  ];

  return (
    <>
      <S2_PageHeader dark={dark} title="About" sub="Version, release channel, and credits." />

      {/* Hero card */}
      <S2_Card dark={dark} style={{ padding: 20, marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <GhastLogo size={56} dark={dark} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: -0.4 }}>Ghast Desktop</div>
            <div style={{ display: 'flex', gap: 10, marginTop: 4, alignItems: 'center', flexWrap: 'wrap' }}>
              <span style={{ fontSize: 12, color: t.fg3, fontFamily: G.mono }}>2.4.0 · stable</span>
              <span style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono }}>build a8f3-bc1e</span>
              {versionState.tag && (
                <span style={{
                  fontSize: 10, padding: '2px 7px', borderRadius: 4,
                  background: versionState.accent ? t.fg : t.surface2,
                  color: versionState.accent ? t.bg : t.fg2,
                  fontFamily: G.mono, letterSpacing: 0.4,
                }}>{versionState.tag}</span>
              )}
            </div>
            <div style={{ fontSize: 11.5, color: t.fg3, marginTop: 8 }}>{versionState.msg}</div>
          </div>
          <Button variant={versionState.accent ? 'primary' : (versionState.danger ? 'secondary' : 'secondary')} size="sm">
            {versionState.spinning && <span style={{ marginRight: 6, display: 'inline-block', width: 8, height: 8, border: `1.5px solid ${t.fg3}`, borderTopColor: 'transparent', borderRadius: 4, animation: 'spin 1s linear infinite' }} />}
            {versionState.cta}
          </Button>
        </div>
        {/* Inline progress bar — only when actively downloading */}
        {versionState.progress != null && (
          <div style={{ marginTop: 14, height: 3, background: t.surface2, borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: `${Math.round(versionState.progress * 100)}%`, height: '100%', background: t.fg, transition: 'width .3s ease' }} />
          </div>
        )}
      </S2_Card>

      {/* Channel */}
      <S2_Section dark={dark} title="Release channel">
        <S2_Card dark={dark}>
          <div style={{ padding: 4 }}>
            <div style={{ display: 'flex', gap: 4, padding: 4, background: t.surface2, borderRadius: 8 }}>
              {[
                { id: 'stable', label: 'Stable', desc: 'Ships every ~6 weeks.', sel: true },
                { id: 'beta',   label: 'Beta',   desc: 'Weekly. Bugs welcome.', sel: false },
                { id: 'dev',    label: 'Dev',    desc: 'Internal. Things break.', sel: false },
              ].map((c) => (
                <div key={c.id} style={{
                  flex: 1, padding: '10px 12px', borderRadius: 6,
                  background: c.sel ? t.bg : 'transparent',
                  border: c.sel ? `1px solid ${t.border}` : 'none',
                  cursor: 'pointer',
                }}>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{c.label}</div>
                  <div style={{ fontSize: 10.5, color: t.fg3, marginTop: 2 }}>{c.desc}</div>
                </div>
              ))}
            </div>
          </div>
        </S2_Card>
      </S2_Section>

      {/* Changelog */}
      <S2_Section dark={dark} title="Recent changes">
        <S2_Card dark={dark}>
          {changelog.map((c, i) => (
            <div key={c.v} style={{
              padding: '12px 14px', display: 'flex', gap: 14,
              borderBottom: i === changelog.length - 1 ? 'none' : `0.5px solid ${t.border2}`,
            }}>
              <div style={{ width: 64, flexShrink: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 600, fontFamily: G.mono }}>{c.v}</div>
                <div style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono }}>{c.d}</div>
              </div>
              <div style={{ fontSize: 12, color: t.fg2, lineHeight: 1.55 }}>{c.notes}</div>
            </div>
          ))}
          <div style={{ padding: '10px 14px', borderTop: `0.5px solid ${t.border2}`, fontSize: 11, color: t.fg2, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
            View full changelog <Icon name="ext" size={11} color={t.fg2} />
          </div>
        </S2_Card>
      </S2_Section>

      {/* Help & legal */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 22 }}>
        <S2_Card dark={dark}>
          <div style={{ padding: '10px 14px', fontSize: 11, fontWeight: 600, color: t.fg2, letterSpacing: 0.6, textTransform: 'uppercase', fontFamily: G.mono, borderBottom: `0.5px solid ${t.border2}` }}>Help</div>
          {[
            ['Documentation', 'docs.ghast.app'],
            ['Discord community', 'discord.gg/ghast'],
            ['GitHub issues', 'github.com/ghast/ghast'],
            ['Email support', 'support@ghast.app'],
          ].map(([k, v], i) => (
            <div key={k} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5 }}>{k}</div>
                <div style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono, marginTop: 1 }}>{v}</div>
              </div>
              <Icon name="ext" size={12} color={t.fg3} />
            </div>
          ))}
        </S2_Card>
        <S2_Card dark={dark}>
          <div style={{ padding: '10px 14px', fontSize: 11, fontWeight: 600, color: t.fg2, letterSpacing: 0.6, textTransform: 'uppercase', fontFamily: G.mono, borderBottom: `0.5px solid ${t.border2}` }}>Legal</div>
          {[
            'Software License',
            'Privacy Policy',
            'Terms of Service',
            'Open Source Licenses (124)',
          ].map((k, i) => (
            <div key={k} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center' }}>
              <div style={{ flex: 1, fontSize: 12.5 }}>{k}</div>
              <Icon name="chevronRight" size={12} color={t.fg3} />
            </div>
          ))}
        </S2_Card>
      </div>

      {/* System info */}
      <S2_Section dark={dark} title="System">
        <S2_Card dark={dark} style={{ padding: 14, fontFamily: G.mono, fontSize: 11.5, color: t.fg2, lineHeight: 1.7 }}>
          <div><span style={{ color: t.fg3 }}>os         </span>macOS 14.4.1 (Sonoma) · arm64</div>
          <div><span style={{ color: t.fg3 }}>chip       </span>Apple M3 Max</div>
          <div><span style={{ color: t.fg3 }}>electron   </span>30.0.6</div>
          <div><span style={{ color: t.fg3 }}>node       </span>20.11.1</div>
          <div><span style={{ color: t.fg3 }}>chromium   </span>124.0.6367.118</div>
          <div><span style={{ color: t.fg3 }}>data dir   </span>~/Library/Application Support/Ghast</div>
        </S2_Card>
      </S2_Section>

      <style>{`@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }`}</style>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// B · ACTIVITY RECORDER
// ═════════════════════════════════════════════════════════════
function ActivityRecorderSettings({ dark, state = 'recording', blacklistCount = 3 }) {
  const t = dark ? G.d : G.l;
  const stateInfo = {
    disabled:  { dot: 'off',  badge: 'Disabled',    msg: 'Recording is off. Turn on to start indexing your screen.', tone: t.fg3 },
    recording: { dot: 'on',   badge: 'Recording',   msg: 'Capturing one frame every 2 seconds.', tone: t.fg },
    paused:    { dot: 'warn', badge: 'Paused',      msg: 'Auto-paused because Banking.app is in the foreground.', tone: '#febc2e' },
    clearing:  { dot: 'warn', badge: 'Clearing…',   msg: 'Removing 124,392 frames and OCR index. ~28 sec remaining.', tone: '#febc2e' },
  }[state];

  const blacklist = [
    'com.apple.Keychain',
    'com.banking.MyBank',
    'com.1password.1password7',
    'com.lastpass.LastPass',
    'com.bitwarden.desktop',
  ].slice(0, blacklistCount);

  return (
    <>
      <S2_PageHeader dark={dark} title="Activity Recorder" sub="Locally-indexed screen history that powers spotlight & memory search." />

      <S2_Card dark={dark} style={{ padding: 18, marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 22, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
            <Icon name="eye" size={20} color={stateInfo.tone} />
            {state === 'recording' && <div style={{ position: 'absolute', top: 4, right: 4, width: 6, height: 6, borderRadius: 3, background: '#ff5f57' }} />}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <S2_StatusDot status={stateInfo.dot} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>{stateInfo.badge}</span>
              <span style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.3 }}>since 09:14 today</span>
            </div>
            <div style={{ fontSize: 11.5, color: t.fg3 }}>{stateInfo.msg}</div>
          </div>
          <S2_Toggle on={state === 'recording' || state === 'paused'} dark={dark} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 1, background: t.border2, marginTop: 16, border: `0.5px solid ${t.border}`, borderRadius: 8, overflow: 'hidden' }}>
          {[
            ['Recorded', '124,392 frames'],
            ['Index size', '1.84 GB'],
            ['OCR hits', '38,217 strings'],
          ].map(([k, v]) => (
            <div key={k} style={{ padding: '12px 14px', background: t.surface }}>
              <div style={{ fontSize: 10, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, textTransform: 'uppercase' }}>{k}</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4, fontFamily: G.mono }}>{v}</div>
            </div>
          ))}
        </div>
      </S2_Card>

      <S2_Section dark={dark} title="Storage">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Storage path" value="~/Library/Application Support/Ghast/recorder" right={<Button variant="secondary" size="sm">Reveal</Button>} />
          <S2_Row dark={dark} label="Retention window" value="Frames older than this are deleted automatically." right={
            <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
              {['7d', '30d', '90d', 'Forever'].map((r, i) => (
                <div key={r} style={{ padding: '4px 10px', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, background: i === 1 ? t.bg : 'transparent', border: i === 1 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
              ))}
            </div>
          } />
          <S2_Row dark={dark} label="Capture interval" value="One frame every 2 seconds." right={<span style={{ fontSize: 12, fontFamily: G.mono, color: t.fg2 }}>2s</span>} last />
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Privacy · app blacklist" sub="When any of these apps is frontmost, recording auto-pauses and the buffer is dropped.">
        <S2_Card dark={dark}>
          {blacklist.map((b, i) => (
            <div key={b} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="lock" size={12} color={t.fg3} />
              <div style={{ flex: 1, fontSize: 12.5, fontFamily: G.mono }}>{b}</div>
              <Icon name="close" size={12} color={t.fg3} style={{ cursor: 'pointer' }} />
            </div>
          ))}
          <div style={{ padding: '10px 14px', borderTop: `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="plus" size={12} color={t.fg2} />
            <input placeholder="com.example.app" style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', fontSize: 12, color: t.fg, fontFamily: G.mono }} readOnly />
            <Button variant="secondary" size="sm">Add</Button>
          </div>
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Danger zone">
        <S2_Card dark={dark} style={{ borderColor: state === 'clearing' ? '#ff5f57' : t.border }}>
          <div style={{ padding: 14, display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Clear all recordings</div>
              <div style={{ fontSize: 11, color: t.fg3, marginTop: 2 }}>Removes every frame and the OCR index. Cannot be undone.</div>
            </div>
            <Button variant="danger" size="sm">{state === 'clearing' ? 'Clearing… 32%' : 'Clear all'}</Button>
          </div>
        </S2_Card>
      </S2_Section>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// C · AGENTS
// ═════════════════════════════════════════════════════════════
function AgentsSettings({ dark, state = 'list', custom = 0 }) {
  const t = dark ? G.d : G.l;

  const builtin = [
    { id: 'guide',    name: 'ghast-guide',    desc: 'Helps onboard new users. Walks the UI, explains commands.', tools: 8,  model: 'Ghast 2 Pro',  builtin: true },
    { id: 'operator', name: 'ghast-operator', desc: 'Runs computer-use & relay tasks. Has elevated tool access.', tools: 24, model: 'Ghast 2 Pro',  builtin: true },
  ];
  const customAgents = [
    { id: 'pr-rev',   name: 'pr-reviewer',    desc: 'Reviews diffs against repo style guide.',                    tools: 6,  model: 'Ghast 2 Pro' },
    { id: 'inbox',    name: 'inbox-triage',   desc: 'Sorts your Telegram & email backlog.',                       tools: 5,  model: 'Ghast 2 Fast' },
    { id: 'reader',   name: 'paper-reader',   desc: 'Reads arXiv pdfs and writes a 5-bullet summary.',            tools: 3,  model: 'Local Llama' },
  ].slice(0, custom);
  const all = [...builtin, ...customAgents];

  if (state === 'editing') {
    return (
      <>
        <S2_PageHeader dark={dark} title="Edit agent · pr-reviewer" sub="Custom agents have their own system prompt and a constrained tool list." right={
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" size="sm">Cancel</Button>
            <Button variant="primary" size="sm">Save</Button>
          </div>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: 18 }}>
          <div>
            <S2_Section dark={dark} title="Identity">
              <S2_Card dark={dark}>
                <S2_Row dark={dark} label="Name" right={<input defaultValue="pr-reviewer" style={{ width: 200, height: 26, padding: '0 8px', fontSize: 12, fontFamily: G.mono, background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 6, color: t.fg }} />} />
                <S2_Row dark={dark} label="Description" right={<input defaultValue="Reviews diffs against repo style guide." style={{ width: 280, height: 26, padding: '0 8px', fontSize: 12, background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 6, color: t.fg }} />} last />
              </S2_Card>
            </S2_Section>

            <S2_Section dark={dark} title="System prompt">
              <S2_Card dark={dark} style={{ padding: 12 }}>
                <textarea defaultValue={`You are pr-reviewer, an assistant that reviews diffs.\n\nWhen given a PR:\n1. Read the diff in full.\n2. Cross-reference against ./docs/style.md.\n3. Output up to 5 bullet points of feedback, ranked by impact.\n4. Never block on stylistic nitpicks below "should".\n\nIf the diff is >800 lines, request a split.`} style={{ width: '100%', minHeight: 180, background: 'transparent', border: 'none', outline: 'none', resize: 'vertical', fontFamily: G.mono, fontSize: 12, lineHeight: 1.55, color: t.fg }} />
                <div style={{ borderTop: `0.5px solid ${t.border2}`, marginTop: 8, paddingTop: 8, display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: t.fg3, fontFamily: G.mono }}>
                  <span>184 tokens · 12 lines</span>
                  <span>{`{{user_name}} · {{workspace_path}} · {{date}}`}</span>
                </div>
              </S2_Card>
            </S2_Section>

            <S2_Section dark={dark} title="Allowed tools">
              <S2_Card dark={dark}>
                {[
                  ['read_file',          true,  'Read source files.'],
                  ['grep',               true,  'Regex search across the workspace.'],
                  ['git_diff',           true,  'Read pending diffs.'],
                  ['github_pr_comment',  true,  'Post review comments on a PR.'],
                  ['shell',              false, 'Execute shell commands.'],
                  ['computer_use',       false, 'Drive UI on the user\'s behalf.'],
                  ['web_fetch',          true,  'Fetch external URLs.'],
                  ['web_search',         true,  'Search the web.'],
                ].map(([name, on, desc], i) => (
                  <div key={name} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontFamily: G.mono }}>{name}</div>
                      <div style={{ fontSize: 10.5, color: t.fg3, marginTop: 1 }}>{desc}</div>
                    </div>
                    <S2_Toggle on={on} dark={dark} />
                  </div>
                ))}
              </S2_Card>
            </S2_Section>
          </div>
          <div>
            <S2_Section dark={dark} title="Default model">
              <S2_Card dark={dark}>
                {['Ghast 2 Pro', 'Ghast 2 Fast', 'Llama 3.3 70B (local)', 'GPT-5'].map((m, i) => (
                  <div key={m} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <div style={{ width: 14, height: 14, borderRadius: 7, border: `1px solid ${i === 0 ? t.fg : t.border}`, background: i === 0 ? t.fg : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      {i === 0 && <div style={{ width: 5, height: 5, borderRadius: 3, background: t.bg }} />}
                    </div>
                    <span style={{ fontSize: 12 }}>{m}</span>
                  </div>
                ))}
              </S2_Card>
            </S2_Section>
            <S2_Section dark={dark} title="Trigger">
              <S2_Card dark={dark}>
                <S2_Row dark={dark} label="Slash command" right={<span style={{ fontSize: 12, fontFamily: G.mono, color: t.fg2 }}>/review</span>} />
                <S2_Row dark={dark} label="Keyboard shortcut" right={<div style={{ display: 'flex', gap: 3 }}><Kbd>⌘</Kbd><Kbd>⇧</Kbd><Kbd>R</Kbd></div>} />
                <S2_Row dark={dark} label="On PR open" value="Auto-run when a new PR appears." right={<S2_Toggle on={false} dark={dark} />} last />
              </S2_Card>
            </S2_Section>
          </div>
        </div>
      </>
    );
  }

  if (state === 'delete-confirm') {
    return (
      <>
        <S2_PageHeader dark={dark} title="Agents" sub="Reusable agent configurations with constrained tool access." />
        <div style={{ position: 'relative' }}>
          <div style={{ filter: 'blur(2px)', opacity: 0.4, pointerEvents: 'none' }}>
            {all.map((a) => <AgentCard key={a.id} a={a} dark={dark} />)}
          </div>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 380, padding: 22, background: t.bg, border: `1px solid ${t.border}`, borderRadius: 14, boxShadow: dark ? '0 20px 60px rgba(0,0,0,.5)' : '0 20px 60px rgba(0,0,0,.18)' }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>Delete pr-reviewer?</div>
              <div style={{ fontSize: 12, color: t.fg3, marginTop: 6, lineHeight: 1.5 }}>This agent's prompt, tool list, and trigger bindings will be removed. Existing chats started by this agent are kept.</div>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 18 }}>
                <Button variant="ghost" size="sm">Cancel</Button>
                <Button variant="danger" size="sm">Delete</Button>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <S2_PageHeader dark={dark} title="Agents" sub="Reusable agent configurations with constrained tool access." right={
        <Button variant="primary" size="sm"><Icon name="plus" size={12} /> Create custom agent</Button>
      } />
      <S2_Section dark={dark} title="Built-in" sub="Shipped with Ghast. Editable but not deletable.">
        {builtin.map((a) => <AgentCard key={a.id} a={a} dark={dark} />)}
      </S2_Section>
      {customAgents.length > 0 && (
        <S2_Section dark={dark} title={`Custom · ${customAgents.length}`}>
          {customAgents.map((a) => <AgentCard key={a.id} a={a} dark={dark} />)}
        </S2_Section>
      )}
      {customAgents.length === 0 && (
        <S2_Section dark={dark} title="Custom">
          <S2_Card dark={dark} style={{ padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 13, color: t.fg2, marginBottom: 4 }}>No custom agents yet.</div>
            <div style={{ fontSize: 11.5, color: t.fg3, marginBottom: 14 }}>Custom agents have their own prompt, tool list, and triggers.</div>
            <Button variant="secondary" size="sm">Create your first</Button>
          </S2_Card>
        </S2_Section>
      )}
    </>
  );
}

function AgentCard({ a, dark }) {
  const t = dark ? G.d : G.l;
  return (
    <div style={{ padding: 14, background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 14 }}>
      <div style={{ width: 36, height: 36, borderRadius: 10, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={a.builtin ? 'sparkle' : 'cube'} size={16} color={t.fg2} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 600, fontFamily: G.mono }}>{a.name}</span>
          {a.builtin && <Tag>built-in</Tag>}
        </div>
        <div style={{ fontSize: 11.5, color: t.fg3, marginTop: 2 }}>{a.desc}</div>
        <div style={{ display: 'flex', gap: 14, fontSize: 10.5, color: t.fg3, fontFamily: G.mono, marginTop: 6 }}>
          <span>{a.tools} tools</span>
          <span>·</span>
          <span>{a.model}</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 4 }}>
        <Button variant="ghost" size="sm">Edit</Button>
        {!a.builtin && <Icon name="moreH" size={14} color={t.fg3} style={{ cursor: 'pointer' }} />}
      </div>
    </div>
  );
}


// ═════════════════════════════════════════════════════════════
// D · CHAT BEHAVIOR
// ═════════════════════════════════════════════════════════════
function ChatBehaviorSettings({ dark, preset = 'default' }) {
  const t = dark ? G.d : G.l;
  const allOn = preset === 'all-on';
  const allOff = preset === 'all-off';
  const v = (def) => allOn ? true : allOff ? false : def;

  return (
    <>
      <S2_PageHeader dark={dark} title="Chat behavior" sub="Streaming, sounds, auto-compact, and other chat surface preferences." />

      <S2_Section dark={dark} title="Sound effects" sub="Subtle audio cues. Can be muted globally with system Do-Not-Disturb.">
        <S2_Card dark={dark}>
          {[
            { id: 'send',   label: 'Message sent',     desc: 'Played when you press ⌘↩ to send.',          on: v(true),  preview: '··· tick' },
            { id: 'recv',   label: 'Reply received',   desc: 'Played when the assistant finishes streaming.', on: v(true),  preview: '·· chime' },
            { id: 'tool',   label: 'Tool finished',    desc: 'Played when a slow tool returns.',           on: v(false), preview: '· pop' },
            { id: 'err',    label: 'Error',            desc: 'Played on any visible error toast.',         on: v(true),  preview: '· thunk' },
          ].map((s, i) => (
            <div key={s.id} style={{ padding: '12px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 12 }}>
              <button style={{ width: 28, height: 28, borderRadius: 14, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.fg2 }}>
                <Icon name="play" size={11} />
              </button>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13 }}>{s.label}</div>
                <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>{s.desc}</div>
              </div>
              <span style={{ fontSize: 10, fontFamily: G.mono, color: t.fg3 }}>{s.preview}</span>
              <S2_Toggle on={s.on} dark={dark} />
            </div>
          ))}
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Auto-compact" sub="When the context window fills, Ghast can summarize the older half and reset.">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Trigger threshold" value="Compact when this share of the context window is used." right={
            <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
              {['80%', '90%', '95%', 'Off'].map((r, i) => (
                <div key={r} style={{ padding: '4px 10px', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, background: i === 1 ? t.bg : 'transparent', border: i === 1 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
              ))}
            </div>
          } />
          <S2_Row dark={dark} label="Summary length" value="Tokens reserved for the summary." right={<span style={{ fontSize: 12, fontFamily: G.mono, color: t.fg2 }}>2,048</span>} last />
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Streaming">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Token-by-token streaming" value="Show the response as it's generated." right={<S2_Toggle on={v(true)} dark={dark} />} />
          <S2_Row dark={dark} label="Streaming speed" value="Cap rendering speed to make long replies easier to read." right={
            <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
              {['Slow', 'Normal', 'Fast', 'Instant'].map((r, i) => (
                <div key={r} style={{ padding: '4px 10px', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, background: i === 1 ? t.bg : 'transparent', border: i === 1 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
              ))}
            </div>
          } last />
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Display">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Auto-scroll on new message" value="Stick to the bottom when new content arrives." right={<S2_Toggle on={v(true)} dark={dark} />} />
          <S2_Row dark={dark} label="Show timestamps" value="When to show send-time on each message." right={
            <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
              {['Hover', 'Always', 'Never'].map((r, i) => (
                <div key={r} style={{ padding: '4px 10px', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, background: i === 0 ? t.bg : 'transparent', border: i === 0 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
              ))}
            </div>
          } />
          <S2_Row dark={dark} label="Confirm before regenerate" value="Ask for confirmation when re-rolling a reply." right={<S2_Toggle on={v(false)} dark={dark} />} last />
        </S2_Card>
      </S2_Section>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// E · CHROME RELAY
// ═════════════════════════════════════════════════════════════
function ChromeRelaySettings({ dark, state = 'paired' }) {
  const t = dark ? G.d : G.l;

  if (state === 'unpaired' || state === 'waiting' || state === 'no-extension') {
    const isWaiting = state === 'waiting';
    const noExt = state === 'no-extension';
    return (
      <>
        <S2_PageHeader dark={dark} title="Chrome Relay" sub="Pair Ghast with the Chrome extension to drive your browser." />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <S2_Card dark={dark} style={{ padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 10 }}>{isWaiting ? 'Waiting for handshake' : 'Pair this device'}</div>
            <div style={{ width: 156, height: 156, margin: '0 auto', background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 12, padding: 12, position: 'relative' }}>
              <div style={{ width: '100%', height: '100%', display: 'grid', gridTemplateColumns: 'repeat(16, 1fr)', gridTemplateRows: 'repeat(16, 1fr)', gap: 0 }}>
                {Array.from({ length: 256 }).map((_, i) => {
                  const r = ((i * 7919 + 31) % 100) > (isWaiting ? 50 : 48);
                  return <div key={i} style={{ background: r ? t.fg : 'transparent' }} />;
                })}
              </div>
              {isWaiting && (
                <div style={{ position: 'absolute', inset: -1, border: `2px solid ${t.fg}`, borderRadius: 12, animation: 'rpulse 1.5s ease-in-out infinite' }} />
              )}
            </div>
            <div style={{ fontSize: 11, color: t.fg3, marginTop: 12, lineHeight: 1.5 }}>Or enter this code in the extension popup:</div>
            <div style={{ fontSize: 22, fontWeight: 600, fontFamily: G.mono, letterSpacing: 4, marginTop: 6 }}>{isWaiting ? '·····' : '7X9 P3K'}</div>
          </S2_Card>
          <div>
            <S2_Section dark={dark} title="Getting started">
              <S2_Card dark={dark} style={{ padding: 14 }}>
                {[
                  ['1', 'Install the extension', noExt ? 'Not detected.' : 'Detected · v1.4.2'],
                  ['2', 'Open the popup',     'Click the Ghast icon in the Chrome toolbar.'],
                  ['3', 'Scan or type the code', 'Tap "Pair desktop" and enter the code on the left.'],
                  ['4', 'Confirm here',        'A confirmation will appear in this panel.'],
                ].map(([num, label, desc]) => (
                  <div key={num} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: 12 }}>
                    <div style={{ width: 22, height: 22, borderRadius: 11, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontFamily: G.mono, color: t.fg2 }}>{num}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{label}</div>
                      <div style={{ fontSize: 11, color: t.fg3, marginTop: 1 }}>{desc}</div>
                    </div>
                  </div>
                ))}
                <Button variant={noExt ? 'primary' : 'secondary'} size="sm" style={{ width: '100%', marginTop: 6 }}>
                  {noExt ? 'Install Chrome extension' : 'Open extension settings'}
                </Button>
              </S2_Card>
            </S2_Section>
            {state === 'no-extension' && (
              <S2_Card dark={dark} style={{ padding: 12, background: 'rgba(255,95,87,.06)', borderColor: 'rgba(255,95,87,.3)' }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <Icon name="warn" size={14} color="#ff5f57" style={{ marginTop: 2 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, color: t.fg }}>Extension not detected</div>
                    <div style={{ fontSize: 11, color: t.fg3, marginTop: 2 }}>Install it from the Chrome Web Store, then return here. Brave & Edge are also supported.</div>
                  </div>
                </div>
              </S2_Card>
            )}
          </div>
        </div>
        <style>{`@keyframes rpulse { 0%, 100% { opacity: 0; } 50% { opacity: 1; } }`}</style>
      </>
    );
  }

  // paired or token-expired
  const expired = state === 'expired';
  return (
    <>
      <S2_PageHeader dark={dark} title="Chrome Relay" sub="Pair Ghast with the Chrome extension to drive your browser." right={
        <Button variant="ghost" size="sm">Disconnect</Button>
      } />
      <S2_Card dark={dark} style={{ padding: 18, marginBottom: 18, borderColor: expired ? 'rgba(254,188,46,.4)' : t.border }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 22, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="link" size={20} color={t.fg2} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <S2_StatusDot status={expired ? 'warn' : 'on'} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>Chrome 124 · MacBook Pro</span>
              <Tag>{expired ? 'Token expired' : 'Active'}</Tag>
            </div>
            <div style={{ fontSize: 11.5, color: t.fg3, marginTop: 4 }}>
              {expired
                ? 'The session token has expired. Regenerate to keep the relay working.'
                : 'Hooked into 5 tabs · last activity 2 sec ago · ping 14 ms'}
            </div>
          </div>
          <Button variant={expired ? 'primary' : 'secondary'} size="sm">{expired ? 'Regenerate token' : 'Detach all'}</Button>
        </div>
      </S2_Card>

      <S2_Section dark={dark} title="Hooked tabs">
        <S2_Card dark={dark}>
          {[
            { url: 'https://github.com/ghast/web/pull/482', title: 'Pull Request #482 · ghast/web', ms: '2s' },
            { url: 'https://docs.ghast.app/skills', title: 'Skills · Ghast Docs', ms: '14s' },
            { url: 'https://app.linear.app/ghast/issue/G-128', title: 'G-128 · Memory tag bug · Linear', ms: '38s' },
            { url: 'https://news.ycombinator.com/', title: 'Hacker News', ms: '2m' },
            { url: 'https://mail.google.com/mail/u/0/#inbox', title: 'Inbox · Gmail', ms: '5m' },
          ].map((tab, i) => (
            <div key={i} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 14, height: 14, borderRadius: 3, background: t.surface2, flexShrink: 0 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tab.title}</div>
                <div style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{tab.url}</div>
              </div>
              <span style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono, flexShrink: 0 }}>{tab.ms}</span>
              <Icon name="close" size={12} color={t.fg3} style={{ cursor: 'pointer', flexShrink: 0 }} />
            </div>
          ))}
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Recent activity">
        <S2_Card dark={dark} style={{ padding: 14, fontFamily: G.mono, fontSize: 11, lineHeight: 1.7, color: t.fg2 }}>
          {[
            ['12:14:08', 'tab.click   ',  '#submit-pr-review'],
            ['12:14:07', 'tab.scroll  ',  'pull/482 · y=824'],
            ['12:14:02', 'tab.fill    ',  '#review-comment <128 chars>'],
            ['12:13:54', 'tab.attach  ',  'tab #2918 (github.com)'],
            ['12:13:51', 'relay.ping  ',  '14ms'],
            ['12:13:42', 'tab.read    ',  'docs.ghast.app/skills <readability>'],
            ['12:12:09', 'relay.token ',  'refreshed (exp +24h)'],
            ['12:11:54', 'tab.detach  ',  'tab #2901 (mail.google.com)'],
            ['12:11:30', 'relay.ping  ',  '12ms'],
            ['12:10:18', 'session.start', 'chrome 124 · macos · v1.4.2'],
          ].map(([ts, op, arg], i) => (
            <div key={i}><span style={{ color: t.fg3 }}>{ts}</span>  <span style={{ color: t.fg }}>{op}</span> <span style={{ color: t.fg3 }}>{arg}</span></div>
          ))}
        </S2_Card>
      </S2_Section>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// F · COMPUTER USE
// ═════════════════════════════════════════════════════════════
function ComputerUseSettings({ dark, state = 'ready' }) {
  const t = dark ? G.d : G.l;
  const helperState = {
    unauthorized: { tag: 'Permissions needed',  tone: 'warn',     msg: 'Grant Accessibility & Screen Recording in System Settings to enable computer-use.', cta: 'Open System Settings' },
    ready:        { tag: 'Ready',                tone: 'on',       msg: 'Helper is running and both permissions are granted.',  cta: 'Restart helper' },
    denied:       { tag: 'Permission denied',    tone: 'off',      msg: 'Accessibility was denied. Re-enable it in System Settings to continue.',     cta: 'Open System Settings' },
    crashed:      { tag: 'Helper crashed',       tone: 'off',      msg: 'ghast-helper exited unexpectedly. It will auto-restart in 12 seconds.', cta: 'Restart now' },
    'needs-helper': { tag: 'Helper not installed', tone: 'warn',  msg: 'Install ghast-helper to enable computer-use. ~3 MB · signed binary.', cta: 'Install helper' },
  }[state];
  const ax = state === 'ready';
  const sr = state === 'ready';

  return (
    <>
      <S2_PageHeader dark={dark} title="Computer Use" sub="Let Ghast see and drive native macOS apps." />

      <S2_Card dark={dark} style={{ padding: 18, marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 22, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="cube" size={20} color={t.fg2} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <S2_StatusDot status={helperState.tone} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>ghast-helper</span>
              <Tag>{helperState.tag}</Tag>
            </div>
            <div style={{ fontSize: 11.5, color: t.fg3, marginTop: 4 }}>{helperState.msg}</div>
          </div>
          <Button variant={state === 'unauthorized' || state === 'denied' ? 'primary' : 'secondary'} size="sm">{helperState.cta}</Button>
        </div>
      </S2_Card>

      <S2_Section dark={dark} title="System permissions">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            { label: 'Accessibility',     desc: 'Required to read window structure and click elements.', granted: ax },
            { label: 'Screen Recording',  desc: 'Required for screenshots and OCR fallbacks.',           granted: sr },
          ].map((p) => (
            <S2_Card key={p.label} dark={dark} style={{ padding: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <S2_StatusDot status={p.granted ? 'on' : 'off'} />
                <span style={{ fontSize: 12.5, fontWeight: 600 }}>{p.label}</span>
                <span style={{ fontSize: 11, color: t.fg3, marginLeft: 'auto', fontFamily: G.mono }}>{p.granted ? 'Granted' : 'Denied'}</span>
              </div>
              <div style={{ fontSize: 11, color: t.fg3, marginTop: 6, lineHeight: 1.5 }}>{p.desc}</div>
            </S2_Card>
          ))}
        </div>
      </S2_Section>

      <S2_Section dark={dark} title="Default behavior">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Auto-screenshot on action" value="Capture a frame after every click and keystroke." right={<S2_Toggle on={true} dark={dark} />} />
          <S2_Row dark={dark} label="Max attempts per task" value="Stop after this many retries on a stuck step." right={
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 120, height: 4, background: t.surface2, borderRadius: 2, position: 'relative' }}>
                <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: '40%', background: t.fg, borderRadius: 2 }} />
                <div style={{ position: 'absolute', left: 'calc(40% - 6px)', top: -4, width: 12, height: 12, background: t.bg, border: `1.5px solid ${t.fg}`, borderRadius: 6 }} />
              </div>
              <span style={{ fontSize: 12, fontFamily: G.mono, width: 16 }}>4</span>
            </div>
          } last />
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Safety · app whitelist" sub="Computer-use is only allowed in these apps. Anything else requires per-task confirmation.">
        <S2_Card dark={dark}>
          {[
            ['com.apple.Notes',     'Notes'],
            ['com.apple.Music',     'Music'],
            ['com.apple.Calendar',  'Calendar'],
            ['com.apple.Mail',      'Mail'],
            ['com.figma.Desktop',   'Figma'],
            ['com.tinyspeck.slackmacgap', 'Slack'],
          ].map(([id, name], i) => (
            <div key={id} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 22, height: 22, borderRadius: 5, background: t.surface2, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5 }}>{name}</div>
                <div style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono, marginTop: 1 }}>{id}</div>
              </div>
              <S2_Toggle on={true} dark={dark} />
            </div>
          ))}
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Test sandbox" sub="Run a no-op snapshot against a demo app.">
        <S2_Card dark={dark} style={{ padding: 14 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
            {['Notes', 'Music', 'Calendar', 'Mail'].map((a, i) => (
              <button key={a} style={{ padding: '5px 11px', fontSize: 11.5, borderRadius: 14, background: i === 0 ? t.fg : t.surface2, color: i === 0 ? t.bg : t.fg2, border: `1px solid ${i === 0 ? t.fg : t.border}` }}>{a}</button>
            ))}
            <div style={{ flex: 1 }} />
            <Button variant="primary" size="sm" disabled={state !== 'ready'}>Take snapshot</Button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <ImgPlaceholder label="screenshot · 1440×900" height={180} />
            <div style={{ background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8, padding: 10, fontFamily: G.mono, fontSize: 10.5, lineHeight: 1.6, color: t.fg2, height: 180, overflow: 'hidden' }}>
              <div style={{ color: t.fg3 }}>{'// AX tree · com.apple.Notes'}</div>
              <div>AXApplication "Notes"</div>
              <div>  AXWindow "All iCloud"</div>
              <div>    AXSplitGroup</div>
              <div>      AXScrollArea</div>
              <div>        AXOutline · 24 rows</div>
              <div>          AXRow "Today" (selected)</div>
              <div>          AXRow "Yesterday"</div>
              <div>      AXTextArea "Note body"</div>
              <div>    AXToolbar · 6 buttons</div>
              <div>      AXButton "New note"</div>
              <div>      AXButton "Search"</div>
            </div>
          </div>
        </S2_Card>
      </S2_Section>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// G · CONTACTS
// ═════════════════════════════════════════════════════════════
function ContactsSettings({ dark, state = 'list' }) {
  const t = dark ? G.d : G.l;
  const contacts = [
    { name: 'Chen Yu',       channel: 'Telegram',  last: '2h',  perms: 'all',     bio: 'Cofounder. Engineer. Reviews diffs.' },
    { name: 'Marcus L.',     channel: 'Discord',   last: '4h',  perms: 'limited', bio: 'Designer. Reviews layouts.' },
    { name: 'Anna B.',       channel: 'Feishu',    last: '1d',  perms: 'all',     bio: 'PM. Triages roadmap.' },
    { name: 'Kira T.',       channel: 'Telegram',  last: '2d',  perms: 'limited', bio: 'Hardware lead.' },
    { name: 'Diego R.',      channel: 'Email',     last: '3d',  perms: 'limited', bio: 'External counsel.' },
    { name: 'Yuki H.',       channel: 'Discord',   last: '5d',  perms: 'all',     bio: 'Researcher.' },
    { name: 'Sam P.',        channel: 'Weixin',    last: '1w',  perms: 'limited', bio: 'Sales.' },
    { name: 'Reed K.',       channel: 'Telegram',  last: '2w',  perms: 'all',     bio: 'Investor.' },
  ];

  if (state === 'empty') {
    return (
      <>
        <S2_PageHeader dark={dark} title="Contacts" sub="People Ghast knows and how to reach them." />
        <S2_Card dark={dark} style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: 28, background: t.surface2, border: `1px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
            <Icon name="user" size={22} color={t.fg3} />
          </div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>No contacts yet</div>
          <div style={{ fontSize: 12, color: t.fg3, marginTop: 6, maxWidth: 320, margin: '6px auto 18px' }}>Contacts are added automatically the first time you converse with someone through a channel, or you can add them manually.</div>
          <Button variant="primary" size="sm">Add a contact</Button>
        </S2_Card>
      </>
    );
  }

  if (state === 'editing') {
    return (
      <>
        <S2_PageHeader dark={dark} title="Edit contact · Chen Yu" sub="Profile and per-contact permissions." right={
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="ghost" size="sm">Cancel</Button>
            <Button variant="primary" size="sm">Save</Button>
          </div>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 18 }}>
          <div>
            <S2_Section dark={dark} title="Profile">
              <S2_Card dark={dark} style={{ padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
                  <Avatar name="Chen Yu" size={56} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>Chen Yu</div>
                    <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, marginTop: 2 }}>chen.yu@example.com · @chenyu</div>
                  </div>
                  <Button variant="secondary" size="sm">Change photo</Button>
                </div>
                <div style={{ fontSize: 11, fontWeight: 600, color: t.fg2, fontFamily: G.mono, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>profile.md</div>
                <textarea defaultValue={`# Chen Yu\n\nCofounder · engineering. Reviews PRs. Pacific time, but reviews late evening Asia.\n\n- Prefers concise replies. No filler.\n- Allergic to dairy.\n- Default channel: Telegram (replies in <30 min during work hours).`} style={{ width: '100%', minHeight: 200, padding: 10, background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8, fontSize: 12, fontFamily: G.mono, lineHeight: 1.55, color: t.fg, resize: 'vertical', outline: 'none' }} />
              </S2_Card>
            </S2_Section>
          </div>
          <div>
            <S2_Section dark={dark} title="Channels">
              <S2_Card dark={dark}>
                {[
                  ['Telegram', '@chenyu',          true],
                  ['Discord',  'chenyu#3914',      true],
                  ['Feishu',   'chen.yu@example',  false],
                  ['Email',    'chen.yu@example.com', true],
                ].map(([ch, addr, on], i) => (
                  <div key={ch} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5 }}>{ch}</div>
                      <div style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{addr}</div>
                    </div>
                    <S2_Toggle on={on} dark={dark} />
                  </div>
                ))}
              </S2_Card>
            </S2_Section>
            <S2_Section dark={dark} title="Permissions">
              <S2_Card dark={dark}>
                <S2_Row dark={dark} label="Allow agent to message first" value="Without an explicit user prompt." right={<S2_Toggle on={true} dark={dark} />} />
                <S2_Row dark={dark} label="Share workspace state" value="What Ghast is currently working on." right={<S2_Toggle on={false} dark={dark} />} />
                <S2_Row dark={dark} label="Read into memory" value="Save what they say into long-term memory." right={<S2_Toggle on={true} dark={dark} />} last />
              </S2_Card>
            </S2_Section>
            <Button variant="danger" size="sm" style={{ width: '100%' }}>Delete contact</Button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <S2_PageHeader dark={dark} title="Contacts" sub="People Ghast knows and how to reach them." right={
        <Button variant="primary" size="sm"><Icon name="plus" size={12} /> Add contact</Button>
      } />
      <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
        <Input placeholder="Search contacts" icon="search" dark={dark} style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
          {['All', 'Telegram', 'Discord', 'Feishu', 'Weixin', 'Email'].map((r, i) => (
            <div key={r} style={{ padding: '5px 10px', borderRadius: 5, fontSize: 11.5, background: i === 0 ? t.bg : 'transparent', border: i === 0 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
          ))}
        </div>
      </div>
      <S2_Card dark={dark}>
        {contacts.map((c, i) => (
          <div key={c.name} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.border2}`, display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar name={c.name} size={32} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ fontSize: 12.5, fontWeight: 500 }}>{c.name}</span>
                <Tag>{c.channel}</Tag>
                {c.perms === 'limited' && <span style={{ fontSize: 10, color: t.fg3, fontFamily: G.mono }}>limited</span>}
              </div>
              <div style={{ fontSize: 11, color: t.fg3, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.bio}</div>
            </div>
            <span style={{ fontSize: 10.5, color: t.fg3, fontFamily: G.mono }}>{c.last}</span>
            <Icon name="chevronRight" size={12} color={t.fg3} />
          </div>
        ))}
      </S2_Card>
    </>
  );
}


// ═════════════════════════════════════════════════════════════
// H · DATA
// ═════════════════════════════════════════════════════════════
function DataSettings({ dark, state = 'idle' }) {
  const t = dark ? G.d : G.l;

  if (state === 'reset-confirm') {
    return (
      <>
        <S2_PageHeader dark={dark} title="Data" sub="Export, import, sync, and reset your local data." />
        <div style={{ position: 'relative' }}>
          <div style={{ filter: 'blur(2px)', opacity: 0.4 }}>
            <DataSettingsBody dark={dark} state="idle" />
          </div>
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 440, padding: 22, background: t.bg, border: `1px solid ${t.border}`, borderRadius: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                <Icon name="warn" size={18} color="#ff5f57" />
                <span style={{ fontSize: 15, fontWeight: 600 }}>Reset everything?</span>
              </div>
              <div style={{ fontSize: 12, color: t.fg3, lineHeight: 1.6, marginBottom: 14 }}>This will delete <strong style={{ color: t.fg }}>all 38 threads</strong>, <strong style={{ color: t.fg }}>312 memories</strong>, <strong style={{ color: t.fg }}>14 connected channels</strong>, and clear your wallet keys from this device. Your account on the server is untouched.</div>
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, color: t.fg3, marginBottom: 6 }}>Type <strong style={{ fontFamily: G.mono, color: t.fg }}>RESET</strong> to confirm:</div>
                <input style={{ width: '100%', height: 32, padding: '0 10px', fontSize: 12, fontFamily: G.mono, background: t.surface2, border: `1.5px solid ${t.border}`, borderRadius: 7, color: t.fg }} />
              </div>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <Button variant="ghost" size="sm">Cancel</Button>
                <Button variant="danger" size="sm" disabled>Reset everything</Button>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <S2_PageHeader dark={dark} title="Data" sub="Export, import, sync, and reset your local data." />
      <DataSettingsBody dark={dark} state={state} />
    </>
  );
}

function DataSettingsBody({ dark, state }) {
  const t = dark ? G.d : G.l;
  const exporting = state === 'exporting';
  const importing = state === 'importing';
  const syncing   = state === 'syncing';

  return (
    <>
      <S2_Section dark={dark} title="Export">
        <S2_Card dark={dark} style={{ padding: 16 }}>
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, marginBottom: 6 }}>SCOPE</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
              {[
                ['Threads',  '38 conversations', true],
                ['Settings', 'All preferences',  true],
                ['Memory',   '312 facts',         true],
                ['Wallet',   'Encrypted keys',    false],
                ['Contacts', '14 people',         true],
                ['Activity', 'Last 30 days',      false],
              ].map(([k, v, on]) => (
                <div key={k} style={{ padding: 10, borderRadius: 8, background: on ? t.surface2 : 'transparent', border: `1px solid ${on ? t.fg : t.border}`, borderWidth: on ? 1.5 : 1, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 14, height: 14, borderRadius: 3, border: `1px solid ${on ? t.fg : t.border}`, background: on ? t.fg : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {on && <Icon name="check" size={9} color={t.bg} />}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12, fontWeight: on ? 500 : 400 }}>{k}</div>
                    <div style={{ fontSize: 10, color: t.fg3, fontFamily: G.mono }}>{v}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 12 }}>
            <div>
              <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, marginBottom: 6 }}>FORMAT</div>
              <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
                {['ZIP', 'JSON', 'SQLite'].map((r, i) => (
                  <div key={r} style={{ flex: 1, padding: '4px 0', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, textAlign: 'center', background: i === 0 ? t.bg : 'transparent', border: i === 0 ? `1px solid ${t.border}` : 'none' }}>{r}</div>
                ))}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, marginBottom: 6 }}>ENCRYPTION</div>
              <div style={{ height: 28, padding: '0 10px', background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 7, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="lock" size={11} color={t.fg2} />
                <span style={{ fontSize: 11.5, color: t.fg2 }}>AES-256 · passphrase</span>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, letterSpacing: 0.6, marginBottom: 6 }}>OUTPUT</div>
              <div style={{ height: 28, padding: '0 10px', background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 7, display: 'flex', alignItems: 'center' }}>
                <span style={{ fontSize: 11, color: t.fg2, fontFamily: G.mono, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>~/Downloads/ghast-export.zip</span>
              </div>
            </div>
          </div>
          {exporting ? (
            <div style={{ height: 32, padding: '0 12px', background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ flex: 1, height: 4, background: t.border2, borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: '70%', background: t.fg }} />
              </div>
              <span style={{ fontSize: 11, fontFamily: G.mono, color: t.fg2 }}>70%  ·  264 MB / 378 MB</span>
              <button style={{ background: 'transparent', border: 'none', fontSize: 11, color: t.fg3, cursor: 'pointer' }}>Cancel</button>
            </div>
          ) : (
            <Button variant="primary" size="sm">Export selected</Button>
          )}
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Import">
        <S2_Card dark={dark} style={{ padding: 16 }}>
          {importing ? (
            <div>
              <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, marginBottom: 8 }}>PREVIEW · ghast-export-2024-03-12.zip</div>
              <div style={{ background: t.surface2, border: `1px solid ${t.border}`, borderRadius: 8, padding: 12, fontFamily: G.mono, fontSize: 11.5, lineHeight: 1.7, marginBottom: 14 }}>
                <div>+ 12 new threads</div>
                <div>+ 84 new memories</div>
                <div><span style={{ color: '#febc2e' }}>~</span> 4 settings differ from current values</div>
                <div><span style={{ color: '#febc2e' }}>~</span> 2 contacts already exist · merge?</div>
              </div>
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 11, color: t.fg3, fontFamily: G.mono, marginBottom: 6 }}>ON CONFLICT</div>
                <div style={{ display: 'flex', gap: 4, padding: 3, background: t.surface2, borderRadius: 7 }}>
                  {['Replace', 'Merge', 'Skip'].map((r, i) => (
                    <div key={r} style={{ padding: '4px 10px', borderRadius: 5, fontSize: 11.5, fontFamily: G.mono, background: i === 1 ? t.bg : 'transparent', border: i === 1 ? `1px solid ${t.border}` : 'none', cursor: 'pointer' }}>{r}</div>
                  ))}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <Button variant="ghost" size="sm">Cancel</Button>
                <Button variant="primary" size="sm">Import</Button>
              </div>
            </div>
          ) : (
            <>
              <div style={{ height: 80, border: `1.5px dashed ${t.border}`, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: t.fg3, fontSize: 12, marginBottom: 10 }}>
                <Icon name="download" size={16} color={t.fg3} style={{ transform: 'rotate(180deg)' }} />
                Drop a ghast-export file here, or click to choose.
              </div>
              <div style={{ fontSize: 11, color: t.fg3 }}>Supported: .zip · .json · .sqlite from any version since 2.1.</div>
            </>
          )}
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Cloud sync" sub="Mirror your data to a folder. Encrypted at rest. iCloud Drive recommended.">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Sync to folder" value={syncing ? 'Syncing now…' : 'Last synced 14 minutes ago.'} right={<S2_Toggle on={true} dark={dark} />} />
          <S2_Row dark={dark} label="Sync folder" value="~/Library/Mobile Documents/com~apple~CloudDocs/GhastSync" right={<Button variant="secondary" size="sm">Reveal</Button>} />
          <S2_Row dark={dark} label="Sync now" value={syncing ? 'Pushed 18 / 38 threads' : 'Pull, then push.'} right={
            syncing ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ width: 100, height: 4, background: t.surface2, borderRadius: 2, overflow: 'hidden' }}><div style={{ height: '100%', width: '47%', background: t.fg }} /></div>
                <span style={{ fontSize: 11, fontFamily: G.mono, color: t.fg2 }}>47%</span>
              </div>
            ) : <Button variant="secondary" size="sm">Sync now</Button>
          } last />
        </S2_Card>
      </S2_Section>

      <S2_Section dark={dark} title="Reset">
        <S2_Card dark={dark}>
          <S2_Row dark={dark} label="Clear cache" value="Removes ~412 MB of throwaway data. Threads & memory are kept." right={<Button variant="secondary" size="sm">Clear cache</Button>} />
          <S2_Row dark={dark} label="Forget all threads" value="Delete every conversation. Memory is kept." right={<Button variant="secondary" size="sm">Forget threads</Button>} />
          <S2_Row dark={dark} label="Forget memory" value="Delete every long-term fact." right={<Button variant="secondary" size="sm">Forget memory</Button>} />
          <S2_Row dark={dark} label="Reset everything" value="Wipes Ghast on this device. Triple-confirm." right={<Button variant="danger" size="sm">Reset everything</Button>} last />
        </S2_Card>
      </S2_Section>
    </>
  );
}


Object.assign(window, {
  S2_StatusDot, S2_Toggle, S2_PageHeader, S2_Section, S2_Row, S2_Card,
  AboutSettings, ActivityRecorderSettings, AgentsSettings, AgentCard,
  ChatBehaviorSettings, ChromeRelaySettings, ComputerUseSettings, ContactsSettings, DataSettings,
});
