// iPad Library — Bookmarks / History / Downloads.
// Shares the data shape with mobile's M_LIB_DATA but renders tablet-styled:
// roomy two-column layout in landscape, sidebar folder rail for bookmarks,
// search field and inline filters. Used when the user picks one of these
// items from TMoreMenu — tablet-app.jsx routes it via setScreen(id).

const T_LIB_DATA = {
  bookmarks: {
    title: 'Bookmarks',
    sub: '12 saved · last added 2 hr ago',
    icon: (p) => <svg width={p?.s||18} height={p?.s||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>,
    folders: [
      { name: 'All',      count: 12 },
      { name: 'Work',     count: 5  },
      { name: 'Reading',  count: 4  },
      { name: 'Daily',    count: 3  },
    ],
    items: [
      { title: 'Linear — Inbox',        url: 'linear.app/inbox',                fav: 'L', bg: '#5E6AD2', folder: 'Work' },
      { title: 'Ajna Browser',          url: 'github.com/ajna-inc/browser',     fav: 'G', bg: '#24292F', folder: 'Work' },
      { title: 'P2P Sync RFC',          url: 'notion.so/p2p-sync',              fav: 'N', bg: '#fff',    c: '#000', folder: 'Reading' },
      { title: 'DIDComm Spec',          url: 'identity.foundation/didcomm',     fav: 'D', bg: '#7C3AED', folder: 'Reading' },
      { title: 'Hacker News',           url: 'news.ycombinator.com',            fav: 'Y', bg: '#FF6600', folder: 'Daily' },
      { title: 'Hypermedia Protocol',   url: 'hyper.media',                     fav: 'H', bg: '#0F172A', folder: 'Reading' },
      { title: 'UCAN Spec',             url: 'ucan.xyz',                        fav: 'U', bg: '#1E40AF', folder: 'Reading' },
      { title: 'Linear · Triage',       url: 'linear.app/ajna/triage',          fav: 'L', bg: '#5E6AD2', folder: 'Work' },
      { title: 'Posthog Dashboard',     url: 'us.posthog.com/dashboard/ajna',   fav: 'P', bg: '#1D4ED8', folder: 'Work' },
      { title: 'Tailwind Docs',         url: 'tailwindcss.com/docs',            fav: 'T', bg: '#0EA5E9', folder: 'Work' },
      { title: 'iA Writer',             url: 'ia.net/writer',                   fav: 'i', bg: '#000',    folder: 'Daily' },
      { title: 'Cloudflare Status',     url: 'cloudflarestatus.com',            fav: 'C', bg: '#F38020', folder: 'Daily' },
    ],
  },
  history: {
    title: 'History',
    sub: 'Cleared on close in private · 9 visits today',
    icon: (p) => <svg width={p?.s||18} height={p?.s||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>,
    items: [
      { group: 'Today',     title: 'Linear — Inbox',           url: 'linear.app/inbox',                    fav: 'L', bg: '#5E6AD2', time: '12 min ago' },
      { group: 'Today',     title: 'Ajna Browser PRs',         url: 'github.com/ajna-inc/browser/pulls',   fav: 'G', bg: '#24292F', time: '34 min ago' },
      { group: 'Today',     title: 'P2P Sync RFC',             url: 'notion.so/p2p-sync',                  fav: 'N', bg: '#fff', c: '#000', time: '1 hr ago' },
      { group: 'Today',     title: 'DIDComm Spec',             url: 'identity.foundation/didcomm',         fav: 'D', bg: '#7C3AED', time: '2 hr ago' },
      { group: 'Today',     title: 'Stripe Dashboard',         url: 'dashboard.stripe.com',                fav: 'S', bg: '#635BFF', time: '3 hr ago' },
      { group: 'Today',     title: 'Hacker News',              url: 'news.ycombinator.com',                fav: 'Y', bg: '#FF6600', time: '4 hr ago' },
      { group: 'Yesterday', title: 'Cloudflare D1 Pricing',    url: 'developers.cloudflare.com/d1',        fav: 'C', bg: '#F38020', time: '11:42 AM' },
      { group: 'Yesterday', title: 'iA Writer',                url: 'ia.net/writer',                       fav: 'i', bg: '#000',    time: '9:14 AM' },
      { group: 'May 25',    title: 'Tailwind v4 Blog',         url: 'tailwindcss.com/blog/tailwindcss-v4', fav: 'T', bg: '#0EA5E9', time: '4:02 PM' },
    ],
  },
  downloads: {
    title: 'Downloads',
    sub: '3 files · ajna://library/downloads',
    icon: (p) => <svg width={p?.s||18} height={p?.s||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>,
    items: [
      { title: 'P2P-Sync-RFC.pdf',      url: '1.2 MB · 12 min ago', fav: 'PDF', bg: '#EF4444' },
      { title: 'didcomm-v2.zip',        url: '6.8 MB · 1 hr ago',   fav: 'ZIP', bg: '#0EA5E9' },
      { title: 'ajna-keys-backup.kbx',  url: '14 KB · Yesterday',   fav: 'KEY', bg: '#10B981' },
    ],
  },
};

function TScreenLibrary({ kind, landscape = true, onOpen }) {
  const data = T_LIB_DATA[kind] || { title: kind, sub: '', items: [] };
  const [q, setQ] = React.useState('');
  const [folder, setFolder] = React.useState('All');
  const filtered = (data.items || []).filter(it => {
    if (folder !== 'All' && it.folder !== folder) return false;
    if (!q) return true;
    const ql = q.toLowerCase();
    return it.title.toLowerCase().includes(ql) || it.url.toLowerCase().includes(ql);
  });

  // Group history by group key
  const historyGroups = {};
  if (kind === 'history') {
    filtered.forEach(it => {
      const k = it.group || 'Other';
      (historyGroups[k] = historyGroups[k] || []).push(it);
    });
  }

  const Row = ({ it }) => (
    <div onClick={() => onOpen && onOpen(it)} style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px', cursor: 'pointer',
      borderBottom: '1px solid ' + M_BORDER_SOFT,
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--m-tint-2)'}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <MTile size={28} 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, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontFamily: 'Geist', letterSpacing: '-0.01em' }}>{it.title}</div>
        <div style={{ fontSize: 11, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {kind === 'history' && it.time && <span style={{ marginRight: 8, color: M_FG_MUTED }}>{it.time}</span>}
          {it.url}
          {kind === 'bookmarks' && it.folder && <span style={{ marginLeft: 8, color: M_ACCENT_B }}>· {it.folder}</span>}
        </div>
      </div>
      {kind === 'downloads'
        ? <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>
        : <span style={{ color: M_FG_DIM, fontSize: 13 }}>↗</span>}
    </div>
  );

  return (
    <div style={{ height: '100%', display: 'flex', overflow: 'hidden', background: M_BG, color: M_FG }}>
      {/* Folder rail — bookmarks only, landscape only */}
      {kind === 'bookmarks' && landscape && data.folders && (
        <div style={{
          width: 220, flexShrink: 0, padding: '24px 14px',
          borderRight: '1px solid ' + M_BORDER_SOFT, background: M_BG,
          overflowY: 'auto',
        }}>
          <div style={{ fontSize: 10, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600, fontFamily: 'JetBrains Mono, monospace', padding: '0 6px 10px' }}>Folders</div>
          {data.folders.map(f => (
            <button key={f.name} onClick={() => setFolder(f.name)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 10,
              padding: '9px 10px', borderRadius: 8,
              background: folder === f.name ? 'var(--m-tint)' : 'transparent',
              border: 0, color: folder === f.name ? M_FG : M_FG_MUTED,
              fontFamily: 'inherit', fontSize: 13, fontWeight: 500, textAlign: 'left', cursor: 'pointer',
            }}>
              <span style={{ color: folder === f.name ? M_ACCENT_B : M_FG_DIM, display: 'grid', placeItems: 'center' }}>
                {f.name === 'All'
                  ? <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/></svg>
                  : <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>}
              </span>
              <span style={{ flex: 1 }}>{f.name}</span>
              <span style={{ fontSize: 10.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>{f.count}</span>
            </button>
          ))}
        </div>
      )}

      {/* Main pane */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 28px 60px' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div style={{
            width: 38, height: 38, borderRadius: 10,
            background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT,
            color: M_FG, display: 'grid', placeItems: 'center',
          }}>{data.icon({ s: 18 })}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 22, fontWeight: 600, fontFamily: 'Geist', letterSpacing: '-0.02em' }}>{data.title}</div>
            <div style={{ fontSize: 11.5, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>{data.sub}</div>
          </div>
        </div>

        {/* Search + (portrait) folder pills */}
        {kind !== 'downloads' && (
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 18, flexWrap: 'wrap' }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '8px 14px', flex: 1, minWidth: 240,
              background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 10,
            }}>
              <span style={{ color: M_FG_DIM }}>{MIc.search({ s: 14 })}</span>
              <input
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder={'Search ' + data.title.toLowerCase() + '…'}
                style={{ flex: 1, background: 'transparent', border: 0, outline: 'none', color: M_FG, fontSize: 13, fontFamily: 'inherit' }}
              />
              <span style={{ fontSize: 10, color: M_FG_DIM, fontFamily: 'JetBrains Mono, monospace' }}>⌘F</span>
            </div>
            {kind === 'bookmarks' && (!landscape || !data.folders) && data.folders && (
              <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 2 }}>
                {data.folders.map(f => (
                  <button key={f.name} onClick={() => setFolder(f.name)} style={{
                    flexShrink: 0, padding: '6px 10px', borderRadius: 999,
                    background: folder === f.name ? M_FG : 'transparent',
                    border: '1px solid ' + (folder === f.name ? M_FG : M_BORDER_SOFT),
                    color: folder === f.name ? '#0B0C0F' : M_FG_MUTED,
                    fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
                  }}>{f.name} <span style={{ opacity: 0.55, marginLeft: 4 }}>{f.count}</span></button>
                ))}
              </div>
            )}
          </div>
        )}

        {/* List */}
        {kind === 'history' ? (
          Object.keys(historyGroups).map(g => (
            <div key={g} style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 11, color: M_FG_DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600, fontFamily: 'JetBrains Mono, monospace', padding: '0 4px 8px' }}>{g}</div>
              <div style={{ background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden' }}>
                {historyGroups[g].map((it, i) => (
                  <div key={it.title + i} style={{ ...((i === historyGroups[g].length - 1) ? { borderBottom: 0 } : {}) }}>
                    <Row it={it}/>
                  </div>
                ))}
              </div>
            </div>
          ))
        ) : (
          <div style={{ background: M_SURFACE, border: '1px solid ' + M_BORDER_SOFT, borderRadius: 12, overflow: 'hidden' }}>
            {filtered.length === 0
              ? <div style={{ padding: '50px 24px', textAlign: 'center', color: M_FG_DIM, fontSize: 13 }}>No matches</div>
              : filtered.map((it, i) => (
                <div key={it.title + i} style={{ ...((i === filtered.length - 1) ? { borderBottom: 0 } : {}) }}>
                  <Row it={it}/>
                </div>
              ))}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TScreenLibrary, T_LIB_DATA });
