// Tablet — Chromium-style Settings page (iPad)
// Left nav rail with categories, right scrollable detail pane.
// Covers Chromium baseline (autofill, privacy, perf, appearance, search,
// startup, downloads, languages, a11y, system, reset, extensions, about)
// PLUS Ajna additions (identity, mesh, chat, tab groups sharing, private mode).

// ─── Toggle ──────────────────────────────────────────────────
function TToggle({ on, onChange, accent = M_ACCENT_B }) {
  return (
    <button onClick={() => onChange && onChange(!on)} style={{
      width: 38, height: 22, borderRadius: 12,
      background: on ? 'linear-gradient(135deg, ' + M_ACCENT + ', ' + M_ACCENT_B + ')' : M_SURFACE_2,
      border: '1px solid ' + (on ? 'transparent' : M_BORDER),
      position: 'relative', cursor: 'pointer', flexShrink: 0, padding: 0,
      transition: 'background 200ms',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 16, height: 16, borderRadius: 8, background: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
        transition: 'left 200ms',
      }}/>
    </button>
  );
}

// ─── Generic select ──────────────────────────────────────────
function TSelect({ value, options, onChange, width = 'auto' }) {
  return (
    <select value={value} onChange={e => onChange && onChange(e.target.value)} style={{
      background: M_SURFACE_2, color: M_FG, border: '1px solid ' + M_BORDER,
      borderRadius: 8, padding: '7px 28px 7px 12px', fontSize: 12.5,
      fontFamily: 'inherit', cursor: 'pointer', minWidth: width,
      appearance: 'none',
      backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='m6 9 6 6 6-6'/></svg>")`,
      backgroundRepeat: 'no-repeat', backgroundPosition: 'right 10px center',
    }}>
      {options.map(o => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
    </select>
  );
}

// ─── Row / Card primitives ──────────────────────────────────
function TSettingRow({ icon, iconColor, title, subtitle, right, onClick, danger }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '12px 14px',
      background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
      borderRadius: 12, cursor: onClick ? 'pointer' : 'default',
      transition: 'background 160ms',
    }}
    onMouseEnter={e => { if (onClick) e.currentTarget.style.background = 'var(--m-tint)'; }}
    onMouseLeave={e => { if (onClick) e.currentTarget.style.background = M_SURFACE; }}
    >
      {icon && (
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: iconColor ? iconColor + '1F' : M_TINT,
          color: iconColor || M_FG_MUTED,
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}>{icon}</div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, color: danger ? '#F87171' : M_FG }}>{title}</div>
        {subtitle && <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 3, lineHeight: 1.45 }}>{subtitle}</div>}
      </div>
      {right || (onClick && (
        <span style={{ color: M_FG_DIM, display: 'grid', placeItems: 'center' }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6"/></svg>
        </span>
      ))}
    </div>
  );
}

function TSectionLabel({ children, sub }) {
  return (
    <div style={{ marginTop: 24, marginBottom: 10, paddingLeft: 2 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase' }}>{children}</div>
      {sub && <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 4, lineHeight: 1.4 }}>{sub}</div>}
    </div>
  );
}

function TChip({ children, color = '#6EE7B7' }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '2px 8px', borderRadius: 999,
      background: color + '22', color, fontSize: 10.5,
      fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em',
      fontWeight: 600, flexShrink: 0,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 3, background: color, boxShadow: '0 0 6px ' + color }}/>
      {children}
    </span>
  );
}

// ─── Nav config ─────────────────────────────────────────────
const T_SETTINGS_NAV = [
  { section: 'Account', items: [
    { id: 'identity',  icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-6 8-6s8 2 8 6"/></svg>,             label: 'You & Ajna',         badge: '3 devices' },
    { id: 'autofill',  icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="15" r="4"/><path d="m11 12 9-9M18 5l2 2"/></svg>,                    label: 'Autofill & passwords' },
  ]},
  { section: 'Privacy', items: [
    { id: 'privacy',   icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/></svg>,                 label: 'Privacy & security', badge: 'Strict' },
    { id: 'private',   icon: () => <IcMask s={15}/>,                                                                                                                                                                                                                label: 'Private browsing',   accent: PRIV_ACCENT_2 },
  ]},
  { section: 'Browser', items: [
    { id: 'appearance',icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="14" r="2"/><path d="M12 4 4 12l8 8 10-10-8-8z"/></svg>,             label: 'Appearance' },
    { id: 'search',    icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg>,                          label: 'Search engine' },
    { id: 'startup',   icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v9"/><path d="M5.6 7.4a9 9 0 1 0 12.8 0"/></svg>,                         label: 'On startup' },
    { id: 'default',   icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg>,           label: 'Default browser' },
    { id: 'tabgroups', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="8" height="7" rx="1.5"/><rect x="13" y="4" width="8" height="7" rx="1.5"/><rect x="3" y="13" width="8" height="7" rx="1.5"/><rect x="13" y="13" width="8" height="7" rx="1.5"/></svg>, label: 'Tab groups' },
    { id: 'perf',      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2 3 14h7l-1 8 10-12h-7z"/></svg>,                                          label: 'Performance' },
  ]},
  { section: 'Ajna network', items: [
    { id: 'mesh',      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="5" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="18" r="2"/><path d="M12 7v4M12 11 6 16M12 11l6 5"/></svg>, label: 'Mesh & peers',       badge: '3 online' },
    { id: 'chat',      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6a3 3 0 0 1 3-3h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3h-5l-5 4v-4H6a3 3 0 0 1-3-3z"/></svg>, label: 'Chat & messaging' },
  ]},
  { section: 'Advanced', items: [
    { id: 'downloads', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 4v12m0 0-4-4m4 4 4-4M4 20h16"/></svg>,                                     label: 'Downloads' },
    { id: 'languages', icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"/></svg>, label: 'Languages' },
    { id: 'a11y',      icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="5" r="2"/><path d="M12 7v6m-4 0h8M8 20l4-7 4 7"/></svg>,           label: 'Accessibility' },
    { id: 'system',    icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 3v3m6-3v3M9 18v3m6-3v3M3 9h3m-3 6h3m15-6h3m-3 6h3"/></svg>, label: 'System' },
    { id: 'reset',     icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg>,                            label: 'Reset settings' },
  ]},
  { section: 'About', items: [
    { id: 'extensions',icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 2v6m6-6v6M5 8h14v4a7 7 0 0 1-14 0z"/><path d="M12 19v3"/></svg>,             label: 'Extensions',           external: true },
    { id: 'about',     icon: <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 8h.01M11 12h1v4h1"/></svg>,                 label: 'About Ajna' },
  ]},
];

const T_SETTING_ROUTES = {
  identity:   'ajna://settings/people',
  autofill:   'ajna://settings/autofill',
  privacy:    'ajna://settings/privacy',
  private:    'ajna://settings/privateBrowsing',
  appearance: 'ajna://settings/appearance',
  search:     'ajna://settings/search',
  startup:    'ajna://settings/onStartup',
  default:    'ajna://settings/defaultBrowser',
  tabgroups:  'ajna://settings/tabGroups',
  perf:       'ajna://settings/performance',
  mesh:       'ajna://settings/mesh',
  chat:       'ajna://settings/chat',
  downloads:  'ajna://settings/downloads',
  languages:  'ajna://settings/languages',
  a11y:       'ajna://settings/accessibility',
  system:     'ajna://settings/system',
  reset:      'ajna://settings/reset',
  extensions: 'ajna://extensions',
  about:      'ajna://settings/help',
};

// ─── Nav rail item ──────────────────────────────────────────
function TSNavItem({ item, active, onClick }) {
  const accent = item.accent || M_ACCENT_B;
  const isIconFn = typeof item.icon === 'function';
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10,
      width: '100%', padding: '8px 11px', borderRadius: 8,
      background: active ? 'rgba(96,165,250,0.10)' : 'transparent',
      border: 0, cursor: 'pointer', textAlign: 'left',
      color: active ? M_FG : M_FG_MUTED, fontFamily: 'inherit',
      boxShadow: active ? 'inset 0 0 0 1px rgba(96,165,250,0.28)' : 'none',
    }}
    onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--m-tint)'; }}
    onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <span style={{ color: active ? accent : M_FG_DIM, display: 'grid', placeItems: 'center', width: 15, flexShrink: 0 }}>
        {isIconFn ? item.icon() : item.icon}
      </span>
      <span style={{ flex: 1, fontSize: 12.5, fontWeight: active ? 500 : 400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.label}</span>
      {item.badge && (
        <span style={{
          fontSize: 9.5, padding: '1px 6px', borderRadius: 999,
          background: 'rgba(110,231,183,0.12)', color: M_ACCENT,
          fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em', fontWeight: 600,
          whiteSpace: 'nowrap', flexShrink: 0,
        }}>{item.badge}</span>
      )}
      {item.external && (
        <span style={{ color: M_FG_DIM, flexShrink: 0 }}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17 17 7M8 7h9v9"/></svg>
        </span>
      )}
    </button>
  );
}

// ─── Page detail bodies ─────────────────────────────────────
function TSPageIdentity() {
  const [name, setName] = React.useState('Maya Chen');
  const [editing, setEditing] = React.useState(false);
  const [avatarIdx, setAvatarIdx] = React.useState(0);
  const [picking, setPicking] = React.useState(false);
  const avatars = [
    { bg: '#A78BFA' }, { bg: '#22D3EE' }, { bg: '#F472B6' },
    { bg: '#FBBF24' }, { bg: '#10B981' }, { bg: '#EF4444' },
  ];
  const initials = name.trim().split(/\s+/).slice(0,2).map(s => s[0] || '').join('').toUpperCase() || 'A';
  const av = avatars[avatarIdx];
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (editing) setTimeout(() => inputRef.current?.focus(), 0); }, [editing]);

  const Lock = () => (
    <span title="Permanent — set when your identity was created" style={{ color: M_FG_DIM, display: 'inline-flex', verticalAlign: 'middle', marginLeft: 6 }}>
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
    </span>
  );

  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.identity} title="You & Ajna" subtitle="Your identity, devices, and the data Ajna keeps for you."/>

      <div style={{
        padding: 20, background: 'linear-gradient(135deg, rgba(110,231,183,0.06), rgba(96,165,250,0.06)), ' + M_SURFACE,
        border: '1px solid ' + M_BORDER, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <MTile size={56} bg={av.bg} color="#fff" label={initials} radius={28}/>
          <button
            onClick={() => setPicking(p => !p)}
            aria-label="Change photo"
            style={{
              position: 'absolute', right: -2, bottom: -2,
              width: 24, height: 24, borderRadius: 12,
              background: M_FG, color: '#0B0C0F', border: '2px solid ' + M_BG,
              display: 'grid', placeItems: 'center', cursor: 'pointer', padding: 0,
            }}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="4"/></svg>
          </button>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          {editing ? (
            <input
              ref={inputRef}
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={() => setEditing(false)}
              onKeyDown={(e) => { if (e.key === 'Enter') setEditing(false); if (e.key === 'Escape') setEditing(false); }}
              style={{
                width: '100%', maxWidth: 320, background: 'var(--m-tint)',
                border: '1px solid rgba(96,165,250,0.45)', borderRadius: 8,
                padding: '6px 10px', color: M_FG, fontSize: 18, fontWeight: 600,
                fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em', outline: 0,
              }}
            />
          ) : (
            <button onClick={() => setEditing(true)}
              style={{
                background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
                fontSize: 18, fontWeight: 600, color: M_FG,
                fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.02em',
                textAlign: 'left', display: 'inline-flex', alignItems: 'center', gap: 8,
              }} aria-label="Edit name">
              {name}
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={M_FG_DIM} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z"/></svg>
            </button>
          )}
          <div style={{ fontSize: 12, color: M_FG_MUTED, marginTop: 4 }}>
            @noah-okafor · maya@ajna.dev <Lock/>
          </div>
          <div style={{ fontSize: 10.5, color: M_FG_DIM, marginTop: 4, fontFamily: 'JetBrains Mono, monospace' }}>
            did:key:z6Mk…9kTp <Lock/>
          </div>
        </div>
        <button style={{ padding: '8px 14px', borderRadius: 10, background: M_SURFACE_2, border: '1px solid ' + M_BORDER, color: M_FG, fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>Manage identity</button>
      </div>

      {picking && (
        <div style={{
          marginTop: 10, padding: 14,
          background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12,
        }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', marginBottom: 12 }}>Pick a color or upload</div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            {avatars.map((a, i) => (
              <button key={i} onClick={() => { setAvatarIdx(i); setPicking(false); }}
                aria-label={'Avatar ' + (i + 1)}
                style={{
                  width: 40, height: 40, borderRadius: 20, padding: 0,
                  background: a.bg, color: '#fff',
                  border: avatarIdx === i ? '2px solid #fff' : '2px solid transparent',
                  boxShadow: avatarIdx === i ? '0 0 0 2px rgba(96,165,250,0.45)' : 'none',
                  fontFamily: 'Geist', fontWeight: 700, fontSize: 13, letterSpacing: '-0.02em',
                  cursor: 'pointer', display: 'grid', placeItems: 'center',
                }}>{initials}</button>
            ))}
            <button onClick={() => { setPicking(false); }}
              aria-label="Upload photo"
              style={{
                width: 40, height: 40, borderRadius: 20, padding: 0,
                background: 'var(--m-tint)', color: M_FG_MUTED,
                border: '1px dashed ' + M_BORDER, cursor: 'pointer',
                display: 'grid', placeItems: 'center',
              }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 4v12m0 0-4-4m4 4 4-4M4 20h16"/></svg>
            </button>
          </div>
        </div>
      )}

      <TSectionLabel>Sync</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Sync everything" subtitle="Bookmarks, tabs, history, passwords, settings — encrypted end-to-end."
          right={<TToggle on onChange={() => {}}/>}/>
        <TSettingRow title="Sync passphrase" subtitle="Encrypt your sync data with your own passphrase. Recommended."
          right={<TChip color={M_ACCENT_B}>SET</TChip>}/>
        <TSettingRow title="Manage what you sync" subtitle="Tabs · Bookmarks · History · Passwords · Autofill · Extensions · Theme" onClick={() => {}}/>
      </div>

      <TSectionLabel>Devices · 3</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { name: 'iPad Pro (this device)', when: 'Active now',  conn: 'mesh', primary: true },
          { name: 'iPhone 15',              when: 'Last seen 4m', conn: 'ble' },
          { name: 'MacBook Air',            when: 'Last seen 2h', conn: 'internet' },
        ].map(d => (
          <TSettingRow key={d.name}
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M11 18h2"/></svg>}
            title={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>{d.name} {d.primary && <TChip>THIS</TChip>}</span>}
            subtitle={d.when}
            right={<MConnChip type={d.conn}/>}
          />
        ))}
      </div>
    </>
  );
}

function TSPagePrivacy() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.privacy} title="Privacy & security" subtitle="Defaults inherited from the Strict preset. Customize per-site below."/>

      <div style={{
        padding: 16, background: 'linear-gradient(135deg, rgba(110,231,183,0.08), transparent), ' + M_SURFACE,
        border: '1px solid rgba(110,231,183,0.18)', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(110,231,183,0.14)', color: M_ACCENT, display: 'grid', placeItems: 'center' }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Strict tracking protection · ON</div>
          <div style={{ fontSize: 12, color: M_FG_MUTED, marginTop: 2 }}>Blocks third-party cookies, fingerprinting, and known trackers everywhere.</div>
        </div>
        <TSelect value="strict" options={[{value:'strict',label:'Strict'},{value:'balanced',label:'Balanced'},{value:'off',label:'Off'}]}/>
      </div>

      <TSectionLabel>Browsing</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Send a 'Do Not Track' request" right={<TToggle on/>}/>
        <TSettingRow title="HTTPS-Only Mode"      subtitle="Upgrade all sites to HTTPS where possible." right={<TToggle on/>}/>
        <TSettingRow title="Block cross-site cookies" right={<TToggle on/>}/>
        <TSettingRow title="Send Safe Browsing reports anonymously" right={<TToggle/>}/>
      </div>

      <TSectionLabel>Site permissions</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { t: 'Location',     v: 'Ask',  icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-8 8-13a8 8 0 1 0-16 0c0 5 8 13 8 13z"/><circle cx="12" cy="9" r="3"/></svg>,                                          c: '#FBBF24' },
          { t: 'Camera',       v: 'Ask',  icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="4"/></svg>,                                                          c: '#F472B6' },
          { t: 'Microphone',   v: 'Ask',  icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="3" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></svg>,                                       c: '#22D3EE' },
          { t: 'Notifications',v: 'Allow on 4 sites', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M6 8a6 6 0 1 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>,                            c: '#A78BFA' },
        ].map(s => (
          <TSettingRow key={s.t} icon={s.icon} iconColor={s.c}
            title={s.t} subtitle={'Default: ' + s.v}
            onClick={() => {}}/>
        ))}
      </div>

      <TSectionLabel>Clear data</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Clear browsing data…" subtitle="History, cookies, cache, downloads…" onClick={() => {}}/>
        <TSettingRow title="Privacy review" subtitle="A 4-step walkthrough of your most important privacy controls." onClick={() => {}}/>
      </div>
    </>
  );
}

function TSPagePrivateBrowsing() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.private} title="Private browsing"
        subtitle="Controls for what happens inside a private window. Private windows never sync to your other devices."
        accent={PRIV_ACCENT_2}/>

      <div style={{
        padding: 18,
        background: 'radial-gradient(ellipse at 0% 0%, rgba(167,139,250,0.10), transparent 60%), ' + PRIV_SURFACE,
        border: '1px solid ' + PRIV_BORDER, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: 'rgba(167,139,250,0.18)', color: PRIV_ACCENT_2, display: 'grid', placeItems: 'center' }}>
          <IcMask s={22}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: PRIV_FG }}>Private windows are isolated</div>
          <div style={{ fontSize: 12, color: PRIV_FG_MUTED, marginTop: 2, lineHeight: 1.45 }}>Each private window has its own cookies, cache, and history — discarded when closed.</div>
        </div>
      </div>

      <TSectionLabel>Defaults</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Block cross-site tracking" subtitle="Always on in private mode." right={<TChip color={PRIV_ACCENT}>ENFORCED</TChip>}/>
        <TSettingRow title="Block third-party cookies"  right={<TChip color={PRIV_ACCENT}>ENFORCED</TChip>}/>
        <TSettingRow title="Always use HTTPS"           right={<TToggle on/>}/>
        <TSettingRow title="Lock private windows after 5 minutes" subtitle="Requires Face ID / passcode to unlock." right={<TToggle on/>}/>
      </div>

      <TSectionLabel>Identity in private mode</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Stay signed out by default" subtitle="Recommended. Ajna identity, Chat, and Mesh are off."
          right={<TToggle on/>}/>
        <TSettingRow title="Allow Ajna identity if I explicitly sign in" subtitle="A persistent banner reminds you when you do."
          right={<TToggle/>}/>
      </div>

      <TSectionLabel>Search & autofill</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Private search engine" subtitle="Used only inside private windows."
          right={<TSelect value="ddg" options={[{value:'ddg',label:'DuckDuckGo'},{value:'brave',label:'Brave Search'},{value:'kagi',label:'Kagi'}]}/>}/>
        <TSettingRow title="Disable autofill in private windows" right={<TToggle on/>}/>
      </div>
    </>
  );
}

function TSPageAppearance() {
  const [theme, setTheme] = React.useState(() => {
    try { return (window.__ajnaGetTheme && window.__ajnaGetTheme()) || document.body.getAttribute('data-theme') || 'dark'; } catch { return 'dark'; }
  });
  const pickTheme = (id) => { setTheme(id); if (window.__ajnaSetTheme) window.__ajnaSetTheme(id); };
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.appearance} title="Appearance"/>

      <TSectionLabel>Theme</TSectionLabel>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 12 }}>
        {[
          { id: 'auto',  label: 'Match system', preview: 'linear-gradient(135deg, #FAFAF8 50%, #14161B 50%)' },
          { id: 'light', label: 'Light',        preview: '#FAFAF8' },
          { id: 'dark',  label: 'Dark',         preview: '#14161B' },
        ].map(t => {
          const active = theme === t.id;
          return (
          <button key={t.id} onClick={() => pickTheme(t.id)} style={{
            padding: 10, background: M_SURFACE,
            border: '1px solid ' + (active ? 'rgba(96,165,250,0.6)' : M_BORDER_SOFT),
            borderRadius: 12, cursor: 'pointer', textAlign: 'left',
            fontFamily: 'inherit', color: M_FG,
            boxShadow: active ? '0 0 0 3px rgba(96,165,250,0.18)' : 'none',
          }}>
            <div style={{
              height: 60, borderRadius: 8,
              background: t.preview, border: '1px solid ' + M_BORDER_SOFT,
              marginBottom: 8,
            }}/>
            <div style={{ fontSize: 12.5, fontWeight: 500 }}>{t.label}</div>
          </button>
          );
        })}
      </div>

      <TSectionLabel>Accent color</TSectionLabel>
      <div style={{ display: 'flex', gap: 10, padding: '12px 0' }}>
        {[
          { id: 'ajna',    g: 'linear-gradient(135deg,#6EE7B7,#60A5FA)', active: true },
          { id: 'sunrise', g: 'linear-gradient(135deg,#FDE68A,#F472B6)' },
          { id: 'ember',   g: 'linear-gradient(135deg,#FCA5A5,#F59E0B)' },
          { id: 'violet',  g: 'linear-gradient(135deg,#C4B5FD,#818CF8)' },
          { id: 'mono',    g: 'linear-gradient(135deg,#D1D5DB,#6B7280)' },
        ].map(a => (
          <button key={a.id} style={{
            width: 32, height: 32, borderRadius: 16, background: a.g,
            border: a.active ? '2px solid #fff' : '2px solid transparent',
            boxShadow: a.active ? '0 0 0 2px rgba(96,165,250,0.5)' : 'none',
            cursor: 'pointer', padding: 0,
          }} aria-label={a.id}/>
        ))}
      </div>

      <TSectionLabel>Layout</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Show sidebar by default" right={<TToggle on/>}/>
        <TSettingRow title="Collapse chrome on scroll" subtitle="Tab strip shrinks to a single pill when you scroll a page." right={<TToggle on/>}/>
        <TSettingRow title="Show favicons in URL bar" right={<TToggle on/>}/>
        <TSettingRow title="Tab strip density" right={<TSelect value="comfortable" options={['Comfortable','Compact','Spacious']}/>}/>
        <TSettingRow title="Show bookmarks bar" right={<TSelect value="newtab" options={[{value:'newtab',label:'On New Tab page only'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/>}/>
      </div>

      <TSectionLabel>Font</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Page font size" right={<TSelect value="medium" options={['Small','Medium','Large','Very large']}/>}/>
        <TSettingRow title="Customize fonts…" subtitle="Standard, serif, sans-serif, fixed-width" onClick={() => {}}/>
      </div>
    </>
  );
}

function TSPageTabGroups() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.tabgroups} title="Tab groups" subtitle="How tab groups behave, share, and clean themselves up."/>

      <TSectionLabel>Defaults</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Open links in the current group when possible" subtitle="If a link comes from a tab inside a group, the new tab stays in that group."
          right={<TToggle on/>}/>
        <TSettingRow title="Auto-name new groups by domain" subtitle='e.g. opening 3 GitHub tabs together suggests "GitHub".'
          right={<TToggle/>}/>
        <TSettingRow title="Default group color"
          right={<TSelect value="blue" options={[{value:'blue',label:'Blue'},{value:'green',label:'Green'},{value:'violet',label:'Violet'},{value:'cyan',label:'Cyan'},{value:'yellow',label:'Yellow'},{value:'pink',label:'Pink'},{value:'red',label:'Red'}]}/>}/>
      </div>

      <TSectionLabel>Shared groups</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow icon={MIc.mesh({ s: 16 })} iconColor="#A78BFA"
          title="Sync shared groups over"
          subtitle="DIDComm over mesh when possible, mediator as fallback."
          right={<TSelect value="auto" options={[{value:'auto',label:'Auto'},{value:'mesh',label:'Mesh only'},{value:'mediator',label:'Mediator only'}]}/>}/>
        <TSettingRow title="Require approval before joining a shared group" right={<TToggle on/>}/>
        <TSettingRow title="Show member presence on tab cards" subtitle="Avatar of whoever has the tab open right now."
          right={<TToggle on/>}/>
        <TSettingRow title="Notify when someone adds a tab to a shared group" right={<TToggle on/>}/>
      </div>

      <TSectionLabel>Archive & cleanup</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Archive inactive groups after"
          right={<TSelect value="30" options={[{value:'7',label:'7 days'},{value:'30',label:'30 days'},{value:'never',label:'Never'}]}/>}/>
        <TSettingRow title="Memory-save closed groups" subtitle="Keep tab metadata and titles after closing so you can restore them."
          right={<TToggle on/>}/>
      </div>
    </>
  );
}

function TSPageMesh() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.mesh} title="Mesh & peers" subtitle="How this device finds and talks to other Ajna devices."/>

      <div style={{
        padding: 18, borderRadius: 14,
        background: 'linear-gradient(135deg, rgba(110,231,183,0.10), rgba(96,165,250,0.08))',
        border: '1px solid ' + M_BORDER,
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, alignItems: 'center',
      }}>
        <div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: 4, background: '#22D27A', boxShadow: '0 0 10px #22D27A' }}/>
            <span style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Online</span>
          </div>
          <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>did:key:z6Mk…9kTp</div>
        </div>
        {[
          { l: 'Mesh peers', v: '3', s: 'BLE' },
          { l: 'Mediators',  v: '1', s: 'online' },
          { l: 'Throughput', v: '24 KB/s', s: 'last 1m' },
        ].map(s => (
          <div key={s.l} style={{ padding: 12, background: 'rgba(0,0,0,0.28)', borderRadius: 10 }}>
            <div style={{ fontSize: 9.5, color: M_FG_DIM, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>{s.l}</div>
            <div style={{ fontSize: 20, fontFamily: 'Geist', fontWeight: 600, marginTop: 2, letterSpacing: '-0.02em' }}>{s.v}</div>
            <div style={{ fontSize: 10, color: M_FG_MUTED, marginTop: 2 }}>{s.s}</div>
          </div>
        ))}
      </div>

      <TSectionLabel>Transports</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow icon={MIc.bluetooth({ s: 16 })} iconColor="#22D3EE"
          title="Bluetooth LE mesh" subtitle="Connect with nearby Ajna devices, no internet required." right={<TToggle on/>}/>
        <TSettingRow icon={MIc.globe({ s: 16 })} iconColor={M_ACCENT_B}
          title="Mediator routing" subtitle="Relay messages through mediator.ajna.dev when peers are offline." right={<TToggle on/>}/>
        <TSettingRow title="Discoverable by other devices" subtitle="When on, nearby BLE devices can see you as @noah-okafor." right={<TToggle/>}/>
        <TSettingRow title="Auto-reconnect" subtitle="Re-join known mesh networks when in range." right={<TToggle on/>}/>
      </div>

      <TSectionLabel>Peers · 3 connected</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { name: 'Aishwarya · iPhone', bg: '#EF4444', initials: 'AI', conn: 'ble',      hint: '12 m · BLE'  },
          { name: 'Maya · MacBook',     bg: '#A78BFA', initials: 'MC', conn: 'internet', hint: 'online'      },
          { name: 'Rohan · Pixel',      bg: '#F472B6', initials: 'RS', conn: 'mesh',     hint: '8 m · BLE'   },
        ].map(p => (
          <TSettingRow key={p.name}
            icon={<MTile size={28} bg={p.bg} color="#fff" label={p.initials} radius={14}/>}
            iconColor="transparent"
            title={p.name} subtitle={p.hint}
            right={<MConnChip type={p.conn}/>}
          />
        ))}
      </div>

      <TSectionLabel>Mediator</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Mediator endpoint" subtitle="mediator.ajna.dev"
          right={<TSelect value="ajna" options={[{value:'ajna',label:'Ajna default'},{value:'self',label:'Self-hosted…'},{value:'none',label:'None'}]}/>}/>
        <TSettingRow title="Push notifications via mediator" subtitle="Wake the app when offline messages arrive." right={<TToggle on/>}/>
      </div>
    </>
  );
}

function TSPageChat() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.chat} title="Chat & messaging" subtitle="Defaults for 1:1 and group chats over DIDComm."/>

      <TSectionLabel>Privacy</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Read receipts" subtitle="Let people know when you've read their messages." right={<TToggle on/>}/>
        <TSettingRow title="Typing indicators" right={<TToggle on/>}/>
        <TSettingRow title="Last seen visibility"
          right={<TSelect value="contacts" options={[{value:'everyone',label:'Everyone'},{value:'contacts',label:'My contacts'},{value:'nobody',label:'Nobody'}]}/>}/>
        <TSettingRow title="Auto-delete messages after"
          right={<TSelect value="never" options={[{value:'never',label:'Never'},{value:'24h',label:'24 hours'},{value:'7d',label:'7 days'},{value:'30d',label:'30 days'}]}/>}/>
      </div>

      <TSectionLabel>Notifications</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Direct messages" right={<TToggle on/>}/>
        <TSettingRow title="Group messages" subtitle="You can override per-group from the conversation header." right={<TToggle on/>}/>
        <TSettingRow title="Mentions and replies only" right={<TToggle/>}/>
        <TSettingRow title="Preview content in notifications" right={<TToggle/>}/>
      </div>

      <TSectionLabel>Calls</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Allow calls from"
          right={<TSelect value="contacts" options={[{value:'everyone',label:'Everyone'},{value:'contacts',label:'My contacts'},{value:'nobody',label:'Nobody'}]}/>}/>
        <TSettingRow title="Default audio device" right={<TSelect value="device" options={['iPad speaker','AirPods Pro','External']}/>}/>
      </div>

      <TSectionLabel>Storage</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Media auto-download"
          right={<TSelect value="wifi" options={[{value:'wifi',label:'Wi-Fi only'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/>}/>
        <TSettingRow title="Clear chat cache…" subtitle="Frees 412 MB. Does not affect messages." onClick={() => {}}/>
      </div>
    </>
  );
}

function TSPageAbout() {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES.about} title="About Ajna"/>

      <div style={{
        padding: 24, background: 'linear-gradient(135deg, rgba(110,231,183,0.06), rgba(96,165,250,0.06)), ' + M_SURFACE,
        border: '1px solid ' + M_BORDER, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 18,
      }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: 'linear-gradient(135deg,#6EE7B7,#60A5FA)', display: 'grid', placeItems: 'center', color: '#0B0C0F', fontFamily: 'Geist', fontWeight: 700, fontSize: 26 }}>A</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 18, fontWeight: 600, fontFamily: 'Geist, Inter, sans-serif' }}>Ajna Browser</div>
          <div style={{ fontSize: 12.5, color: M_FG_MUTED, marginTop: 4, fontFamily: 'JetBrains Mono, monospace' }}>Version 0.4.2 (24891) · Chromium 124</div>
          <div style={{ fontSize: 11.5, color: M_ACCENT, marginTop: 8, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: 3, background: M_ACCENT, boxShadow: '0 0 8px ' + M_ACCENT }}/> Up to date
          </div>
        </div>
      </div>

      <TSectionLabel>Help</TSectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <TSettingRow title="Release notes" onClick={() => {}}/>
        <TSettingRow title="Report an issue" onClick={() => {}}/>
        <TSettingRow title="Terms of service" onClick={() => {}}/>
        <TSettingRow title="Privacy policy" onClick={() => {}}/>
      </div>
    </>
  );
}

// Generic "simple list" page used for the lower-importance settings —
// keeps the page felt-complete without exploding the file size.
function TSPageSimple({ routeKey, title, subtitle, rows }) {
  return (
    <>
      <TSHeader route={T_SETTING_ROUTES[routeKey]} title={title} subtitle={subtitle}/>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {rows.map((r, i) => {
          if (r.section) return <TSectionLabel key={'s'+i}>{r.section}</TSectionLabel>;
          return <TSettingRow key={i} {...r}/>;
        })}
      </div>
    </>
  );
}

function TSHeader({ route, title, subtitle, accent }) {
  return (
    <div style={{ marginBottom: 20 }}>
      {route && <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{route}</div>}
      <h1 style={{
        margin: '6px 0 6px', fontFamily: 'Geist, Inter, sans-serif',
        fontSize: 30, lineHeight: 1.1, fontWeight: 600, letterSpacing: '-0.025em',
        color: accent || M_FG,
      }}>{title}</h1>
      {subtitle && <p style={{ margin: 0, color: M_FG_MUTED, fontSize: 13, lineHeight: 1.55, maxWidth: 560 }}>{subtitle}</p>}
    </div>
  );
}

// ─── Main page ──────────────────────────────────────────────
function TScreenSettings({ landscape = true, initial = 'identity' }) {
  const [active, setActive] = React.useState(initial);
  const [query, setQuery] = React.useState('');

  // Build flat searchable list once
  const flatItems = React.useMemo(() => {
    const out = [];
    T_SETTINGS_NAV.forEach(s => s.items.forEach(it => out.push({ ...it, section: s.section })));
    return out;
  }, []);
  const filtered = query.trim()
    ? flatItems.filter(i => i.label.toLowerCase().includes(query.toLowerCase().trim()))
    : null;

  const PAGES = {
    identity:   () => <TSPageIdentity/>,
    privacy:    () => <TSPagePrivacy/>,
    private:    () => <TSPagePrivateBrowsing/>,
    appearance: () => <TSPageAppearance/>,
    tabgroups:  () => <TSPageTabGroups/>,
    mesh:       () => <TSPageMesh/>,
    chat:       () => <TSPageChat/>,
    about:      () => <TSPageAbout/>,
    autofill:   () => <TSPageSimple routeKey="autofill" title="Autofill & passwords" subtitle="Saved passwords, addresses, and payment methods sync end-to-end encrypted." rows={[
      { section: 'Passwords' },
      { title: 'Saved passwords', subtitle: '128 saved · last sync 4m ago', onClick: () => {} },
      { title: 'Offer to save passwords', right: <TToggle on/> },
      { title: 'Auto sign-in', right: <TToggle on/> },
      { title: 'Password checkup', subtitle: '3 compromised · 8 weak · 12 reused', right: <TChip color="#F87171">REVIEW</TChip>, onClick: () => {} },
      { section: 'Addresses' },
      { title: 'Saved addresses', subtitle: '2 saved', onClick: () => {} },
      { title: 'Save and fill addresses', right: <TToggle on/> },
      { section: 'Payment methods' },
      { title: 'Saved cards', subtitle: '3 cards', onClick: () => {} },
      { title: 'Save and fill payment methods', right: <TToggle on/> },
      { title: 'Allow sites to check if you have payment methods saved', right: <TToggle on/> },
    ]}/>,
    search:     () => <TSPageSimple routeKey="search" title="Search engine" subtitle="What happens when you type into the URL pill." rows={[
      { section: 'Search engine used in the address bar' },
      { title: 'Default', right: <TSelect value="ajna" options={[{value:'ajna',label:'Ajna (privacy)'},{value:'google',label:'Google'},{value:'duckduckgo',label:'DuckDuckGo'},{value:'kagi',label:'Kagi'},{value:'brave',label:'Brave Search'}]}/> },
      { title: 'Show search suggestions', right: <TToggle on/> },
      { title: 'Show trending searches', right: <TToggle/> },
      { section: 'Manage' },
      { title: 'Site search shortcuts', subtitle: 'Type @gh, @wiki, @lin to search inside specific sites', onClick: () => {} },
    ]}/>,
    startup:    () => <TSPageSimple routeKey="startup" title="On startup" subtitle="What Ajna does when you open it." rows={[
      { title: 'Open the New Tab page',                       right: <TToggle/> },
      { title: 'Continue where you left off',                 right: <TToggle on/>, subtitle: 'Restores tabs and tab groups from your last session.' },
      { title: 'Open a specific page or set of pages…',       right: <TToggle/>, onClick: () => {} },
    ]}/>,
    default:    () => <TSPageSimple routeKey="default" title="Default browser" rows={[
      { title: 'Make Ajna your default browser', subtitle: 'Links from other apps will open here.', right: <TChip>DEFAULT</TChip> },
    ]}/>,
    perf:       () => <TSPageSimple routeKey="perf" title="Performance" rows={[
      { section: 'Memory' },
      { title: 'Memory saver',  subtitle: 'Freezes inactive tabs to free RAM. Tabs reload on click.', right: <TToggle on/> },
      { title: 'Show memory usage on tab cards', right: <TToggle/> },
      { section: 'Energy' },
      { title: 'Energy saver',  subtitle: 'Limit background activity and visual effects.', right: <TSelect value="auto" options={[{value:'auto',label:'When battery < 20%'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/> },
      { section: 'Prefetch' },
      { title: 'Preload pages',  subtitle: 'Makes browsing and search faster. Uses cookies.', right: <TToggle on/> },
    ]}/>,
    downloads:  () => <TSPageSimple routeKey="downloads" title="Downloads" rows={[
      { title: 'Location', subtitle: 'iCloud Drive · Ajna / Downloads', onClick: () => {} },
      { title: 'Ask where to save each file before downloading', right: <TToggle/> },
      { title: "Show downloads when they're done", right: <TToggle on/> },
    ]}/>,
    languages:  () => <TSPageSimple routeKey="languages" title="Languages" subtitle="Order matters — Ajna asks pages for the first language that's available." rows={[
      { title: 'English (United States)',  subtitle: 'Primary',  right: <TChip>PRIMARY</TChip> },
      { title: 'हिन्दी (हिंदी)' },
      { title: 'Deutsch' },
      { title: 'Add languages…', onClick: () => {} },
      { section: 'Translation' },
      { title: 'Offer to translate pages not in your languages', right: <TToggle on/> },
      { title: 'Translate using',  right: <TSelect value="ajna" options={[{value:'ajna',label:'Ajna on-device'},{value:'google',label:'Google Translate'}]}/> },
    ]}/>,
    a11y:       () => <TSPageSimple routeKey="a11y" title="Accessibility" rows={[
      { title: 'Always show navigation hints', subtitle: 'Show tooltips for icons and gestures.', right: <TToggle/> },
      { title: 'Larger text', subtitle: 'Increases base font size system-wide.', right: <TSelect value="100" options={[{value:'90',label:'90%'},{value:'100',label:'100%'},{value:'120',label:'120%'},{value:'150',label:'150%'}]}/> },
      { title: 'High contrast mode', right: <TToggle/> },
      { title: 'Reduce motion', subtitle: 'Disables non-essential animations.', right: <TToggle/> },
      { title: 'Underline links', right: <TToggle/> },
      { title: 'Screen reader optimizations', right: <TToggle on/> },
    ]}/>,
    system:     () => <TSPageSimple routeKey="system" title="System" rows={[
      { title: 'Continue running background apps when Ajna is closed', right: <TToggle/> },
      { title: 'Use hardware acceleration when available', right: <TToggle on/> },
      { title: 'Use prediction service to load pages more quickly', right: <TToggle on/> },
      { section: 'Proxy' },
      { title: 'Network proxy', subtitle: 'Direct connection — no proxy configured.', onClick: () => {} },
    ]}/>,
    reset:      () => <TSPageSimple routeKey="reset" title="Reset settings" subtitle="Choose how thoroughly to reset Ajna. None of these affect bookmarks, history, or saved passwords." rows={[
      { title: 'Restore settings to their original defaults', subtitle: 'Resets startup page, new tab page, search engine, pinned tabs, content settings, cookies, extensions, and themes.', onClick: () => {} },
      { title: 'Clean up computer', subtitle: 'Find and remove harmful software.', onClick: () => {} },
      { title: 'Sign out and forget this device', danger: true, onClick: () => {} },
    ]}/>,
    extensions: () => <TSPageSimple routeKey="extensions" title="Extensions" subtitle="Extensions inherit Chromium's permission model. Mesh-aware extensions can use DIDComm transport." rows={[
      { title: '1Password',         subtitle: 'Password manager · Access to all sites', right: <TToggle on/> },
      { title: 'Stylus',            subtitle: 'User stylesheets · Access to all sites', right: <TToggle on/> },
      { title: 'Vimium',            subtitle: 'Keyboard shortcuts · Access to all sites', right: <TToggle/> },
      { title: 'Manage extensions…', subtitle: 'Open ajna://extensions', onClick: () => {} },
    ]}/>,
  };

  const Page = PAGES[active] || PAGES.identity;

  return (
    <div style={{ flex: 1, display: 'flex', minHeight: 0, background: M_BG, overflow: 'hidden' }}>
      {/* Left nav rail */}
      <nav style={{
        width: 240, flexShrink: 0,
        borderRight: '1px solid ' + M_BORDER_SOFT,
        padding: '16px 10px 16px',
        overflowY: 'auto', minHeight: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 8px 14px' }}>
          <div style={{ width: 22, height: 22, borderRadius: 7, background: 'linear-gradient(135deg,#6EE7B7,#60A5FA)', display: 'grid', placeItems: 'center', color: '#0B0C0F', fontWeight: 700, fontSize: 13, fontFamily: 'Geist' }}>A</div>
          <span style={{ fontSize: 14, fontFamily: 'Geist, Inter, sans-serif', fontWeight: 600, letterSpacing: '-0.01em' }}>Settings</span>
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 11px', marginBottom: 14,
          background: M_SURFACE, borderRadius: 8,
          border: '1px solid ' + M_BORDER_SOFT,
        }}>
          <span style={{ color: M_FG_DIM, display: 'grid', placeItems: 'center' }}>{MIc.search({ s: 13 })}</span>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="Search settings"
            style={{
              flex: 1, background: 'transparent', border: 0, outline: 0,
              color: M_FG, fontSize: 12, fontFamily: 'inherit', minWidth: 0,
            }}
          />
        </div>

        {filtered ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {filtered.length === 0 && (
              <div style={{ fontSize: 12, color: M_FG_DIM, padding: 12, textAlign: 'center' }}>No matches.</div>
            )}
            {filtered.map(it => (
              <TSNavItem key={it.id} item={it} active={active === it.id} onClick={() => { setActive(it.id); setQuery(''); }}/>
            ))}
          </div>
        ) : (
          T_SETTINGS_NAV.map((sec, i) => (
            <div key={i} style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 9.5, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, padding: '4px 10px 8px' }}>{sec.section}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                {sec.items.map(it => (
                  <TSNavItem key={it.id} item={it} active={active === it.id} onClick={() => setActive(it.id)}/>
                ))}
              </div>
            </div>
          ))
        )}
      </nav>

      {/* Right page */}
      <main style={{ flex: 1, overflowY: 'auto', padding: '24px 36px 60px', minHeight: 0 }}>
        <div style={{ maxWidth: 720 }}>
          <Page/>
        </div>
      </main>
    </div>
  );
}

Object.assign(window, {
  TScreenSettings, T_SETTINGS_NAV, T_SETTING_ROUTES, TSettingRow, TSectionLabel, TToggle, TSelect, TChip,
});
