// Desktop library pages — History / Bookmarks / Downloads / Recently closed /
// Reading list / Passwords / Site permissions. Reuses shared A_* data and the
// desktop CSS-var palette so light/dark + accent all work automatically.
// Rendered as full content panes by the variant router in app.jsx.

// ── shared chrome ──────────────────────────────────────────────
function DLPage({ children }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', background: 'var(--sidebar-bg)', color: 'var(--fg)', fontFamily: 'Inter, sans-serif' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '32px clamp(20px,4vw,56px) 80px' }}>
        {children}
      </div>
    </div>
  );
}

function DLHeader({ icon, color, title, sub, tools }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 26 }}>
      <div style={{
        width: 46, height: 46, borderRadius: 12, flexShrink: 0,
        background: 'color-mix(in oklch, ' + color + ' 16%, transparent)',
        border: '1px solid color-mix(in oklch, ' + color + ' 34%, transparent)',
        color: color, display: 'grid', placeItems: 'center',
      }}>{icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 27, fontWeight: 700, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.03em' }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', fontFamily: 'JetBrains Mono, monospace', marginTop: 5 }}>{sub}</div>}
      </div>
      {tools}
    </div>
  );
}

function DLSearch({ value, onChange, placeholder }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', marginBottom: 18,
      background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 10,
    }}>
      <span style={{ color: 'var(--fg-dim)' }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg></span>
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        style={{ flex: 1, background: 'transparent', border: 0, outline: 0, color: 'var(--fg)', fontSize: 13, fontFamily: 'inherit' }}/>
      <span style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>⌘F</span>
    </div>
  );
}

function DLCard({ children }) {
  return <div style={{ background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 14, overflow: 'hidden' }}>{children}</div>;
}

function DLConnChip({ device }) {
  const d = typeof device === 'string' ? (A_DEVICES[device] || {}) : (device || {});
  const tone = d.conn === 'this' ? { c: '#C4B5FD' } : d.conn === 'ble' ? { c: '#67E8F9' } : d.conn === 'net' ? { c: '#93C5FD' } : d.conn === 'peer' ? { c: '#F9A8D4' } : { c: 'var(--fg-dim)' };
  if (!d.short) return null;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexShrink: 0, padding: '3px 9px', borderRadius: 999, background: 'color-mix(in oklch, ' + tone.c + ' 14%, transparent)', color: tone.c, fontSize: 10.5, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.04em', fontWeight: 600 }}>
      <span style={{ width: 4, height: 4, borderRadius: 2, background: tone.c }}/>{d.short}
    </span>
  );
}

const DLtile = (it, size = 28) => <Favicon domain={(it.url || '').split('/')[0]} size={size} radius={size <= 24 ? 6 : 8} label={it.fav} bg={it.bg}/>;
const dlFmt = (n) => n >= 1e9 ? (n/1e9).toFixed(2)+' GB' : n >= 1e6 ? (n/1e6).toFixed(1)+' MB' : n >= 1e3 ? (n/1e3).toFixed(0)+' KB' : n+' B';

// ── History ────────────────────────────────────────────────────
function DScreenHistory({ onClearData }) {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const ql = q.toLowerCase();
  const filtered = A_HISTORY.filter(it => (filter === 'all' || it.day === filter || it.device === filter) && (!ql || it.title.toLowerCase().includes(ql) || it.url.toLowerCase().includes(ql)));
  const grouped = filtered.reduce((a, it) => { (a[it.day] = a[it.day] || []).push(it); return a; }, {});
  return (
    <DLPage>
      <DLHeader color="var(--accent-b)"
        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>}
        title="History" sub="ajna://history · synced E2E across devices"
        tools={<button onClick={onClearData} style={dlBtn()}>Clear browsing data…</button>}/>

      <div style={{ display: 'flex', alignItems: 'center', gap: 24, padding: '16px 20px', marginBottom: 22, borderRadius: 14, background: 'var(--bg-elev)', border: '1px solid var(--border-soft)' }}>
        <div>
          <div style={dlKicker()}>Today</div>
          <div style={{ fontSize: 32, 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: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>sites visited</div>
        </div>
        <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--border-soft)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ ...dlKicker(), marginBottom: 10 }}>Across devices</div>
          <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
            {A_HISTORY_STATS.map(s => (
              <div key={s.device} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <DLConnChip device={s.device}/><span style={{ fontSize: 14, fontFamily: 'Geist', fontWeight: 600, letterSpacing: '-0.02em' }}>{s.count}</span><span style={{ fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>visits</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <DLSearch value={q} onChange={setQ} placeholder="Search history"/>
      {Object.entries(grouped).map(([day, items]) => (
        <div key={day} style={{ marginBottom: 26 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '0 4px 10px' }}><span style={dlKicker()}>{day}</span><span style={{ fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>{items.length} visits</span></div>
          <DLCard>
            {items.map((it, i) => (
              <div key={i} className="dl-row" style={dlRow(i)}>
                <span style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', width: 52, flexShrink: 0 }}>{it.ts}</span>
                {DLtile(it, 24)}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={dlTitle()}>{it.title}</div>
                  <div style={dlUrl()}>{it.url}</div>
                </div>
                <DLConnChip device={it.device}/>
              </div>
            ))}
          </DLCard>
        </div>
      ))}
    </DLPage>
  );
}

// ── Bookmarks ──────────────────────────────────────────────────
function DScreenBookmarks() {
  const [q, setQ] = React.useState('');
  const [folder, setFolder] = React.useState('All');
  const ql = q.toLowerCase();
  const filtered = A_BOOKMARKS.filter(it => (folder === 'All' || it.folder === folder) && (!ql || it.title.toLowerCase().includes(ql) || it.url.toLowerCase().includes(ql)));
  return (
    <DLPage>
      <DLHeader color="#FBBF24"
        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>}
        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={dlBtn()}>Import…</button><button style={dlBtn(true)}>Add bookmark</button></div>}/>

      <div style={{ display: 'flex', gap: 22 }}>
        <div style={{ width: 200, flexShrink: 0 }}>
          <div style={{ ...dlKicker(), padding: '0 6px 10px' }}>Folders</div>
          {[{ name: 'All', count: A_BOOKMARKS.length, color: 'var(--fg-muted)' }, ...A_BOOKMARK_FOLDERS].map(f => (
            <button key={f.name} onClick={() => setFolder(f.name)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 8, background: folder === f.name ? 'var(--hover)' : 'transparent', border: 0, color: folder === f.name ? 'var(--fg)' : 'var(--fg-muted)', fontFamily: 'inherit', fontSize: 13, fontWeight: 500, textAlign: 'left', cursor: 'pointer' }}>
              <span style={{ width: 8, height: 8, borderRadius: 2, background: f.color, flexShrink: 0 }}/>
              <span style={{ flex: 1 }}>{f.name}</span>
              <span style={{ fontSize: 10.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>{f.count}</span>
            </button>
          ))}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <DLSearch value={q} onChange={setQ} placeholder="Search bookmarks"/>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
            {filtered.map((it, i) => {
              const fm = A_BOOKMARK_FOLDERS.find(f => f.name === it.folder);
              return (
                <div key={i} className="dl-row" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, cursor: 'pointer' }}>
                  {DLtile(it, 30)}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={dlTitle()}>{it.title}</div>
                    <div style={{ display: 'flex', gap: 8, marginTop: 2 }}><span style={{ ...dlUrl(), flex: 1, minWidth: 0 }}>{it.url}</span><span style={{ fontSize: 10, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>{it.saved}</span></div>
                  </div>
                  {it.shared && <span title="Shared with mesh" style={{ color: '#A78BFA' }}><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 style={{ width: 8, height: 8, borderRadius: 2, background: fm.color }}/>}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </DLPage>
  );
}

// ── Downloads ──────────────────────────────────────────────────
function DScreenDownloads() {
  const total = 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 (
    <DLPage>
      <DLHeader color="#10B981"
        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>}
        title="Downloads" sub={A_DOWNLOADS.length + ' files · ' + dlFmt(total) + ' · iCloud Drive / Ajna'}
        tools={<button style={dlBtn()}>Open folder</button>}/>
      {active && (
        <div style={{ marginBottom: 22 }}>
          <div style={{ ...dlKicker(), padding: '0 4px 10px' }}>In progress</div>
          <DLCard>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10 }}>
                <span style={dlExt(active.bg)}>{active.ext}</span>
                <div style={{ flex: 1, minWidth: 0 }}><div style={dlTitle()}>{active.name}</div><div style={dlUrl()}>{dlFmt(active.bytes)} / {dlFmt(active.total)} · {active.speed}</div></div>
                <button style={dlBtn()}>Pause</button><button style={dlBtn()}>Cancel</button>
              </div>
              <div style={{ height: 4, background: 'var(--bg-elev-2)', borderRadius: 2, overflow: 'hidden' }}><div style={{ height: '100%', width: (active.bytes/active.total*100).toFixed(0)+'%', background: 'linear-gradient(90deg,#10B981,#6EE7B7)' }}/></div>
            </div>
          </DLCard>
        </div>
      )}
      <div style={{ ...dlKicker(), padding: '0 4px 10px' }}>Recent</div>
      <DLCard>
        {done.map((it, i) => (
          <div key={i} className="dl-row" style={dlRow(i)}>
            <span style={dlExt(it.bg)}>{it.ext}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={dlTitle()}>{it.name}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 3, alignItems: 'center', flexWrap: 'wrap' }}>
                <span style={dlUrl()}>{dlFmt(it.bytes)} · {it.time} · {it.source}</span>
                {it.verified && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 9.5, color: '#6EE7B7', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600, letterSpacing: '0.05em' }}><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', fontWeight: 600 }}>ENCRYPTED</span>}
              </div>
            </div>
            <button style={dlBtn()}>Show in folder</button>
          </div>
        ))}
      </DLCard>
    </DLPage>
  );
}

// ── Recently closed ────────────────────────────────────────────
function DScreenRecentlyClosed() {
  return (
    <DLPage>
      <DLHeader color="#22D3EE"
        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>}
        title="Recently closed" sub={A_RECENTLY_CLOSED.reduce((a, s) => a + s.tabs.length, 0) + ' tabs · ' + 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, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{s.session}</div><div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{s.when}</div></div>
            <button style={dlBtn()}>Reopen all</button>
          </div>
          <DLCard>
            {s.tabs.map((it, i) => (
              <div key={i} className="dl-row" style={dlRow(i)}>{DLtile(it, 24)}<div style={{ flex: 1, minWidth: 0 }}><div style={dlTitle()}>{it.title}</div><div style={dlUrl()}>{it.url}</div></div><span style={{ color: 'var(--fg-dim)', fontSize: 16 }}>↺</span></div>
            ))}
          </DLCard>
        </div>
      ))}
    </DLPage>
  );
}

// ── Reading list ───────────────────────────────────────────────
function DScreenReadingList({ onOpenReader }) {
  const [filter, setFilter] = React.useState('unread');
  const filtered = A_READING_LIST.filter(r => filter === 'all' || (filter === 'unread' ? !r.read : r.read));
  return (
    <DLPage>
      <DLHeader color="#10B981"
        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>}
        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={dlPill(filter === o.k)}>{o.l}</button>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
        {filtered.map((r, i) => (
          <div key={i} onClick={() => onOpenReader && onOpenReader()} className="dl-row" style={{ padding: 18, background: 'var(--bg-elev)', border: '1px solid var(--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 }}>{DLtile(r, 26)}<div style={{ flex: 1, ...dlUrl() }}>{r.url}</div>{!r.read && <span style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--accent-a)' }}/>}</div>
            <div style={{ fontSize: 16.5, fontWeight: 600, fontFamily: 'Geist', letterSpacing: '-0.02em', lineHeight: 1.3 }}>{r.title}</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', lineHeight: 1.5 }}>{r.preview}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 10.5, color: 'var(--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' }}><DLConnChip device={r.device}/></span></div>
          </div>
        ))}
      </div>
    </DLPage>
  );
}

// ── Passwords ──────────────────────────────────────────────────
function DScreenPasswords() {
  const [q, setQ] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const ql = q.toLowerCase();
  const filtered = A_PASSWORDS.filter(p => (filter === 'all' || p.flag === filter) && (!ql || p.site.toLowerCase().includes(ql) || p.user.toLowerCase().includes(ql)));
  const fc = { compromised: '#F87171', weak: '#FBBF24', reused: '#A78BFA' };
  return (
    <DLPage>
      <DLHeader color="#F472B6"
        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>}
        title="Passwords" sub={A_PASSWORDS_HEALTH.total + ' saved · encrypted with device key · synced E2E'}
        tools={<div style={{ display: 'flex', gap: 8 }}><button style={dlBtn()}>Export…</button><button style={dlBtn(true)}>Add password</button></div>}/>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 18px', marginBottom: 22, borderRadius: 14, background: 'var(--bg-elev)', border: '1px solid color-mix(in oklch, #F87171 22%, transparent)' }}>
        <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, fontFamily: 'Geist', letterSpacing: '-0.02em' }}>Password checkup</div><div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2 }}>23 credentials need your attention</div></div>
        <div style={{ display: 'flex', gap: 18 }}>
          {[['compromised', A_PASSWORDS_HEALTH.compromised], ['weak', A_PASSWORDS_HEALTH.weak], ['reused', A_PASSWORDS_HEALTH.reused]].map(([k, n]) => (
            <div key={k} style={{ textAlign: 'center' }}><div style={{ fontSize: 22, fontWeight: 700, color: fc[k], fontFamily: 'Geist', letterSpacing: '-0.03em', lineHeight: 1 }}>{n}</div><div style={{ fontSize: 9.5, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 3, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>{k}</div></div>
          ))}
        </div>
        <button style={{ ...dlBtn(), background: '#F87171', color: '#0B0C0F', border: 0, fontWeight: 700 }}>Review now</button>
      </div>
      <DLSearch 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={dlPill(filter === o.k, fc[o.k])}>{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>
      <DLCard>
        {filtered.map((p, i) => (
          <div key={i} className="dl-row" style={dlRow(i)}>
            {DLtile(p, 30)}
            <div style={{ flex: 1, minWidth: 0 }}><div style={dlTitle()}>{p.domain}</div><div style={dlUrl()}>{p.site}</div></div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', fontFamily: 'JetBrains Mono, monospace', minWidth: 220 }}>{p.user}</div>
            <div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', width: 44 }}>{p.last}</div>
            {p.flag ? <span style={{ fontSize: 9.5, fontWeight: 700, padding: '3px 9px', borderRadius: 999, background: 'color-mix(in oklch,' + fc[p.flag] + ' 18%, transparent)', color: fc[p.flag], fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.05em' }}>{p.flag.toUpperCase()}</span> : <span style={{ width: 70 }}/>}
          </div>
        ))}
      </DLCard>
    </DLPage>
  );
}

// ── Site permissions ───────────────────────────────────────────
function DScreenSitePermissions() {
  const pi = (id) => {
    const W = (d) => <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
    return ({ pin: W(<><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: W(<><path d="M3 7h4l2-3h6l2 3h4v12H3z"/><circle cx="12" cy="13" r="4"/></>), mic: W(<><rect x="9" y="3" width="6" height="12" rx="3"/><path d="M5 11a7 7 0 0 0 14 0M12 18v3"/></>), bell: W(<><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: W(<><rect x="8" y="2" width="8" height="4" rx="1"/><rect x="5" y="6" width="14" height="16" rx="2"/></>), play: W(<polygon points="6 4 20 12 6 20 6 4"/>), cookie: W(<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: W(<><ellipse cx="12" cy="6" rx="9" ry="3"/><path d="M3 6v12c0 1.7 4 3 9 3s9-1.3 9-3V6"/></>) }[id] || W(<circle cx="12" cy="12" r="9"/>));
  };
  return (
    <DLPage>
      <DLHeader color="#6EE7B7"
        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>}
        title="Site permissions" sub="Per-site grants · revoked instantly · audit log on mediator"/>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 24 }}>
        {A_PERMS_SUMMARY.map(p => (
          <div key={p.id} className="dl-row" style={{ padding: 14, background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, cursor: 'pointer' }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: 'color-mix(in oklch,' + p.color + ' 18%, transparent)', color: p.color, display: 'grid', placeItems: 'center', marginBottom: 10 }}>{pi(p.icon)}</div>
            <div style={{ fontSize: 12.5, fontWeight: 600, 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={{ ...dlKicker(), padding: '0 4px 10px' }}>Per-site grants</div>
      <DLCard>
        {A_PERMS_SITES.map((s, i) => (
          <div key={i} className="dl-row" style={dlRow(i)}>
            <div style={{ fontSize: 13.5, fontWeight: 500, 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 m = 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' ? 'color-mix(in oklch,#6EE7B7 14%,transparent)' : 'color-mix(in oklch,#F87171 14%,transparent)', color: v === 'allow' ? '#6EE7B7' : '#F87171', fontFamily: 'JetBrains Mono, monospace', fontWeight: 600 }}>{m.label.toLowerCase()} · {v}</span>; })}
            </div>
            <span style={{ color: 'var(--fg-dim)' }}>›</span>
          </div>
        ))}
      </DLCard>
    </DLPage>
  );
}

// shared style helpers
function dlBtn(primary) { return { padding: '8px 13px', borderRadius: 9, background: primary ? 'var(--fg)' : 'var(--bg-elev)', border: primary ? 0 : '1px solid var(--border-soft)', color: primary ? 'var(--bg)' : 'var(--fg)', fontSize: 12, fontWeight: primary ? 600 : 500, fontFamily: 'inherit', cursor: 'pointer' }; }
function dlPill(active, color) { return { padding: '6px 13px', borderRadius: 999, background: active ? (color || 'var(--fg)') : 'transparent', border: '1px solid ' + (active ? (color || 'var(--fg)') : 'var(--border-soft)'), color: active ? '#0B0C0F' : 'var(--fg-muted)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }; }
function dlKicker() { return { fontSize: 11, fontWeight: 700, color: 'var(--fg-dim)', letterSpacing: '0.14em', textTransform: 'uppercase', fontFamily: 'JetBrains Mono, monospace' }; }
function dlRow(i) { return { display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderTop: i === 0 ? 0 : '1px solid var(--border-soft)', cursor: 'pointer' }; }
function dlTitle() { return { fontSize: 13.5, fontWeight: 500, fontFamily: 'Geist, Inter, sans-serif', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }; }
function dlUrl() { return { fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }; }
function dlExt(bg) { return { width: 34, height: 34, borderRadius: 8, background: bg, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', flexShrink: 0 }; }

Object.assign(window, {
  DScreenHistory, DScreenBookmarks, DScreenDownloads, DScreenRecentlyClosed,
  DScreenReadingList, DScreenPasswords, DScreenSitePermissions,
  DScreenHelp, DScreenCredits,
});

// ── Help ───────────────────────────────────────────────────────
function DScreenHelp() {
  const links = [
    ['Release notes', 'v0.4.2 · 12 changes', '📰'], ['Get support', 'support.ajna.dev', '💬'],
    ['Documentation', 'docs.ajna.dev', '📘'], ['Community', 'community.ajna.dev', '🏛'],
    ['Roadmap', 'roadmap.ajna.dev', '🗺'], ['Send feedback', 'Direct to engineering', '✉'],
    ['Report a bug', 'Auto-attaches diagnostics', '🐞'], ['Privacy policy', 'ajna.dev/privacy', '🔒'],
    ['Terms of service', 'ajna.dev/terms', '📄'],
  ];
  return (
    <DLPage>
      <DLHeader color="#FBBF24"
        icon={<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M9.1 9a3 3 0 1 1 5.8 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>}
        title="Help & feedback" sub="Real humans · responses in under 24 hours"/>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
        {links.map(([l, s, ic]) => (
          <div key={l} className="dl-row" style={{ padding: '14px 16px', background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 12, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={{ fontSize: 22 }}>{ic}</span>
            <div style={{ fontSize: 13.5, fontWeight: 600, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{l}</div>
            <div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>{s}</div>
          </div>
        ))}
      </div>
    </DLPage>
  );
}

// ── Credits ────────────────────────────────────────────────────
function DScreenCredits() {
  const team = [['Maya Chen', 'Founder · Mesh', '#A78BFA'], ['Aishwarya Iyer', 'Identity · DIDComm', '#EF4444'], ['Rohan Sharma', 'Browser · UI', '#F472B6'], ['Noah Okafor', 'Sync · CRDT', '#10B981'], ['Léa Dubois', 'Design', '#22D3EE'], ['Ken Watanabe', 'Web compat', '#FBBF24']];
  const oss = [['React', '18.3.1'], ['Babel standalone', '7.29.0'], ['Geist', '1.3'], ['JetBrains Mono', '2.304'], ['Tailwind tokens', '4.0'], ['DIDComm v2', '1.0'], ['UCAN spec', '0.10'], ['noble crypto', '1.7'], ['libp2p', '1.4']];
  return (
    <DLPage>
      <DLHeader color="var(--accent-a)"
        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>}
        title="Credits" sub="People and code that built Ajna"/>
      <div style={{ display: 'flex', alignItems: 'center', gap: 22, padding: 26, marginBottom: 24, borderRadius: 16, background: 'var(--bg-elev)', border: '1px solid var(--border-soft)' }}>
        <div style={{ width: 68, height: 68, borderRadius: 18, background: 'var(--accent-grad)', display: 'grid', placeItems: 'center', color: '#0F1114', fontFamily: 'Geist', fontWeight: 700, fontSize: 38, flexShrink: 0 }}>A</div>
        <div style={{ flex: 1 }}><div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'Geist', letterSpacing: '-0.025em' }}>Ajna Browser</div><div style={{ fontSize: 11.5, color: 'var(--fg-muted)', fontFamily: 'JetBrains Mono, monospace', marginTop: 4 }}>v0.4.2 · build 24891 · May 28 2026</div><div style={{ fontSize: 12.5, color: 'var(--fg-dim)', marginTop: 8, lineHeight: 1.5 }}>Made with care in Berlin, Bangalore, and San Francisco.</div></div>
      </div>
      <div style={{ ...dlKicker(), padding: '0 4px 10px' }}>Team</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 22 }}>
        {team.map(([n, r, c]) => <div key={n} style={{ padding: 14, background: 'var(--bg-elev)', border: '1px solid var(--border-soft)', borderRadius: 11, display: 'flex', alignItems: 'center', gap: 11 }}><div style={{ width: 34, height: 34, borderRadius: 8, background: c, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700, fontFamily: 'Geist' }}>{n.split(' ').map(x => x[0]).join('')}</div><div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 600, fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{n}</div><div style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace', marginTop: 1 }}>{r}</div></div></div>)}
      </div>
      <div style={{ ...dlKicker(), padding: '0 4px 10px' }}>Open source</div>
      <DLCard>
        {oss.map(([n, v], i) => <div key={n} style={{ display: 'flex', padding: '12px 16px', borderTop: i === 0 ? 0 : '1px solid var(--border-soft)' }}><span style={{ flex: 1, fontSize: 13, fontFamily: 'Geist' }}>{n}</span><span style={{ fontSize: 11, color: 'var(--fg-dim)', fontFamily: 'JetBrains Mono, monospace' }}>v{v}</span></div>)}
      </DLCard>
    </DLPage>
  );
}
