// Primus IQ — Library Screen

const LIB_FILES = [
  { name: 'Public Policy Whitepaper 2026.pdf', ext: 'pdf',  size: '6.2 MB',  modified: '12 May 2026', conf: 'public',   practice: 'Public Policy Realization' },
  { name: 'GCC Fintech Sector Map.png',         ext: 'png',  size: '2.1 MB',  modified: '10 May 2026', conf: 'internal', practice: 'Sector Potential Realization' },
  { name: 'Sector Outlook · KSA.pptx',          ext: 'pptx', size: '14.8 MB', modified: '08 May 2026', conf: 'internal', practice: 'Sector Potential Realization' },
  { name: 'TCFD Compliance Matrix.xlsx',        ext: 'xlsx', size: '3.4 MB',  modified: '04 May 2026', conf: 'public',   practice: 'Economic Potential Realization' },
  { name: 'Renewables Capex 2026.pdf',          ext: 'pdf',  size: '4.8 MB',  modified: '30 Apr 2026', conf: 'public',   practice: 'Economic Potential Realization' },
  { name: 'CFO interview transcript.docx',      ext: 'docx', size: '180 KB',  modified: '22 Apr 2026', conf: 'client',   practice: 'Sector Potential Realization' },
  { name: 'Cost build · Phase 1.xlsx',          ext: 'xlsx', size: '2.4 MB',  modified: '18 Apr 2026', conf: 'client',   practice: 'Transaction Realization' },
];

const adaptLibraryFile = (f) => {
  const ext = (f.file_name || '').split('.').pop().toLowerCase() || 'doc';
  const bytes = f.file_size || 0;
  const size = bytes < 1024 ? `${bytes} B` : bytes < 1048576 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1048576).toFixed(1)} MB`;
  return {
    id: f.id,
    name: f.file_name || f.name || '',
    ext,
    size: size || '',
    modified: f.uploaded_at ? new Date(f.uploaded_at).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' }) : '—',
    conf: f.confidentiality || 'internal',
    practice: (f.tags && f.tags.length > 0) ? f.tags[0] : '',
    status: f.status || 'uploading',
  };
};

const LIBRARY_PAGE_SIZE = 50;   // rows rendered per "page" — keeps 1000+ files from all mounting at once

const ScreenLibrary = ({ openAddSources, libraryFiles, onDeleteFile, onDownloadFile, onEditFile, onViewFile }) => {
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');
  const [visible, setVisible] = React.useState(LIBRARY_PAGE_SIZE);

  const sourceFiles = (libraryFiles && libraryFiles.length > 0) ? libraryFiles.map(adaptLibraryFile) : [];

  const filtered = sourceFiles.filter(f =>
    (filter === 'all'
      || (filter === 'images' && (f.ext === 'png' || f.ext === 'jpg'))
      || (filter === 'docs'   && (f.ext === 'pdf' || f.ext === 'docx'))
      || (filter === 'sheets' && f.ext === 'xlsx')
      || (filter === 'decks'  && f.ext === 'pptx')
    ) && (!q || f.name.toLowerCase().includes(q.toLowerCase()))
  );

  // Render only a window of rows; reset to the first page whenever the filter/search changes.
  React.useEffect(() => { setVisible(LIBRARY_PAGE_SIZE); }, [filter, q]);
  const shown = filtered.slice(0, visible);
  const hasMore = filtered.length > visible;

  return (
    <div style={{ flex: 1, height: '100%', background: 'var(--bg)', position: 'relative', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div className="mobile-p-16" style={{ padding: '40px 48px 0', flexShrink: 0 }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div className="mobile-stack" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
          <div>
            <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: 0, letterSpacing: '-0.02em' }}>Library</h1>
            <p style={{ fontSize: 13, color: 'var(--mute)', margin: '6px 0 0' }}>
              Firm-wide knowledge base — searchable across every chat.
            </p>
          </div>
          <button className="btn-primary" onClick={openAddSources}>
            <PIcon name="plus" size={14} color="white" /> Add sources
          </button>
        </div>
        <div className="mobile-stack" style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <div className="library-filters-container">
            {[
              { id: 'all',    l: 'All',    n: sourceFiles.length },
              { id: 'docs',   l: 'Docs',   n: sourceFiles.filter(f => f.ext === 'pdf' || f.ext === 'docx').length },
              { id: 'decks',  l: 'Decks',  n: sourceFiles.filter(f => f.ext === 'pptx').length },
              { id: 'sheets', l: 'Sheets', n: sourceFiles.filter(f => f.ext === 'xlsx').length },
              { id: 'images', l: 'Images', n: sourceFiles.filter(f => f.ext === 'png' || f.ext === 'jpg').length },
            ].map(t => (
              <button key={t.id} onClick={() => setFilter(t.id)} style={{
                padding: '7px 14px', borderRadius: 7,
                background: filter === t.id ? 'var(--bg-card)' : 'transparent',
                border: 'none', cursor: 'pointer',
                fontSize: 13, fontWeight: filter === t.id ? 600 : 500,
                color: filter === t.id ? 'var(--ink)' : 'var(--mute)',
                fontFamily: 'inherit',
                boxShadow: filter === t.id ? 'var(--shadow-xs)' : 'none',
                display: 'inline-flex', alignItems: 'center', gap: 6,
                flexShrink: 0,
              }}>
                {t.l}
                <span style={{ fontSize: 11, color: 'var(--mute-2)', fontWeight: 500 }}>{t.n}</span>
              </button>
            ))}
          </div>
          <div style={{ flex: 1 }} />
          <div className="search-input" style={{ width: 260, height: 36 }}>
            <PIcon name="search" size={16} color="var(--mute)" />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search library"/>
          </div>
        </div>
        </div>
      </div>

      <div className="pi-thin-scroll mobile-p-16" style={{ flex: 1, overflowY: 'auto', padding: '0 48px 40px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          {sourceFiles.length === 0 && !q && (
            <div style={{
              padding: '60px 20px', borderRadius: 14, background: 'var(--bg-card)',
              border: '1px dashed var(--line-2)', textAlign: 'center',
              fontSize: 14, color: 'var(--mute)', marginTop: 16,
            }}>
              No files in the library yet.{' '}
              <button onClick={openAddSources} style={{ background: 'none', border: 'none', color: 'var(--maroon)', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14 }}>
                Add your first source.
              </button>
            </div>
          )}
          {sourceFiles.length > 0 && (
            <div style={{ background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--line)', overflow: 'hidden' }}>
              {/* Column headers - sticky so they stay aligned with rows under the scrollbar */}
              <div className="library-grid-row" style={{
                display: 'grid', gridTemplateColumns: '1fr 180px 120px 160px 40px',
                padding: '10px 18px', fontSize: 11, color: 'var(--mute)', fontWeight: 600,
                letterSpacing: '0.06em', textTransform: 'uppercase',
                background: 'var(--bg-soft)', borderBottom: '1px solid var(--line)',
                position: 'sticky', top: 0, zIndex: 2,
              }}>
                <div>Name</div><div className="mobile-hide">Confidentiality</div><div>Status</div><div className="mobile-hide">Modified</div><div></div>
              </div>
              {filtered.length === 0 && (
                <div style={{ padding: '24px 18px', fontSize: 13, color: 'var(--mute)', textAlign: 'center' }}>
                  No files match your filter.
                </div>
              )}
              {shown.map((f, i) => (
                <LibraryFileRow
                  key={f.id || i}
                  f={f}
                  isLast={!hasMore && i === shown.length - 1}
                  onDownload={onDownloadFile ? () => onDownloadFile(f.id) : null}
                  onDelete={onDeleteFile ? () => onDeleteFile(f.id) : null}
                  onEdit={onEditFile ? () => onEditFile(f) : null}
                  onView={onViewFile ? () => onViewFile(f) : null}
                />
              ))}
              {hasMore && (
                <div style={{ padding: '14px 18px', textAlign: 'center' }}>
                  <button onClick={() => setVisible(v => v + LIBRARY_PAGE_SIZE)} className="btn-secondary" style={{ height: 34 }}>
                    Load more · showing {shown.length} of {filtered.length}
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const LibraryFileRow = ({ f, isLast, onDownload, onDelete, onEdit, onView }) => {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  React.useEffect(() => {
    if (!menuOpen) return;
    const handler = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [menuOpen]);
  return (
    <div className="library-grid-row" onClick={() => onView && onView()} style={{
      display: 'grid', gridTemplateColumns: '1fr 180px 120px 160px 40px',
      padding: '12px 18px', alignItems: 'center',
      borderBottom: isLast ? 'none' : '1px solid var(--line)',
      cursor: onView ? 'pointer' : 'default', transition: 'background 0.12s',
    }}
    onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-soft)'}
    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
        <FileBadge ext={f.ext} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
          <div style={{ fontSize: 11, color: 'var(--mute)' }}>{f.size}</div>
        </div>
      </div>
      <div className="mobile-hide"><span className={`conf ${f.conf}`}> {CONF_LABELS[f.conf] || f.conf} </span></div>
      <div>
        <span className={`status-pill ${f.status}`} style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            whiteSpace: 'nowrap',
          }}>
          {
            f.status === 'graph_complete' ? 'Published to AI'
            : f.status === 'dirty_ready'  ? 'AI Search Ready'
            : f.status === 'complete'     ? 'File Saved'
            : f.status === 'failed'       ? 'Save Failed'
            : f.status
          }
        </span>
      </div>
      <div className="mobile-hide" style={{ fontSize: 12, color: 'var(--mute)' }}>{f.modified}</div>
      <div ref={menuRef} style={{ textAlign: 'center', position: 'relative' }}>
        <button onClick={(e) => { e.stopPropagation(); setMenuOpen(o => !o); }} style={{
          width: 28, height: 28, borderRadius: 7, background: 'transparent', border: 'none',
          cursor: 'pointer', color: 'var(--mute)', display: 'grid', placeItems: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><circle cx="3" cy="8" r="1.3"/><circle cx="8" cy="8" r="1.3"/><circle cx="13" cy="8" r="1.3"/></svg>
        </button>
        {menuOpen && (
          <div style={{
            position: 'absolute', right: 0,
            bottom: isLast ? '100%' : 'auto',
            top: isLast ? 'auto' : '100%',
            marginBottom: isLast ? 4 : 0,
            marginTop: isLast ? 0 : 4,
            width: 140,
            background: 'var(--bg-card)', border: '1px solid var(--line-2)', borderRadius: 10,
            boxShadow: 'var(--shadow-md)', zIndex: 30, overflow: 'hidden',
          }}>
            {onDownload && (
              <button onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onDownload(); }} style={fileMenuItemStyle}>
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M8 3v8M4 8l4 4 4-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/><path d="M3 13h10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
                Download
              </button>
            )}
            {onEdit && (
              <button onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onEdit(); }} style={fileMenuItemStyle}>
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M11 2l3 3-8 8-3.5.5.5-3.5 8-8z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Edit tags &amp; visibility
              </button>
            )}
            {onDelete && (
              <button onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onDelete(); }} style={{ ...fileMenuItemStyle, color: 'var(--maroon)' }}>
                <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M3 5h10M6 5V3h4v2M7 8v4M9 8v4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/><path d="M5 5l.5 8h5l.5-8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Delete
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, {
  LIB_FILES,
  adaptLibraryFile,
  ScreenLibrary,
  LibraryFileRow,
});
