// iPad Library v2 — Ajna-native designs matching the mobile library.
// Wider layout: optional left rail for bookmarks folders / history days /
// permission categories. Same data, same metadata, scaled up.

// ─── Shared iPad chrome ───────────────────────────────────────
function TLPage({ children, rail }) {
  return (
    <div style={{ height: '100%', display: 'flex', overflow: 'hidden', background: M_BG, color: M_FG }}>
      {rail}
      <div style={{ flex: 1, overflowY: 'auto', padding: '28px 32px 60px' }}>
        {children}
      </div>
    </div>
  );
}

function TLHeader({ icon, color, title, sub, tools }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 22 }}>
      <div style={{
        width: 44, height: 44, borderRadius: 11, 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={{ fontSize: 26, fontWeight: 700, fontFamily: 'Geist', letterSpacing: '-0.03em', color: M_FG }}>{title}</div>
        {sub && <div style={{ fontSize: 12, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>{sub}</div>}
      </div>
      {tools}
    </div>
  );
}

function TLSearch({ value, onChange, placeholder, shortcut = '⌘F' }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '9px 14px', marginBottom: 18,
      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' }}/>
      <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{shortcut}</span>
    </div>
  );
}

function TLRailButton({ active, onClick, dot, label, count, children }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', display: 'flex', alignItems: 'center', gap: 10,
      padding: '9px 10px', borderRadius: 8,
      background: active ? 'var(--m-tint)' : 'transparent',
      border: 0, color: active ? M_FG : M_FG_MUTED,
      fontFamily: 'inherit', fontSize: 13, fontWeight: 500, textAlign: 'left', cursor: 'pointer',
    }}>
      {dot && <span style={{ width: 8, height: 8, borderRadius: 2, background: dot, flexShrink: 0 }}/>}
      {children}
      <span style={{ flex: 1 }}>{label}</span>
      {count !== undefined && <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{count}</span>}
    </button>
  );
}

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

// ─── History (iPad) ────────────────────────────────────────────
function TScreenHistory({ landscape, onOpen }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const ql = q.toLowerCase();
  const matches = (it) => {
    if (filter !== 'all' && it.day !== filter && 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 days = ['Today', 'Yesterday', 'Earlier this week'];

  const rail = landscape ? (
    <div style={{ width: 220, flexShrink: 0, padding: '24px 12px', borderRight: '1px solid ' + M_BORDER_SOFT, overflowY: 'auto' }}>
      <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', padding: '0 6px 10px' }}>When</div>
      <TLRailButton active={filter === 'all'} onClick={() => setFilter('all')} label="All" count={A_HISTORY.length}/>
      {days.map(d => {
        const c = A_HISTORY.filter(h => h.day === d).length;
        if (!c) return null;
        return <TLRailButton key={d} active={filter === d} onClick={() => setFilter(d)} label={d} count={c}/>;
      })}
      <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', padding: '14px 6px 10px' }}>Device</div>
      {['thisIphone', 'ipad', 'mac'].map(id => {
        const c = A_HISTORY.filter(h => h.device === id).length;
        if (!c) return null;
        const d = A_DEVICES[id];
        return <TLRailButton key={id} active={filter === id} onClick={() => setFilter(id)} label={d.label} count={c} dot={d.color}/>;
      })}
    </div>
  ) : null;

  return (
    <TLPage rail={rail}>
      <TLHeader
        icon={<svg width="22" height="22" 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 E2E across devices"
        tools={
          <button style={{ padding: '8px 12px', borderRadius: 8, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, color: M_FG, fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>Clear…</button>
        }
      />

      {/* Activity band */}
      <div style={{
        padding: '16px 18px', marginBottom: 22, borderRadius: 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,
        display: 'flex', alignItems: 'center', gap: 24,
      }}>
        <div>
          <div style={{ fontSize: 10.5, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace' }}>Today</div>
          <div style={{ fontSize: 34, fontWeight: 700, fontFamily: 'Geist', letterSpacing: '-0.04em', lineHeight: 1, marginTop: 4 }}>{A_HISTORY.filter(h => h.day === 'Today').length}</div>
          <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>sites visited</div>
        </div>
        <div style={{ width: 1, alignSelf: 'stretch', background: M_BORDER_SOFT }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 10.5, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', marginBottom: 10 }}>Across devices</div>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            {A_HISTORY_STATS.map(s => (
              <div key={s.device} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <AConnChip device={s.device} size="lg"/>
                <span style={{ fontSize: 14, fontFamily: 'Geist', fontWeight: 600, color: M_FG, letterSpacing: '-0.02em' }}>{s.count}</span>
                <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>visits</span>
              </div>
            ))}
          </div>
        </div>
      </div>

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

      {Object.entries(grouped).map(([day, items]) => (
        <div key={day} style={{ marginBottom: 26 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px 10px' }}>
            <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.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{items.length} visits</div>
          </div>
          <TLCard>
            {items.map((it, i) => (
              <div key={it.title + i} onClick={() => onOpen && onOpen(it)} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px',
                borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
              }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint-2)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
              >
                <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', width: 56, flexShrink: 0 }}>{it.ts}</div>
                <MTile size={26} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={6}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                  <div style={{ fontSize: 11, 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>
            ))}
          </TLCard>
        </div>
      ))}
    </TLPage>
  );
}

// ─── Bookmarks (iPad) ──────────────────────────────────────────
function TScreenBookmarks({ landscape, 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 rail = landscape ? (
    <div style={{ width: 240, flexShrink: 0, padding: '24px 12px', borderRight: '1px solid ' + M_BORDER_SOFT, overflowY: 'auto' }}>
      <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', padding: '0 6px 10px' }}>Folders</div>
      <TLRailButton active={folder === 'All'} onClick={() => setFolder('All')} label="All bookmarks" count={A_BOOKMARKS.length}/>
      <TLRailButton active={folder === '__shared'} onClick={() => setFolder('All')} label="Shared with mesh" count={A_BOOKMARKS.filter(b => b.shared).length}/>
      <div style={{ height: 1, margin: '10px 8px', background: M_BORDER_SOFT }}/>
      {A_BOOKMARK_FOLDERS.map(f => (
        <TLRailButton key={f.name} active={folder === f.name} onClick={() => setFolder(f.name)} label={f.name} count={f.count} dot={f.color}/>
      ))}
      <button style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 8,
        padding: '9px 10px', borderRadius: 8, marginTop: 6,
        background: 'transparent', border: '1px dashed ' + M_BORDER_SOFT, color: M_FG_DIM,
        fontFamily: 'inherit', fontSize: 12, cursor: 'pointer',
      }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>
        <span>New folder</span>
      </button>
    </div>
  ) : null;

  return (
    <TLPage rail={rail}>
      <TLHeader
        icon={<svg width="22" height="22" 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={folder === 'All' ? 'Bookmarks' : folder}
        sub={A_BOOKMARKS.length + ' saved · ' + A_BOOKMARKS.filter(b => b.shared).length + ' shared with mesh'}
        tools={
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={{ padding: '8px 12px', borderRadius: 8, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, color: M_FG, fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>Import…</button>
            <button style={{ padding: '8px 12px', borderRadius: 8, background: M_FG, border: 0, color: '#0B0C0F', fontSize: 12, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer' }}>Add bookmark</button>
          </div>
        }
      />

      <TLSearch value={q} onChange={setQ} placeholder={'Search ' + (folder === 'All' ? 'bookmarks' : folder)}/>

      <div style={{ display: 'grid', gridTemplateColumns: landscape ? 'repeat(2, 1fr)' : '1fr', gap: 10 }}>
        {filtered.map((it, i) => {
          const fm = 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: 12,
              padding: '12px 14px', background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
              borderRadius: 12, cursor: 'pointer',
            }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = 'rgba(96,165,250,0.4)'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = M_BORDER_SOFT}
            >
              <MTile size={32} bg={it.bg} color={it.c || '#fff'} label={it.fav} radius={7}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 2 }}>
                  <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1, minWidth: 0 }}>{it.url}</div>
                  <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }}>{it.saved}</span>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                {it.shared && (
                  <span title="Shared with mesh" style={{ color: '#A78BFA', display: 'grid', placeItems: 'center' }}>
                    <svg width="13" height="13" 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>
                )}
                {fm && <span title={fm.name} style={{ width: 8, height: 8, borderRadius: 2, background: fm.color }}/>}
              </div>
            </div>
          );
        })}
      </div>
    </TLPage>
  );
}

// ─── Downloads (iPad) ──────────────────────────────────────────
function TScreenDownloads({ landscape, onOpen }) {
  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 totalBytes = A_DOWNLOADS.reduce((a, d) => a + d.bytes, 0);
  const active = A_DOWNLOADS.find(d => d.status === 'active');
  const done = A_DOWNLOADS.filter(d => d.status === 'done');

  return (
    <TLPage>
      <TLHeader
        icon={<svg width="22" height="22" 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 · iCloud Drive / Ajna'}
        tools={<button style={{ padding: '8px 12px', borderRadius: 8, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, color: M_FG, fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>Open folder</button>}
      />

      {active && (
        <div style={{ marginBottom: 22 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 10px' }}>In progress</div>
          <TLCard>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10 }}>
                <MTile size={36} bg={active.bg} color="#fff" label={active.ext} radius={8}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{active.name}</div>
                  <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{fmtBytes(active.bytes)} / {fmtBytes(active.total)} · {active.speed}</div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button style={{ padding: '6px 10px', borderRadius: 6, background: 'var(--m-tint)', border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED, fontSize: 11, fontFamily: 'inherit', cursor: 'pointer' }}>Pause</button>
                  <button style={{ padding: '6px 10px', borderRadius: 6, background: 'rgba(239,68,68,0.10)', border: '1px solid rgba(239,68,68,0.25)', color: '#F87171', fontSize: 11, fontFamily: 'inherit', cursor: 'pointer' }}>Cancel</button>
                </div>
              </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 }}/>
              </div>
            </div>
          </TLCard>
        </div>
      )}

      <div style={{ fontSize: 11, fontWeight: 700, color: M_FG_DIM, letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 10px' }}>Recent</div>
      <TLCard>
        {done.map((it, i) => (
          <div key={it.name} onClick={() => onOpen && onOpen(it)} style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <MTile size={34} bg={it.bg} color="#fff" label={it.ext} radius={7}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{it.name}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 3, alignItems: 'center', flexWrap: 'wrap' }}>
                <span style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{fmtBytes(it.bytes)}</span>
                <span style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>· {it.time}</span>
                <span style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>· {it.source}</span>
                {it.verified && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 9.5, color: '#6EE7B7', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em', fontWeight: 600 }}>
                  <svg width="10" height="10" 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.5, color: '#FBBF24', fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em', fontWeight: 600 }}>ENCRYPTED</span>}
              </div>
              {it.hash && <div style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{it.hash}</div>}
            </div>
            <button onClick={(e) => e.stopPropagation()} style={{ padding: '7px 10px', borderRadius: 7, background: 'var(--m-tint)', border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED, fontSize: 11, fontFamily: 'inherit', cursor: 'pointer' }}>Show in folder</button>
          </div>
        ))}
      </TLCard>
    </TLPage>
  );
}

// ─── Recently closed (iPad) ────────────────────────────────────
function TScreenRecentlyClosed({ onOpen }) {
  return (
    <TLPage>
      <TLHeader
        icon={<svg width="22" height="22" 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 in ' + A_RECENTLY_CLOSED.length + ' sessions · cleared after 7 days'}
      />

      {A_RECENTLY_CLOSED.map((s, si) => (
        <div key={si} style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px 10px' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{s.session}</div>
              <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{s.when}</div>
            </div>
            <button style={{ padding: '6px 11px', borderRadius: 7, background: 'rgba(96,165,250,0.10)', border: '1px solid rgba(96,165,250,0.28)', color: '#93C5FD', fontSize: 11, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer' }}>Reopen all</button>
          </div>
          <TLCard>
            {s.tabs.map((it, i) => (
              <div key={it.title} onClick={() => onOpen && onOpen(it)} style={{
                display: 'flex', alignItems: 'center', gap: 14, padding: '11px 16px',
                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={5}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{it.title}</div>
                  <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{it.url}</div>
                </div>
                <span style={{ color: M_FG_DIM, fontSize: 16 }}>↺</span>
              </div>
            ))}
          </TLCard>
        </div>
      ))}
    </TLPage>
  );
}

// ─── Passwords (iPad) ──────────────────────────────────────────
function TScreenPasswords() {
  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' };

  return (
    <TLPage>
      <TLHeader
        icon={<svg width="22" height="22" 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 · synced E2E'}
        tools={
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={{ padding: '8px 12px', borderRadius: 8, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, color: M_FG, fontSize: 12, fontFamily: 'inherit', cursor: 'pointer' }}>Export…</button>
            <button style={{ padding: '8px 12px', borderRadius: 8, background: M_FG, border: 0, color: '#0B0C0F', fontSize: 12, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer' }}>Add password</button>
          </div>
        }
      />

      <div style={{
        padding: '16px 18px', marginBottom: 22, borderRadius: 14,
        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.20)',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <span style={{ color: '#F87171' }}>
          <svg width="24" height="24" 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: 14, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.02em' }}>Password checkup</div>
          <div style={{ fontSize: 11.5, color: M_FG_MUTED, marginTop: 2 }}>23 credentials need your attention</div>
        </div>
        <div style={{ display: 'flex', gap: 14 }}>
          {[
            { 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={{ textAlign: 'center' }}>
              <div style={{ fontSize: 22, fontWeight: 700, color: s.c, fontFamily: 'Geist', letterSpacing: '-0.03em', lineHeight: 1 }}>{s.n}</div>
              <div style={{ fontSize: 9.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 3, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>{s.k}</div>
            </div>
          ))}
        </div>
        <button style={{ padding: '8px 16px', borderRadius: 8, background: '#F87171', border: 0, color: '#0B0C0F', fontSize: 12, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer' }}>Review now</button>
      </div>

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

      <div style={{ display: 'flex', gap: 7, marginBottom: 16 }}>
        {[{ k: 'all', l: 'All' }, { k: 'compromised', l: 'Compromised' }, { k: 'weak', l: 'Weak' }, { k: 'reused', l: 'Reused' }].map(o => (
          <button key={o.k} onClick={() => setFilter(o.k)} style={{
            padding: '6px 12px', borderRadius: 999,
            background: filter === o.k ? (flagColor[o.k] || M_FG) : 'transparent',
            border: '1px solid ' + (filter === o.k ? (flagColor[o.k] || M_FG) : M_BORDER_SOFT),
            color: filter === o.k ? '#0B0C0F' : M_FG_MUTED,
            fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          }}>{o.l} <span style={{ opacity: 0.7, marginLeft: 4 }}>{o.k === 'all' ? A_PASSWORDS.length : A_PASSWORDS.filter(p => p.flag === o.k).length}</span></button>
        ))}
      </div>

      <TLCard>
        {filtered.map((p, i) => (
          <div key={p.site} style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <MTile size={32} bg={p.bg} color={p.c || '#fff'} label={p.fav} radius={7}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{p.domain}</div>
              <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{p.site}</div>
            </div>
            <div style={{ fontSize: 12, color: M_FG_MUTED, fontFamily: 'JetBrains Mono, monospace', minWidth: 200 }}>{p.user}</div>
            <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', width: 50 }}>{p.last}</div>
            {p.flag ? (
              <span style={{ fontSize: 9.5, fontWeight: 700, padding: '3px 9px', borderRadius: 999, background: flagColor[p.flag] + '22', color: flagColor[p.flag], fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{p.flag.toUpperCase()}</span>
            ) : <span style={{ width: 70 }}/>}
            <button style={{ width: 30, height: 30, borderRadius: 7, background: 'var(--m-tint)', border: '1px solid ' + M_BORDER_SOFT, color: M_FG_MUTED, display: 'grid', placeItems: 'center', cursor: 'pointer' }}>{MIc.more({ s: 14 })}</button>
          </div>
        ))}
      </TLCard>
    </TLPage>
  );
}

// ─── Reading list (iPad) ───────────────────────────────────────
function TScreenReadingList({ onOpen }) {
  const [filter, setFilter] = React.useState('unread');
  const filtered = A_READING_LIST.filter(r => filter === 'all' || (filter === 'unread' ? !r.read : r.read));
  return (
    <TLPage>
      <TLHeader
        icon={<svg width="22" height="22" 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 · synced across devices'}
      />

      <div style={{ display: 'flex', gap: 7, marginBottom: 18 }}>
        {[{ k: 'unread', l: 'Unread' }, { k: 'all', l: 'All' }, { k: 'read', l: 'Read' }].map(o => (
          <button key={o.k} onClick={() => setFilter(o.k)} style={{
            padding: '6px 13px', borderRadius: 999,
            background: filter === o.k ? M_FG : 'transparent',
            border: '1px solid ' + (filter === o.k ? M_FG : M_BORDER_SOFT),
            color: filter === o.k ? '#0B0C0F' : M_FG_MUTED,
            fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          }}>{o.l}</button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
        {filtered.map((r, i) => (
          <div key={r.title + i} onClick={() => onOpen && onOpen(r)} style={{
            padding: 18, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
            borderRadius: 14, cursor: 'pointer', opacity: r.read ? 0.62 : 1,
            display: 'flex', flexDirection: 'column', gap: 10,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <MTile size={26} bg={r.bg} color={r.c || '#fff'} label={r.fav} radius={6}/>
              <div style={{ flex: 1, fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.url}</div>
              {!r.read && <span style={{ width: 8, height: 8, borderRadius: 4, background: M_ACCENT, boxShadow: '0 0 8px ' + M_ACCENT }}/>}
            </div>
            <div style={{ fontSize: 16.5, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.02em', lineHeight: 1.3 }}>{r.title}</div>
            <div style={{ fontSize: 12.5, color: M_FG_MUTED, lineHeight: 1.5 }}>{r.preview}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 'auto', paddingTop: 6 }}>
              <span>{r.mins} min</span>
              <span>·</span>
              <span>{r.saved}</span>
              <span style={{ marginLeft: 'auto' }}><AConnChip device={r.device}/></span>
            </div>
          </div>
        ))}
      </div>
    </TLPage>
  );
}

// ─── Site permissions (iPad) ───────────────────────────────────
function TScreenSitePermissions() {
  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"/></>),
      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 (
    <TLPage>
      <TLHeader
        icon={<svg width="22" height="22" 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 · audit log on mediator"
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 22 }}>
        {A_PERMS_SUMMARY.map(p => (
          <div key={p.id} style={{
            padding: 14, background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
            borderRadius: 12, cursor: 'pointer',
          }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: p.color + '22', color: p.color, display: 'grid', placeItems: 'center', marginBottom: 10 }}>{permIcon(p.icon)}</div>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{p.label}</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 5, fontSize: 10.5, fontFamily: 'JetBrains Mono, monospace' }}>
              <span style={{ color: '#6EE7B7' }}>{p.allowed} allow</span>
              <span style={{ color: '#F87171' }}>{p.blocked} block</span>
            </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 10px' }}>Per-site grants</div>
      <TLCard>
        {A_PERMS_SITES.map((s, i) => (
          <div key={s.domain} style={{
            display: 'flex', alignItems: 'center', gap: 14, padding: '13px 16px',
            borderTop: i === 0 ? 0 : '1px solid ' + M_BORDER_SOFT, cursor: 'pointer',
          }}>
            <div style={{ fontSize: 13.5, fontWeight: 500, color: M_FG, fontFamily: 'Geist', letterSpacing: '-0.01em', minWidth: 220 }}>{s.domain}</div>
            <div style={{ flex: 1, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {Object.entries(s.perms).map(([k, v]) => {
                const meta = A_PERMS_SUMMARY.find(p => p.id === k) || { label: k };
                return (
                  <span key={k} style={{
                    fontSize: 10, padding: '3px 8px', 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.04em',
                  }}>{meta.label.toLowerCase()} · {v}</span>
                );
              })}
            </div>
            <span style={{ color: M_FG_DIM }}>›</span>
          </div>
        ))}
      </TLCard>
    </TLPage>
  );
}

Object.assign(window, {
  TScreenHistory, TScreenBookmarks, TScreenDownloads, TScreenRecentlyClosed,
  TScreenPasswords, TScreenReadingList, TScreenSitePermissions,
});
