// Mobile Library v2 — Ajna-native designs for the menu's library section.
// Replaces MScreenLibrary. Each screen has identity-aware chrome (peer/device
// source chips, sync state, verified hashes) instead of a generic Chromium
// list. Routed by setScreen() from mobile-variants.jsx.

// ─── Shared chrome ──────────────────────────────────────────────
function MLHeader({ icon, color, title, sub, badge, tools }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 14 }}>
      <div style={{
        width: 36, height: 36, borderRadius: 9, flexShrink: 0,
        background: color ? color + '18' : M_TINT,
        border: '1px solid ' + (color ? color + '38' : M_BORDER_SOFT),
        color: color || M_FG, display: 'grid', placeItems: 'center',
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 19, fontWeight: 700, fontFamily: 'Geist', letterSpacing: '-0.025em', color: M_FG }}>{title}</div>
          {badge}
        </div>
        {sub && <div style={{ fontSize: 11, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', marginTop: 3, lineHeight: 1.5, letterSpacing: '0.01em' }}>{sub}</div>}
      </div>
      {tools}
    </div>
  );
}

function MLSearch({ value, onChange, placeholder, shortcut = '⌘F' }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '9px 12px', marginBottom: 12,
      background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 10,
    }}>
      <span style={{ color: M_FG_DIM }}>{MIc.search({ s: 14 })}</span>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: M_FG, fontSize: 13, fontFamily: 'inherit', minWidth: 0 }}/>
      {value
        ? <button onClick={() => onChange('')} style={{ background: 'transparent', border: 0, color: M_FG_DIM, cursor: 'pointer', padding: 0, fontSize: 11 }}>Clear</button>
        : <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>{shortcut}</span>}
    </div>
  );
}

function MLChip({ active, onClick, children, color }) {
  return (
    <button onClick={onClick} style={{
      flexShrink: 0, padding: '6px 11px', borderRadius: 999,
      background: active ? (color || M_FG) : 'transparent',
      border: '1px solid ' + (active ? (color || M_FG) : M_BORDER_SOFT),
      color: active ? '#0B0C0F' : M_FG_MUTED,
      fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
      whiteSpace: 'nowrap', letterSpacing: '0.01em',
    }}>{children}</button>
  );
}

function MLCard({ children }) {
  return (
    <div style={{ background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden' }}>
      {children}
    </div>
  );
}

function MLPage({ children }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', padding: '22px 14px 100px', boxSizing: 'border-box', color: M_FG, background: M_BG }}>
      {children}
    </div>
  );
}

// ─── History ───────────────────────────────────────────────────
function MScreenHistory({ onOpen }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all'); // 'all', or a device id
  const ql = q.toLowerCase();

  const matches = (it) => {
    if (filter !== 'all' && it.device !== filter) return false;
    if (!ql) return true;
    return it.title.toLowerCase().includes(ql) || it.url.toLowerCase().includes(ql);
  };
  const filtered = A_HISTORY.filter(matches);
  const grouped = filtered.reduce((acc, it) => {
    (acc[it.day] = acc[it.day] || []).push(it); return acc;
  }, {});

  const deviceChips = [
    { id: 'all',       label: 'All',      count: A_HISTORY.length },
    { id: 'thisIphone',label: 'iPhone',   color: '#C4B5FD', count: A_HISTORY.filter(h => h.device === 'thisIphone').length },
    { id: 'ipad',      label: 'iPad',     color: '#93C5FD', count: A_HISTORY.filter(h => h.device === 'ipad').length },
    { id: 'mac',       label: 'Mac',      color: '#93C5FD', count: A_HISTORY.filter(h => h.device === 'mac').length },
  ];

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 9"/><path d="M3 3v6h6"/><path d="M12 7v5l3 2"/></svg>}
        color={M_ACCENT_B}
        title="History"
        sub="ajna://history · synced across devices"
      />

      {/* Cross-device activity band — the thing Chrome doesn't have */}
      <div style={{
        padding: '12px 14px', marginBottom: 14,
        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: 12,
      }}>
        <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', marginBottom: 8 }}>Today · across devices</div>
        <div style={{ display: 'flex', gap: 14, alignItems: 'baseline' }}>
          <div>
            <div style={{ fontSize: 26, fontWeight: 700, fontFamily: 'Geist', letterSpacing: '-0.03em' }}>{A_HISTORY.filter(h => h.day === 'Today').length}</div>
            <div style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: -2 }}>sites</div>
          </div>
          <div style={{ flex: 1, display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
            {A_HISTORY_STATS.map(s => (
              <div key={s.device} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: M_FG_MUTED }}>
                <AConnChip device={s.device}/>
                <span style={{ fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>{s.count}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <MLSearch value={q} onChange={setQ} placeholder="Search history"/>

      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginBottom: 16, paddingBottom: 2 }}>
        {deviceChips.map(c => (
          <MLChip key={c.id} active={filter === c.id} onClick={() => setFilter(c.id)}>
            {c.label} <span style={{ opacity: 0.6, marginLeft: 4, fontFamily: 'JetBrains Mono, monospace' }}>{c.count}</span>
          </MLChip>
        ))}
      </div>

      {Object.keys(grouped).length === 0 && (
        <div style={{ padding: '48px 20px', textAlign: 'center', color: M_FG_DIM, fontSize: 12.5 }}>
          No history matches.
        </div>
      )}

      {Object.entries(grouped).map(([day, items]) => (
        <div key={day} style={{ marginBottom: 18 }}>
          <div style={{
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
            padding: '0 4px 8px',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace' }}>{day}</div>
            <div style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{items.length} {items.length === 1 ? 'visit' : 'visits'}</div>
          </div>
          <MLCard>
            {items.map((it, i) => (
              <div key={it.title + i} onClick={() => onOpen && onOpen(it)} style={{
                display: 'flex', alignItems: 'center', gap: 11,
                padding: '11px 12px',
                borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT,
                cursor: 'pointer',
              }}>
                <div style={{ fontSize: 9.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', width: 38, flexShrink: 0, letterSpacing: '0.02em' }}>{it.ts}</div>
                <MTile size={22} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={5}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{it.title}</div>
                  <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.url}</div>
                </div>
                <AConnChip device={it.device}/>
              </div>
            ))}
          </MLCard>
        </div>
      ))}
    </MLPage>
  );
}

// ─── Bookmarks ─────────────────────────────────────────────────
function MScreenBookmarks({ onOpen }) {
  const [q, setQ] = React.useState('');
  const [folder, setFolder] = React.useState('All');
  const ql = q.toLowerCase();
  const filtered = A_BOOKMARKS.filter(it => {
    if (folder !== 'All' && it.folder !== folder) return false;
    if (!ql) return true;
    return it.title.toLowerCase().includes(ql) || it.url.toLowerCase().includes(ql);
  });
  const recent = [...A_BOOKMARKS].sort((a, b) => {
    const score = s => /day/.test(s.saved) ? 1 : /week/.test(s.saved) ? 2 : 3;
    return score(a) - score(b);
  }).slice(0, 3);

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M19 21V5a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v16l7-4z"/></svg>}
        color="#FBBF24"
        title="Bookmarks"
        sub={A_BOOKMARKS.length + ' saved · ' + A_BOOKMARKS.filter(b => b.shared).length + ' shared with mesh'}
      />

      <MLSearch value={q} onChange={setQ} placeholder="Search bookmarks"/>

      {/* Folder pills */}
      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginBottom: 16, paddingBottom: 2 }}>
        <MLChip active={folder === 'All'} onClick={() => setFolder('All')}>All <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_BOOKMARKS.length}</span></MLChip>
        {A_BOOKMARK_FOLDERS.map(f => (
          <MLChip key={f.name} active={folder === f.name} onClick={() => setFolder(f.name)} color={f.color}>
            <span style={{ width: 7, height: 7, borderRadius: 2, background: f.color, display: 'inline-block', marginRight: 6, verticalAlign: 'middle' }}/>
            {f.name} <span style={{ opacity: 0.6, marginLeft: 4 }}>{f.count}</span>
          </MLChip>
        ))}
      </div>

      {/* Recently added when no search */}
      {!q && folder === 'All' && (
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px' }}>Recently added</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {recent.map((it, i) => (
              <div key={i} onClick={() => onOpen && onOpen(it)} style={{
                padding: 10, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
                borderRadius: 10, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 7, minHeight: 78,
              }}>
                <MTile size={22} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={5}/>
                <div style={{ fontSize: 12, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                <div style={{ fontSize: 9.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 'auto' }}>{it.saved}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px', display: 'flex', justifyContent: 'space-between' }}>
        <span>{folder === 'All' ? 'All bookmarks' : folder}</span>
        <span>{filtered.length}</span>
      </div>

      <MLCard>
        {filtered.length === 0 && <div style={{ padding: '40px 20px', textAlign: 'center', color: M_FG_DIM, fontSize: 12.5 }}>No matches</div>}
        {filtered.map((it, i) => {
          const folderMeta = A_BOOKMARK_FOLDERS.find(f => f.name === it.folder);
          return (
            <div key={it.title + i} onClick={() => onOpen && onOpen(it)} style={{
              display: 'flex', alignItems: 'center', gap: 11,
              padding: '11px 12px',
              borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT,
              cursor: 'pointer',
            }}>
              <MTile size={24} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={6}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{it.title}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
                  <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1, minWidth: 0 }}>{it.url}</div>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
                {it.shared && (
                  <span title="Shared with mesh" style={{ color: '#A78BFA' }}>
                    <svg width="12" height="12" 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>
                  </span>
                )}
                {folderMeta && <span style={{ width: 7, height: 7, borderRadius: 2, background: folderMeta.color }}/>}
              </div>
            </div>
          );
        })}
      </MLCard>
    </MLPage>
  );
}

// ─── Downloads ─────────────────────────────────────────────────
function MScreenDownloads({ onOpen }) {
  const totalBytes = A_DOWNLOADS.reduce((a, d) => a + d.bytes, 0);
  const fmtBytes = (n) => n >= 1e9 ? (n/1e9).toFixed(2) + ' GB'
                     : n >= 1e6 ? (n/1e6).toFixed(1) + ' MB'
                     : n >= 1e3 ? (n/1e3).toFixed(0) + ' KB'
                     : n + ' B';
  const active = A_DOWNLOADS.find(d => d.status === 'active');
  const done = A_DOWNLOADS.filter(d => d.status === 'done');

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v12M6 11l6 6 6-6M5 21h14"/></svg>}
        color="#10B981"
        title="Downloads"
        sub={A_DOWNLOADS.length + ' files · ' + fmtBytes(totalBytes) + ' on this device'}
      />

      {/* Storage band */}
      <div style={{
        padding: '12px 14px', marginBottom: 14,
        background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
          <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace' }}>Saved to</div>
          <div style={{ fontSize: 10.5, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace' }}>iCloud Drive / Ajna</div>
        </div>
        <div style={{ height: 6, background: 'var(--m-tint)', borderRadius: 3, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: '34%', background: 'linear-gradient(90deg,#6EE7B7,#60A5FA)', borderRadius: 3 }}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6 }}>
          <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{fmtBytes(totalBytes)} used</span>
          <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>50 GB total</span>
        </div>
      </div>

      {active && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px' }}>In progress</div>
          <MLCard>
            <div style={{ padding: '12px 14px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 8 }}>
                <MTile size={28} bg={active.bg} color="#fff" label={active.ext} radius={6}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{active.name}</div>
                  <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{fmtBytes(active.bytes)} / {fmtBytes(active.total)} · {active.speed}</div>
                </div>
                <button style={{
                  width: 28, height: 28, borderRadius: 6,
                  background: 'rgba(239,68,68,0.10)', border: '1px solid rgba(239,68,68,0.22)',
                  color: '#F87171', display: 'grid', placeItems: 'center', cursor: 'pointer',
                }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="4" width="16" height="16" rx="2"/></svg>
                </button>
              </div>
              <div style={{ height: 4, background: 'var(--m-tint)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: (active.bytes / active.total * 100).toFixed(0) + '%', background: 'linear-gradient(90deg,#10B981,#6EE7B7)', borderRadius: 2, transition: 'width 200ms' }}/>
              </div>
            </div>
          </MLCard>
        </div>
      )}

      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px' }}>Recent</div>
      <MLCard>
        {done.map((it, i) => (
          <div key={it.name + i} onClick={() => onOpen && onOpen(it)} style={{
            display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <MTile size={28} bg={it.bg} color="#fff" label={it.ext} radius={6}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.name}</div>
              <div style={{ display: 'flex', gap: 6, marginTop: 2, alignItems: 'center', flexWrap: 'wrap' }}>
                <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{fmtBytes(it.bytes)} · {it.time}</span>
                {it.verified && <span title="Hash verified" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 9, color: '#6EE7B7', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>
                  <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                  VERIFIED
                </span>}
                {it.encrypted && <span style={{ fontSize: 9, color: '#FBBF24', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                  <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.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>
                  ENCRYPTED
                </span>}
              </div>
            </div>
            <button onClick={(e) => e.stopPropagation()} aria-label="More" style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--m-tint)', border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED, display: 'grid', placeItems: 'center', cursor: 'pointer' }}>{MIc.more({ s: 12 })}</button>
          </div>
        ))}
      </MLCard>
    </MLPage>
  );
}

// ─── Recently closed ───────────────────────────────────────────
function MScreenRecentlyClosed({ onOpen }) {
  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7h13a5 5 0 0 1 0 10h-2"/><path d="m7 11-4-4 4-4"/></svg>}
        color="#22D3EE"
        title="Recently closed"
        sub={A_RECENTLY_CLOSED.reduce((a, s) => a + s.tabs.length, 0) + ' tabs · ' + A_RECENTLY_CLOSED.length + ' sessions'}
      />

      {A_RECENTLY_CLOSED.map((s, si) => (
        <div key={si} style={{ marginBottom: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px 8px' }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{s.session}</div>
              <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{s.when}</div>
            </div>
            <button style={{
              padding: '5px 9px', borderRadius: 7,
              background: 'rgba(96,165,250,0.10)', border: '1px solid rgba(96,165,250,0.28)',
              color: '#93C5FD', fontSize: 10, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
            }}>Reopen all</button>
          </div>
          <MLCard>
            {s.tabs.map((it, i) => (
              <div key={it.title + i} onClick={() => onOpen && onOpen(it)} style={{
                display: 'flex', alignItems: 'center', gap: 11, padding: '10px 12px',
                borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
              }}>
                <MTile size={22} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={5}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                  <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.url}</div>
                </div>
                <span style={{ color: M_FG_DIM }}>↺</span>
              </div>
            ))}
          </MLCard>
        </div>
      ))}
    </MLPage>
  );
}

// ─── Passwords ─────────────────────────────────────────────────
function MScreenPasswords() {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const ql = q.toLowerCase();
  const matches = (p) => {
    if (filter !== 'all' && p.flag !== filter) return false;
    if (!ql) return true;
    return p.site.toLowerCase().includes(ql) || p.user.toLowerCase().includes(ql);
  };
  const filtered = A_PASSWORDS.filter(matches);
  const flagColor = { compromised: '#F87171', weak: '#FBBF24', reused: '#A78BFA' };
  const flagLabel = { compromised: 'COMPROMISED', weak: 'WEAK', reused: 'REUSED' };

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="10" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>}
        color="#F472B6"
        title="Passwords"
        sub={A_PASSWORDS_HEALTH.total + ' saved · encrypted with device key'}
      />

      {/* Health banner */}
      <div style={{
        padding: '12px 14px', marginBottom: 14, borderRadius: 12,
        background: 'linear-gradient(135deg, rgba(248,113,113,0.06), rgba(251,191,36,0.06)), ' + M_SURFACE,
        border: '1px solid rgba(248,113,113,0.18)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <span style={{ color: '#F87171' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 9v4M12 17h.01"/><path d="M3 12a9 9 0 1 0 18 0 9 9 0 0 0-18 0z"/></svg>
          </span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: M_FG, fontFamily: 'Geist' }}>Password checkup</div>
            <div style={{ fontSize: 10.5, color: M_FG_MUTED, marginTop: 1 }}>Review weak and exposed credentials</div>
          </div>
          <button style={{ padding: '5px 9px', borderRadius: 7, background: '#F87171', border: 0, color: '#0B0C0F', fontSize: 10, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer' }}>REVIEW</button>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {[
            { k: 'compromised', n: A_PASSWORDS_HEALTH.compromised, c: '#F87171' },
            { k: 'weak',        n: A_PASSWORDS_HEALTH.weak,        c: '#FBBF24' },
            { k: 'reused',      n: A_PASSWORDS_HEALTH.reused,      c: '#A78BFA' },
          ].map(s => (
            <div key={s.k} style={{ flex: 1, padding: '6px 10px', background: 'rgba(0,0,0,0.30)', borderRadius: 8 }}>
              <div style={{ fontSize: 17, fontWeight: 700, color: s.c, fontFamily: 'Geist', letterSpacing: '-0.02em' }}>{s.n}</div>
              <div style={{ fontSize: 9, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{s.k}</div>
            </div>
          ))}
        </div>
      </div>

      <MLSearch value={q} onChange={setQ} placeholder="Search passwords"/>

      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginBottom: 16, paddingBottom: 2 }}>
        <MLChip active={filter === 'all'} onClick={() => setFilter('all')}>All <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_PASSWORDS.length}</span></MLChip>
        {['compromised', 'weak', 'reused'].map(k => (
          <MLChip key={k} active={filter === k} onClick={() => setFilter(k)} color={flagColor[k]}>
            {k.charAt(0).toUpperCase() + k.slice(1)} <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_PASSWORDS.filter(p => p.flag === k).length}</span>
          </MLChip>
        ))}
      </div>

      <MLCard>
        {filtered.length === 0 && <div style={{ padding: 30, textAlign: 'center', color: M_FG_DIM, fontSize: 12 }}>No matches</div>}
        {filtered.map((p, i) => (
          <div key={p.site} style={{
            display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <MTile size={24} bg={p.bg} color={p.c || '#fff'} label={p.fav} radius={6}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{p.domain}</div>
              <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.user} · {p.last}</div>
            </div>
            {p.flag && (
              <span style={{ fontSize: 9, fontWeight: 700, padding: '2px 7px', borderRadius: 999, background: flagColor[p.flag] + '22', color: flagColor[p.flag], fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{flagLabel[p.flag]}</span>
            )}
          </div>
        ))}
      </MLCard>
    </MLPage>
  );
}

// ─── Reading list ──────────────────────────────────────────────
function MScreenReadingList({ onOpen }) {
  const [filter, setFilter] = React.useState('unread');
  const filtered = A_READING_LIST.filter(r => filter === 'all' || (filter === 'unread' ? !r.read : r.read));

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3h12a3 3 0 0 1 3 3v15"/><path d="M3 21V3"/><path d="M9 8h6M9 12h6"/></svg>}
        color="#10B981"
        title="Reading list"
        sub={A_READING_LIST.filter(r => !r.read).length + ' unread · ' + A_READING_LIST.reduce((a, r) => a + r.mins, 0) + ' min total'}
      />

      <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
        <MLChip active={filter === 'unread'} onClick={() => setFilter('unread')}>Unread <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_READING_LIST.filter(r => !r.read).length}</span></MLChip>
        <MLChip active={filter === 'all'} onClick={() => setFilter('all')}>All <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_READING_LIST.length}</span></MLChip>
        <MLChip active={filter === 'read'} onClick={() => setFilter('read')}>Read <span style={{ opacity: 0.6, marginLeft: 4 }}>{A_READING_LIST.filter(r => r.read).length}</span></MLChip>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map((r, i) => (
          <div key={r.title + i} onClick={() => onOpen && onOpen(r)} style={{
            padding: 14, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12,
            cursor: 'pointer', opacity: r.read ? 0.6 : 1,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <MTile size={22} bg={r.bg} color={r.c || '#fff'} label={r.fav} radius={5}/>
              <div style={{ flex: 1, fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.url}</div>
              {!r.read && <span style={{ width: 7, height: 7, borderRadius: 3.5, background: M_ACCENT, boxShadow: '0 0 7px ' + M_ACCENT }}/>}
            </div>
            <div style={{ fontSize: 14.5, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.02em', lineHeight: 1.3, marginBottom: 4 }}>{r.title}</div>
            <div style={{ fontSize: 12, color: M_FG_MUTED, lineHeight: 1.45, marginBottom: 9 }}>{r.preview}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>
              <span>{r.mins} min</span>
              <span>·</span>
              <span>{r.saved}</span>
              <span style={{ marginLeft: 'auto' }}><AConnChip device={r.device}/></span>
            </div>
          </div>
        ))}
      </div>
    </MLPage>
  );
}

// ─── Site permissions ──────────────────────────────────────────
function MScreenSitePermissions() {
  const permIcon = (id) => {
    const Wrap = (d) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
    const map = {
      pin:    Wrap(<><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"/></>),
      camera: Wrap(<><path d="M3 7h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="4"/></>),
      mic:    Wrap(<><rect x="9" y="3" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></>),
      bell:   Wrap(<><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"/></>),
      clip:   Wrap(<><rect x="8" y="2" width="8" height="4" rx="1"/><rect x="5" y="6" width="14" height="16" rx="2"/></>),
      play:   Wrap(<polygon points="6 4 20 12 6 20 6 4"/>),
      cookie: Wrap(<><path d="M12 22a10 10 0 1 1 0-20c0 2 2 4 4 4s2 2 2 4 2 4 4 4a10 10 0 0 1-10 8z"/><circle cx="9" cy="9" r="0.8"/><circle cx="14" cy="13" r="0.8"/><circle cx="9" cy="15" r="0.8"/></>),
      disk:   Wrap(<><ellipse cx="12" cy="6" rx="9" ry="3"/><path d="M3 6v6c0 1.7 4 3 9 3s9-1.3 9-3V6M3 12v6c0 1.7 4 3 9 3s9-1.3 9-3v-6"/></>),
    };
    return map[id] || map.pin;
  };

  return (
    <MLPage>
      <MLHeader
        icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" 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>}
        color="#6EE7B7"
        title="Site permissions"
        sub="Per-site grants · revoked instantly"
      />

      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px' }}>By permission</div>
      <MLCard>
        {A_PERMS_SUMMARY.map((p, i) => (
          <div key={p.id} style={{
            display: 'flex', alignItems: 'center', gap: 11, padding: '11px 12px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <div style={{ width: 28, height: 28, borderRadius: 7, background: p.color + '22', color: p.color, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{permIcon(p.icon)}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{p.label}</div>
              <div style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>
                <span style={{ color: '#6EE7B7' }}>{p.allowed} allow</span>
                <span style={{ margin: '0 6px', color: M_FG_DIM }}>·</span>
                <span style={{ color: '#F87171' }}>{p.blocked} block</span>
              </div>
            </div>
            <span style={{ color: M_FG_DIM }}>›</span>
          </div>
        ))}
      </MLCard>

      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '14px 4px 8px' }}>Recent sites</div>
      <MLCard>
        {A_PERMS_SITES.slice(0, 5).map((s, i) => (
          <div key={s.domain} style={{
            padding: '11px 12px', borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <div style={{ fontSize: 12.5, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{s.domain}</div>
            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginTop: 5 }}>
              {Object.entries(s.perms).map(([k, v]) => {
                const meta = A_PERMS_SUMMARY.find(p => p.id === k) || { label: k, color: M_FG_MUTED };
                return (
                  <span key={k} style={{
                    fontSize: 9.5, padding: '2px 7px', borderRadius: 999,
                    background: v === 'allow' ? 'rgba(110,231,183,0.10)' : 'rgba(248,113,113,0.10)',
                    color: v === 'allow' ? '#6EE7B7' : '#F87171',
                    fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.03em',
                  }}>{meta.label.toLowerCase()} · {v}</span>
                );
              })}
            </div>
          </div>
        ))}
      </MLCard>
    </MLPage>
  );
}

Object.assign(window, {
  MScreenHistory, MScreenBookmarks, MScreenDownloads, MScreenRecentlyClosed,
  MScreenPasswords, MScreenReadingList, MScreenSitePermissions,
});
