// Mobile Settings — iOS-style drill-down navigation.
// Pattern: top-level list grouped by section → tap to drill into a sub-page
// → back button returns to the list. Reuses the iPad's setting categories
// (T_SETTINGS_NAV) and many of its sub-pages (TSPageIdentity, TSPagePrivacy,
// etc.) since they're vertically-flowing row layouts that work at narrow
// widths. Mobile-specific chrome wraps each sub-page.

// Local IcMask — defined here because the global IcMask (in tablet-private.jsx)
// loads AFTER this file, and we reference it at module-scope inside M_SETTINGS_NAV.
const MS_IcMask = ({ s = 14 }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 8c0-1.5 1.5-3 4-3h10c2.5 0 4 1.5 4 3v4c0 3-2 5-5 5-1.5 0-2.5-.7-4-1.5C10.5 16.3 9.5 17 8 17c-3 0-5-2-5-5z"/>
    <circle cx="8" cy="11" r="1.4"/><circle cx="16" cy="11" r="1.4"/>
  </svg>
);

// ─── Tiny primitives (mobile-tuned versions of the iPad ones) ─────
function MSToggle({ on, onChange }) {
  return (
    <button onClick={() => onChange && onChange(!on)} style={{
      width: 40, height: 24, borderRadius: 12, padding: 0, flexShrink: 0,
      background: on ? 'linear-gradient(135deg,#6EE7B7,#60A5FA)' : 'var(--m-tint)',
      border: '1px solid ' + (on ? 'transparent' : M_BORDER),
      position: 'relative', cursor: 'pointer',
      transition: 'background 200ms',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 18, height: 18, borderRadius: 9, background: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
        transition: 'left 200ms',
      }}/>
    </button>
  );
}

function MSRow({ icon, iconColor, title, subtitle, right, onClick, danger, last }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderBottom: last ? 0 : '1px solid ' + M_BORDER_SOFT,
      cursor: onClick ? 'pointer' : 'default',
    }}>
      {icon && (
        <div style={{
          width: 28, height: 28, borderRadius: 7,
          background: iconColor ? iconColor + '22' : 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, fontWeight: 500, color: danger ? '#F87171' : M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{title}</div>
        {subtitle && <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 2, lineHeight: 1.4 }}>{subtitle}</div>}
      </div>
      {right || (onClick && (
        <span style={{ color: M_FG_DIM, display: 'grid', placeItems: 'center' }}>
          <svg width="12" height="12" 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 MSCard({ children, label, sub }) {
  return (
    <>
      {label && (
        <div style={{ padding: '14px 4px 8px' }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace' }}>{label}</div>
          {sub && <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 3, lineHeight: 1.4 }}>{sub}</div>}
        </div>
      )}
      <div style={{ background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden' }}>
        {children}
      </div>
    </>
  );
}

function MSChip({ children, color = M_ACCENT }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 7px', borderRadius: 999,
      background: color + '22', color, fontSize: 9.5,
      fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em',
      fontWeight: 600, flexShrink: 0,
    }}>
      <span style={{ width: 4, height: 4, borderRadius: 2, background: color, boxShadow: '0 0 5px ' + color }}/>
      {children}
    </span>
  );
}

function MSSelect({ value, options, onChange }) {
  return (
    <select value={value} onChange={e => onChange && onChange(e.target.value)} style={{
      background: 'var(--m-tint)', color: M_FG, border: 0,
      borderRadius: 7, padding: '5px 22px 5px 10px', fontSize: 11.5,
      fontFamily: 'inherit', cursor: 'pointer', flexShrink: 0,
      appearance: 'none', maxWidth: 160,
      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 7px center',
    }}>
      {options.map(o => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
    </select>
  );
}

// ─── Nav config (mirrors iPad's T_SETTINGS_NAV, mobile icons) ────
const M_SETTINGS_NAV = [
  { section: 'Account', items: [
    { id: 'identity',  label: 'You & Ajna',           sub: 'Identity, devices, sync', color: '#A78BFA',
      icon: <svg width="14" height="14" 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>,
      badge: '3 devices' },
    { id: 'autofill',  label: 'Autofill & passwords', sub: '128 saved · 3 compromised', color: '#F472B6',
      icon: <svg width="14" height="14" 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> },
  ]},
  { section: 'Privacy', items: [
    { id: 'privacy',   label: 'Privacy & security',   sub: 'Strict tracking protection · ON', color: '#6EE7B7',
      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 2 4 5v7c0 5 3.5 8.5 8 10 4.5-1.5 8-5 8-10V5z"/></svg> },
    { id: 'private',   label: 'Private browsing',     sub: 'Always-on protections', color: '#C4B5FD',
      icon: <MS_IcMask s={14}/> },
  ]},
  { section: 'Browser', items: [
    { id: 'appearance',label: 'Appearance',           sub: 'Theme, accent, layout', color: '#FBBF24',
      icon: <svg width="14" height="14" 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> },
    { id: 'search',    label: 'Search engine',        sub: 'Ajna · privacy', color: M_ACCENT_B,
      icon: <svg width="14" height="14" 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> },
    { id: 'startup',   label: 'On startup',           sub: 'Continue where you left off', color: '#22D3EE',
      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 3v9"/><path d="M5.6 7.4a9 9 0 1 0 12.8 0"/></svg> },
    { id: 'default',   label: 'Default browser',      sub: 'Currently default', color: '#10B981',
      icon: <svg width="14" height="14" 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> },
    { id: 'tabgroups', label: 'Tab groups',           sub: 'Share over mesh · auto-archive', color: '#60A5FA',
      icon: <svg width="14" height="14" 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> },
    { id: 'perf',      label: 'Performance',          sub: 'Memory + energy saver', color: '#F59E0B',
      icon: <svg width="14" height="14" 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> },
  ]},
  { section: 'Ajna network', items: [
    { id: 'mesh',      label: 'Mesh & peers',         sub: '3 online · BLE + mediator', color: '#A78BFA',
      icon: <svg width="14" height="14" 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> },
    { id: 'chat',      label: 'Chat & messaging',     sub: 'Read receipts, calls', color: M_ACCENT_B,
      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 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> },
  ]},
  { section: 'Advanced', items: [
    { id: 'downloads', label: 'Downloads',            sub: 'iCloud Drive · Ajna', color: '#0EA5E9',
      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 4v12m0 0-4-4m4 4 4-4M4 20h16"/></svg> },
    { id: 'languages', label: 'Languages',            sub: 'English (US) · 2 others', color: '#84CC16',
      icon: <svg width="14" height="14" 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> },
    { id: 'a11y',      label: 'Accessibility',        sub: 'Text size, motion, contrast', color: '#EC4899',
      icon: <svg width="14" height="14" 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> },
    { id: 'system',    label: 'System',               sub: 'Hardware acceleration, proxy', color: M_FG_MUTED,
      icon: <svg width="14" height="14" 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> },
    { id: 'reset',     label: 'Reset settings',       sub: 'Restore defaults', color: '#F87171',
      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 12a9 9 0 1 0 3-6.7"/><path d="M3 4v5h5"/></svg> },
  ]},
  { section: 'About', items: [
    { id: 'about',     label: 'About Ajna',           sub: 'v0.4.2 · up to date', color: M_FG_MUTED,
      icon: <svg width="14" height="14" 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> },
  ]},
];

// ─── Sub-page bodies — mobile-tuned variants of the iPad pages ────
function MSPageIdentity() {
  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', label: 'MC' },
    { bg: '#22D3EE', label: 'MC' },
    { bg: '#F472B6', label: 'MC' },
    { bg: '#FBBF24', label: 'MC' },
    { bg: '#10B981', label: 'MC' },
    { bg: '#EF4444', label: 'MC' },
  ];
  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]);

  return (
    <>
      {/* Identity hero — name and avatar are editable; handle and DID are not. */}
      <div style={{
        padding: 16, marginBottom: 16,
        background: 'linear-gradient(135deg, rgba(110,231,183,0.06), rgba(96,165,250,0.06)), ' + M_SURFACE,
        border: '1px solid ' + M_BORDER_SOFT, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <MTile size={52} bg={av.bg} color="#fff" label={initials} radius={26}/>
          <button
            onClick={() => setPicking(p => !p)}
            aria-label="Change photo"
            style={{
              position: 'absolute', right: -2, bottom: -2,
              width: 22, height: 22, borderRadius: 11,
              background: M_FG, color: '#0B0C0F', border: '2px solid ' + M_BG,
              display: 'grid', placeItems: 'center', cursor: 'pointer', padding: 0,
            }}>
            <svg width="11" height="11" 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); }}
              style={{
                width: '100%', background: 'var(--m-tint)',
                border: '1px solid rgba(96,165,250,0.45)',
                borderRadius: 7, padding: '4px 8px',
                color: M_FG, fontSize: 15, fontWeight: 600,
                fontFamily: 'Geist', letterSpacing: '-0.02em', outline: 0,
              }}
            />
          ) : (
            <button
              onClick={() => setEditing(true)}
              style={{
                background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
                fontSize: 15, fontWeight: 600, color: M_FG,
                fontFamily: 'Geist', letterSpacing: '-0.02em', textAlign: 'left',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}
              aria-label="Edit name"
            >
              {name}
              <svg width="11" height="11" 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={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
            <span style={{ fontSize: 10.5, color: M_FG_MUTED }}>@noah-okafor</span>
            <span title="Handle is permanent" style={{ color: M_FG_DIM, display: 'inline-flex' }}>
              <svg width="9" height="9" 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>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 2 }}>
            <span style={{ fontSize: 9.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>did:key:z6Mk…9kTp</span>
            <span title="DID is bound to this device" style={{ color: M_FG_DIM, display: 'inline-flex' }}>
              <svg width="9" height="9" 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>
          </div>
        </div>
      </div>

      {/* Avatar picker — appears when camera badge is tapped */}
      {picking && (
        <div style={{
          marginTop: -8, marginBottom: 16,
          padding: 12, background: M_SURFACE,
          border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12,
        }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', marginBottom: 10 }}>Pick a color</div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {avatars.map((a, i) => (
              <button key={i} onClick={() => { setAvatarIdx(i); setPicking(false); }}
                aria-label={'Avatar ' + (i + 1)}
                style={{
                  width: 36, height: 36, borderRadius: 18, 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: 12, letterSpacing: '-0.02em',
                  cursor: 'pointer', display: 'grid', placeItems: 'center',
                }}>{initials}</button>
            ))}
            <button onClick={() => {/* prototype stub: file picker */ setPicking(false); }}
              aria-label="Upload photo"
              style={{
                width: 36, height: 36, borderRadius: 18, padding: 0,
                background: 'var(--m-tint)', color: M_FG_MUTED,
                border: '1px dashed ' + M_BORDER, cursor: 'pointer',
                display: 'grid', placeItems: 'center',
              }}>
              <svg width="14" height="14" 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>
      )}

      <MSCard label="Sync">
        <MSRow title="Sync everything" subtitle="Encrypted end-to-end" right={<MSToggle on/>}/>
        <MSRow title="Sync passphrase" right={<MSChip color={M_ACCENT_B}>SET</MSChip>}/>
        <MSRow title="Manage what you sync" subtitle="Tabs · Bookmarks · History · Passwords" onClick={() => {}} last/>
      </MSCard>

      <MSCard label="Devices · 3">
        <MSRow icon={<svg width="14" height="14" 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="iPhone (this device)" subtitle="Active now" right={<MSChip>THIS</MSChip>}/>
        <MSRow icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="14" rx="2"/><path d="M8 22h8"/><path d="M12 18v4"/></svg>}
          title="iPad Pro" subtitle="Last seen 4m" right={<MSChip color="#22D3EE">BLE</MSChip>}/>
        <MSRow icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M8 21h8M12 17v4"/></svg>}
          title="MacBook Air" subtitle="Last seen 2h" right={<MSChip color={M_ACCENT_B}>NET</MSChip>} last/>
      </MSCard>
    </>
  );
}

function MSPagePrivacy() {
  return (
    <>
      <div style={{
        padding: 14, marginBottom: 16,
        background: 'linear-gradient(135deg, rgba(110,231,183,0.10), transparent), ' + M_SURFACE,
        border: '1px solid rgba(110,231,183,0.20)', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(110,231,183,0.16)', color: M_ACCENT, display: 'grid', placeItems: 'center' }}>
          <svg width="18" height="18" 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: 13, fontWeight: 600 }}>Strict protection · ON</div>
          <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 1, lineHeight: 1.4 }}>Blocks third-party cookies and trackers.</div>
        </div>
        <MSSelect value="strict" options={[{value:'strict',label:'Strict'},{value:'balanced',label:'Balanced'},{value:'off',label:'Off'}]}/>
      </div>

      <MSCard label="Browsing">
        <MSRow title="Send 'Do Not Track'" right={<MSToggle on/>}/>
        <MSRow title="HTTPS-Only Mode" subtitle="Upgrade all sites where possible" right={<MSToggle on/>}/>
        <MSRow title="Block cross-site cookies" right={<MSToggle on/>}/>
        <MSRow title="Safe browsing reports" right={<MSToggle/>} last/>
      </MSCard>

      <MSCard label="Site permissions">
        <MSRow 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>} iconColor="#FBBF24"
          title="Location" subtitle="Ask" onClick={() => {}}/>
        <MSRow 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>} iconColor="#F472B6"
          title="Camera" subtitle="Ask" onClick={() => {}}/>
        <MSRow 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>} iconColor="#22D3EE"
          title="Microphone" subtitle="Ask" onClick={() => {}}/>
        <MSRow 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>} iconColor="#A78BFA"
          title="Notifications" subtitle="Allow on 4 sites" onClick={() => {}} last/>
      </MSCard>

      <MSCard label="Data">
        <MSRow title="Clear browsing data…" subtitle="History, cookies, cache, downloads" onClick={() => {}}/>
        <MSRow title="Privacy review" subtitle="4-step walkthrough" onClick={() => {}} last/>
      </MSCard>
    </>
  );
}

function MSPagePrivate() {
  return (
    <>
      <div style={{
        padding: 14, marginBottom: 16,
        background: 'radial-gradient(ellipse at 0% 0%, rgba(167,139,250,0.12), transparent 60%), ' + M_SURFACE,
        border: '1px solid rgba(167,139,250,0.22)', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(167,139,250,0.20)', color: '#C4B5FD', display: 'grid', placeItems: 'center' }}>
          <MS_IcMask s={18}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Private windows are isolated</div>
          <div style={{ fontSize: 11, color: M_FG_MUTED, marginTop: 1, lineHeight: 1.4 }}>Own cookies, cache, history — discarded on close.</div>
        </div>
      </div>

      <MSCard label="Defaults">
        <MSRow title="Block cross-site tracking" right={<MSChip color="#C4B5FD">ENFORCED</MSChip>}/>
        <MSRow title="Block third-party cookies"  right={<MSChip color="#C4B5FD">ENFORCED</MSChip>}/>
        <MSRow title="Always use HTTPS" right={<MSToggle on/>}/>
        <MSRow title="Lock after 5 minutes" subtitle="Face ID to unlock" right={<MSToggle on/>} last/>
      </MSCard>

      <MSCard label="Identity">
        <MSRow title="Stay signed out by default" subtitle="Identity, Chat, Mesh are off" right={<MSToggle on/>}/>
        <MSRow title="Allow sign-in if explicit" subtitle="Persistent banner reminds you" right={<MSToggle/>} last/>
      </MSCard>

      <MSCard label="Search & autofill">
        <MSRow title="Private search engine" right={<MSSelect value="ddg" options={[{value:'ddg',label:'DuckDuckGo'},{value:'brave',label:'Brave'},{value:'kagi',label:'Kagi'}]}/>}/>
        <MSRow title="Disable autofill" right={<MSToggle on/>} last/>
      </MSCard>
    </>
  );
}

function MSPageAppearance() {
  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 (
    <>
      <MSCard label="Theme">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, padding: 10 }}>
          {[
            { id: 'auto',  label: 'Auto',  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: 8, background: 'var(--m-tint-2)',
              border: '1px solid ' + (active ? 'rgba(96,165,250,0.55)' : M_BORDER_SOFT),
              borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', color: M_FG,
              boxShadow: active ? '0 0 0 2px rgba(96,165,250,0.2)' : 'none',
            }}>
              <div style={{ height: 44, borderRadius: 6, background: t.preview, border: '1px solid ' + M_BORDER_SOFT, marginBottom: 6 }}/>
              <div style={{ fontSize: 11, fontWeight: 500 }}>{t.label}</div>
            </button>
            );
          })}
        </div>
      </MSCard>

      <MSCard label="Accent">
        <div style={{ display: 'flex', gap: 10, padding: 12 }}>
          {[
            { 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: 30, height: 30, borderRadius: 15, background: a.g,
              border: a.active ? '2px solid #fff' : '2px solid transparent',
              boxShadow: a.active ? '0 0 0 2px rgba(96,165,250,0.45)' : 'none',
              cursor: 'pointer', padding: 0,
            }}/>
          ))}
        </div>
      </MSCard>

      <MSCard label="Layout">
        <MSRow title="Collapse chrome on scroll" subtitle="Address bar shrinks when scrolling" right={<MSToggle on/>}/>
        <MSRow title="Show favicons in URL bar" right={<MSToggle on/>}/>
        <MSRow title="Address bar position" right={<MSSelect value="bottom" options={[{value:'bottom',label:'Bottom'},{value:'top',label:'Top'}]}/>}/>
        <MSRow title="Show bookmarks bar" right={<MSSelect value="newtab" options={[{value:'newtab',label:'On NTP only'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/>} last/>
      </MSCard>

      <MSCard label="Font">
        <MSRow title="Page font size" right={<MSSelect value="medium" options={['Small','Medium','Large','Very large']}/>}/>
        <MSRow title="Customize fonts…" subtitle="Standard, serif, sans-serif" onClick={() => {}} last/>
      </MSCard>
    </>
  );
}

function MSPageMesh() {
  return (
    <>
      <div style={{
        padding: 14, marginBottom: 16, borderRadius: 14,
        background: 'linear-gradient(135deg, rgba(110,231,183,0.10), rgba(96,165,250,0.10))',
        border: '1px solid ' + M_BORDER_SOFT,
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 4, background: '#22D27A', boxShadow: '0 0 8px #22D27A' }}/>
          <span style={{ fontSize: 10, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Online</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {[
            { l: 'Peers',  v: '3',       s: 'BLE' },
            { l: 'Relay',  v: '1',       s: 'online' },
            { l: 'Speed',  v: '24 KB/s', s: 'last 1m' },
          ].map(x => (
            <div key={x.l} style={{ padding: 10, background: 'rgba(0,0,0,0.32)', borderRadius: 8 }}>
              <div style={{ fontSize: 9, color: M_FG_DIM, letterSpacing: '0.08em', textTransform: 'uppercase', fontWeight: 600 }}>{x.l}</div>
              <div style={{ fontSize: 17, fontFamily: 'Geist', fontWeight: 600, marginTop: 2, letterSpacing: '-0.02em' }}>{x.v}</div>
              <div style={{ fontSize: 9.5, color: M_FG_MUTED, marginTop: 1 }}>{x.s}</div>
            </div>
          ))}
        </div>
      </div>

      <MSCard label="Transports">
        <MSRow icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="m7 7 10 10-5 5V2l5 5L7 17"/></svg>} iconColor="#22D3EE"
          title="Bluetooth LE mesh" subtitle="Nearby devices, no internet" right={<MSToggle on/>}/>
        <MSRow icon={<svg width="14" height="14" 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>} iconColor={M_ACCENT_B}
          title="Mediator routing" subtitle="Relay via mediator.ajna.dev" right={<MSToggle on/>}/>
        <MSRow title="Discoverable" subtitle="Nearby devices see you" right={<MSToggle/>}/>
        <MSRow title="Auto-reconnect" right={<MSToggle on/>} last/>
      </MSCard>

      <MSCard label="Peers · 3">
        <MSRow icon={<MTile size={22} bg="#EF4444" color="#fff" label="AI" radius={11}/>} iconColor="transparent"
          title="Aishwarya · iPhone" subtitle="12m · BLE" right={<MSChip color="#22D3EE">BLE</MSChip>}/>
        <MSRow icon={<MTile size={22} bg="#A78BFA" color="#fff" label="MC" radius={11}/>} iconColor="transparent"
          title="Maya · MacBook" subtitle="Online" right={<MSChip color={M_ACCENT_B}>NET</MSChip>}/>
        <MSRow icon={<MTile size={22} bg="#F472B6" color="#fff" label="RS" radius={11}/>} iconColor="transparent"
          title="Rohan · Pixel" subtitle="8m · BLE" right={<MSChip color="#22D3EE">BLE</MSChip>} last/>
      </MSCard>

      <MSCard label="Mediator">
        <MSRow title="Endpoint" subtitle="mediator.ajna.dev" right={<MSSelect value="ajna" options={[{value:'ajna',label:'Default'},{value:'self',label:'Self-hosted'},{value:'none',label:'None'}]}/>}/>
        <MSRow title="Push notifications" subtitle="Wake on offline messages" right={<MSToggle on/>} last/>
      </MSCard>
    </>
  );
}

function MSPageChat() {
  return (
    <>
      <MSCard label="Privacy">
        <MSRow title="Read receipts" right={<MSToggle on/>}/>
        <MSRow title="Typing indicators" right={<MSToggle on/>}/>
        <MSRow title="Last seen" right={<MSSelect value="contacts" options={[{value:'everyone',label:'Everyone'},{value:'contacts',label:'Contacts'},{value:'nobody',label:'Nobody'}]}/>}/>
        <MSRow title="Auto-delete after" right={<MSSelect value="never" options={[{value:'never',label:'Never'},{value:'24h',label:'24 hours'},{value:'7d',label:'7 days'},{value:'30d',label:'30 days'}]}/>} last/>
      </MSCard>

      <MSCard label="Notifications">
        <MSRow title="Direct messages" right={<MSToggle on/>}/>
        <MSRow title="Group messages" right={<MSToggle on/>}/>
        <MSRow title="Mentions only" right={<MSToggle/>}/>
        <MSRow title="Preview content" right={<MSToggle/>} last/>
      </MSCard>

      <MSCard label="Calls">
        <MSRow title="Allow calls from" right={<MSSelect value="contacts" options={[{value:'everyone',label:'Everyone'},{value:'contacts',label:'Contacts'},{value:'nobody',label:'Nobody'}]}/>}/>
        <MSRow title="Default audio" right={<MSSelect value="airpods" options={['Speaker','AirPods Pro','External']}/>} last/>
      </MSCard>

      <MSCard label="Storage">
        <MSRow title="Media auto-download" right={<MSSelect value="wifi" options={[{value:'wifi',label:'Wi-Fi only'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/>}/>
        <MSRow title="Clear chat cache…" subtitle="Frees 412 MB" onClick={() => {}} last/>
      </MSCard>
    </>
  );
}

function MSPageTabGroups() {
  return (
    <>
      <MSCard label="Defaults">
        <MSRow title="Stay in current group" subtitle="Links open in the same group" right={<MSToggle on/>}/>
        <MSRow title="Auto-name by domain" subtitle='e.g. 3 GitHub tabs → "GitHub"' right={<MSToggle/>}/>
        <MSRow title="Default group color" right={<MSSelect value="blue" options={['Blue','Green','Violet','Cyan','Yellow','Pink','Red']}/>} last/>
      </MSCard>

      <MSCard label="Shared groups">
        <MSRow icon={<svg width="14" height="14" 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>} iconColor="#A78BFA"
          title="Sync over" right={<MSSelect value="auto" options={[{value:'auto',label:'Auto'},{value:'mesh',label:'Mesh'},{value:'mediator',label:'Mediator'}]}/>}/>
        <MSRow title="Require approval to join" right={<MSToggle on/>}/>
        <MSRow title="Show member presence" right={<MSToggle on/>}/>
        <MSRow title="Notify on add" right={<MSToggle on/>} last/>
      </MSCard>

      <MSCard label="Archive">
        <MSRow title="Archive inactive after" right={<MSSelect value="30" options={[{value:'7',label:'7 days'},{value:'30',label:'30 days'},{value:'never',label:'Never'}]}/>}/>
        <MSRow title="Memory-save closed groups" right={<MSToggle on/>} last/>
      </MSCard>
    </>
  );
}

function MSPageAbout() {
  return (
    <>
      <div style={{
        padding: 18, marginBottom: 16,
        background: 'linear-gradient(135deg, rgba(110,231,183,0.06), rgba(96,165,250,0.06)), ' + M_SURFACE,
        border: '1px solid ' + M_BORDER_SOFT, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 14,
      }}>
        <div style={{ width: 46, height: 46, borderRadius: 12, background: 'linear-gradient(135deg,#6EE7B7,#60A5FA)', display: 'grid', placeItems: 'center', color: '#0B0C0F', fontFamily: 'Geist', fontWeight: 700, fontSize: 22 }}>A</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600, fontFamily: 'Geist' }}>Ajna Browser</div>
          <div style={{ fontSize: 10.5, color: M_FG_MUTED, marginTop: 2, fontFamily: 'JetBrains Mono, monospace' }}>v0.4.2 (24891)</div>
          <div style={{ fontSize: 10.5, color: M_ACCENT, marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <span style={{ width: 5, height: 5, borderRadius: 2.5, background: M_ACCENT, boxShadow: '0 0 6px ' + M_ACCENT }}/> Up to date
          </div>
        </div>
      </div>

      <MSCard label="Help">
        <MSRow title="Release notes" onClick={() => {}}/>
        <MSRow title="Report an issue" onClick={() => {}}/>
        <MSRow title="Terms of service" onClick={() => {}}/>
        <MSRow title="Privacy policy" onClick={() => {}} last/>
      </MSCard>
    </>
  );
}

// Generic simple page — covers the lower-importance settings
function MSPageSimple({ rows }) {
  // rows is a flat array where {section: '...'} starts a new card and the rest are MSRow props
  const cards = [];
  let current = { label: null, rows: [] };
  rows.forEach(r => {
    if (r.section) {
      if (current.rows.length) cards.push(current);
      current = { label: r.section, rows: [] };
    } else {
      current.rows.push(r);
    }
  });
  if (current.rows.length) cards.push(current);
  return (
    <>
      {cards.map((c, i) => (
        <MSCard key={i} label={c.label}>
          {c.rows.map((r, j) => <MSRow key={j} {...r} last={j === c.rows.length - 1}/>)}
        </MSCard>
      ))}
    </>
  );
}

// ─── Page registry ─────────────────────────────────────────
const M_SETTINGS_PAGES = {
  identity:   () => <MSPageIdentity/>,
  privacy:    () => <MSPagePrivacy/>,
  private:    () => <MSPagePrivate/>,
  appearance: () => <MSPageAppearance/>,
  mesh:       () => <MSPageMesh/>,
  chat:       () => <MSPageChat/>,
  tabgroups:  () => <MSPageTabGroups/>,
  about:      () => <MSPageAbout/>,
  autofill:   () => <MSPageSimple rows={[
    { section: 'Passwords' },
    { title: 'Saved passwords', subtitle: '128 saved · last sync 4m', onClick: () => {} },
    { title: 'Offer to save passwords', right: <MSToggle on/> },
    { title: 'Auto sign-in', right: <MSToggle on/> },
    { title: 'Password checkup', subtitle: '3 compromised · 8 weak · 12 reused', right: <MSChip color="#F87171">REVIEW</MSChip>, onClick: () => {} },
    { section: 'Addresses' },
    { title: 'Saved addresses', subtitle: '2 saved', onClick: () => {} },
    { title: 'Save and fill addresses', right: <MSToggle on/> },
    { section: 'Payment methods' },
    { title: 'Saved cards', subtitle: '3 cards', onClick: () => {} },
    { title: 'Save and fill cards', right: <MSToggle on/> },
  ]}/>,
  search:     () => <MSPageSimple rows={[
    { section: 'Default engine' },
    { title: 'Search engine', right: <MSSelect value="ajna" options={[{value:'ajna',label:'Ajna'},{value:'google',label:'Google'},{value:'duckduckgo',label:'DuckDuckGo'},{value:'kagi',label:'Kagi'},{value:'brave',label:'Brave'}]}/> },
    { title: 'Show suggestions', right: <MSToggle on/> },
    { title: 'Show trending', right: <MSToggle/> },
    { section: 'Shortcuts' },
    { title: 'Site search shortcuts', subtitle: '@gh, @wiki, @lin to scope', onClick: () => {} },
  ]}/>,
  startup:    () => <MSPageSimple rows={[
    { title: 'Open New Tab page', right: <MSToggle/> },
    { title: 'Continue where you left off', subtitle: 'Restores tabs from last session', right: <MSToggle on/> },
    { title: 'Open a specific page…', onClick: () => {} },
  ]}/>,
  default:    () => <MSPageSimple rows={[
    { title: 'Make Ajna default', subtitle: 'Links from other apps open here', right: <MSChip>DEFAULT</MSChip> },
  ]}/>,
  perf:       () => <MSPageSimple rows={[
    { section: 'Memory' },
    { title: 'Memory saver', subtitle: 'Freezes inactive tabs', right: <MSToggle on/> },
    { title: 'Show memory on tab cards', right: <MSToggle/> },
    { section: 'Energy' },
    { title: 'Energy saver', right: <MSSelect value="auto" options={[{value:'auto',label:'When <20%'},{value:'always',label:'Always'},{value:'never',label:'Never'}]}/> },
    { section: 'Prefetch' },
    { title: 'Preload pages', subtitle: 'Faster browsing · uses cookies', right: <MSToggle on/> },
  ]}/>,
  downloads:  () => <MSPageSimple rows={[
    { title: 'Location', subtitle: 'iCloud Drive · Ajna / Downloads', onClick: () => {} },
    { title: 'Ask before downloading', right: <MSToggle/> },
    { title: 'Show when done', right: <MSToggle on/> },
  ]}/>,
  languages:  () => <MSPageSimple rows={[
    { title: 'English (US)', subtitle: 'Primary', right: <MSChip>PRIMARY</MSChip> },
    { title: 'हिन्दी (हिंदी)' },
    { title: 'Deutsch' },
    { title: 'Add languages…', onClick: () => {} },
    { section: 'Translation' },
    { title: 'Offer to translate', right: <MSToggle on/> },
    { title: 'Translate using', right: <MSSelect value="ajna" options={[{value:'ajna',label:'On-device'},{value:'google',label:'Google'}]}/> },
  ]}/>,
  a11y:       () => <MSPageSimple rows={[
    { title: 'Always show hints', subtitle: 'Tooltips for icons and gestures', right: <MSToggle/> },
    { title: 'Larger text', right: <MSSelect value="100" options={[{value:'90',label:'90%'},{value:'100',label:'100%'},{value:'120',label:'120%'},{value:'150',label:'150%'}]}/> },
    { title: 'High contrast', right: <MSToggle/> },
    { title: 'Reduce motion', right: <MSToggle/> },
    { title: 'Underline links', right: <MSToggle/> },
    { title: 'Screen reader optimizations', right: <MSToggle on/> },
  ]}/>,
  system:     () => <MSPageSimple rows={[
    { title: 'Background activity when closed', right: <MSToggle/> },
    { title: 'Hardware acceleration', right: <MSToggle on/> },
    { title: 'Page prediction', right: <MSToggle on/> },
    { section: 'Network' },
    { title: 'Proxy', subtitle: 'Direct connection — no proxy', onClick: () => {} },
  ]}/>,
  reset:      () => <MSPageSimple rows={[
    { title: 'Restore defaults', subtitle: 'Startup, NTP, search, pinned tabs, cookies, extensions, theme.', onClick: () => {} },
    { title: 'Sign out and forget this device', danger: true, onClick: () => {} },
  ]}/>,
};

// ─── Header / breadcrumb (mobile) ──────────────────────────
function MSHeader({ subPage, onBack }) {
  const all = M_SETTINGS_NAV.flatMap(s => s.items);
  const meta = subPage ? all.find(i => i.id === subPage) : null;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 14px 12px',
      borderBottom: '1px solid ' + M_BORDER_SOFT,
      background: M_BG,
    }}>
      {subPage ? (
        <button onClick={onBack} aria-label="Back" style={{
          width: 32, height: 32, borderRadius: 8,
          background: 'var(--m-tint)', border: '1px solid ' + M_BORDER_SOFT,
          color: M_FG, display: 'grid', placeItems: 'center', cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6"/></svg>
        </button>
      ) : (
        <div style={{ width: 26, height: 26, borderRadius: 7, background: 'linear-gradient(135deg,#6EE7B7,#60A5FA)', display: 'grid', placeItems: 'center', color: '#0B0C0F', fontWeight: 700, fontSize: 14, fontFamily: 'Geist' }}>A</div>
      )}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 16, fontWeight: 600, fontFamily: 'Geist', letterSpacing: '-0.02em', color: meta?.color === '#C4B5FD' ? '#C4B5FD' : M_FG }}>
          {meta ? meta.label : 'Settings'}
        </div>
        {meta && meta.sub && <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{meta.sub}</div>}
      </div>
    </div>
  );
}

// ─── Main Settings screen ──────────────────────────────────
function MScreenSettings() {
  const [subPage, setSubPage] = React.useState(null);
  const [query, setQuery] = React.useState('');

  const flat = M_SETTINGS_NAV.flatMap(s => s.items.map(i => ({ ...i, section: s.section })));
  const filtered = query.trim() ? flat.filter(i => i.label.toLowerCase().includes(query.toLowerCase().trim())) : null;

  // Sub-page view
  if (subPage) {
    const Page = M_SETTINGS_PAGES[subPage];
    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: M_BG, color: M_FG, overflow: 'hidden' }}>
        <MSHeader subPage={subPage} onBack={() => setSubPage(null)}/>
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px 100px' }}>
          {Page ? <Page/> : <div style={{ padding: 40, textAlign: 'center', color: M_FG_DIM, fontSize: 13 }}>Coming soon</div>}
        </div>
      </div>
    );
  }

  // Top-level list
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: M_BG, color: M_FG, overflow: 'hidden' }}>
      <MSHeader/>

      <div style={{ padding: '12px 14px 4px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '9px 12px',
          background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 10,
        }}>
          <span style={{ color: M_FG_DIM }}>{MIc.search({ s: 14 })}</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.5, fontFamily: 'inherit', minWidth: 0 }}
          />
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '4px 14px 100px' }}>
        {filtered ? (
          <MSCard label={filtered.length ? 'Results' : null}>
            {filtered.length === 0
              ? <div style={{ padding: '32px 18px', textAlign: 'center', color: M_FG_DIM, fontSize: 12 }}>No matches</div>
              : filtered.map((it, i) => (
                <MSRow key={it.id}
                  icon={it.icon} iconColor={it.color}
                  title={it.label} subtitle={it.sub}
                  onClick={() => { setSubPage(it.id); setQuery(''); }}
                  last={i === filtered.length - 1}
                />
              ))
            }
          </MSCard>
        ) : (
          M_SETTINGS_NAV.map((sec, i) => (
            <MSCard key={i} label={sec.section}>
              {sec.items.map((it, j) => (
                <MSRow key={it.id}
                  icon={it.icon} iconColor={it.color}
                  title={it.label} subtitle={it.sub}
                  right={it.badge ? <MSChip>{it.badge}</MSChip> : undefined}
                  onClick={() => setSubPage(it.id)}
                  last={j === sec.items.length - 1}
                />
              ))}
            </MSCard>
          ))
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MScreenSettings, M_SETTINGS_NAV });
