// Library — index of every user-generated guide.

function LibraryScreen() {
  const userGuides = useGuides();
  const subjects = useSubjects();

  return (
    <Page>
      <PageHeader
        breadcrumb={['All guides']}
        sub={`${userGuides.length} ${userGuides.length === 1 ? 'guide' : 'guides'}`}
        actions={
          <button className="btn blue small" onClick={() => {
            if (subjects.length === 0) { navigate('/'); return; }
            navigate(`/subject/${subjects[0].id}/upload`);
          }}>{Icon.sparkle} New guide</button>
        }
      />

      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 22px' }}>
        {userGuides.length === 0 ? (
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 32, textAlign: 'center' }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>No guides yet</div>
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 6 }}>
              {subjects.length === 0
                ? 'Add a subject from the sidebar, then upload files to generate your first guide.'
                : 'Upload files to generate your first guide.'}
            </div>
            {subjects.length > 0 && (
              <button className="btn blue small" style={{ marginTop: 14 }}
                onClick={() => navigate(`/subject/${subjects[0].id}/upload`)}>
                {Icon.upload} Upload files
              </button>
            )}
          </div>
        ) : (
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '20px 130px 1fr 90px 80px 70px 24px', gap: 10, padding: '8px 12px', fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-mute)', borderBottom: '1px solid var(--line)', background: 'var(--bg)' }}>
              <span></span><span>Subject</span><span>Title</span><span>Sources</span><span>Cards</span><span>Created</span><span></span>
            </div>
            {userGuides.map((g, i) => {
              const subject = subjects.find((s) => s.id === g.subjectId);
              return (
                <div key={g.id}
                  onClick={() => navigate(`/subject/${g.subjectId}/guide/${g.id}`)}
                  style={{ display: 'grid', gridTemplateColumns: '20px 130px 1fr 90px 80px 70px 24px', gap: 10, padding: '9px 12px', alignItems: 'center', fontSize: 12, borderBottom: i === userGuides.length - 1 ? 'none' : '1px solid var(--line-soft)', cursor: 'pointer' }}>
                  <input type="checkbox" style={{ margin: 0 }} onClick={(e) => e.stopPropagation()} />
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-mute)' }}>
                    <span>{subject?.emoji || '📄'}</span>
                    <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{subject?.name || '(unknown subject)'}</span>
                  </div>
                  <div style={{ fontWeight: 500 }}>{g.title}</div>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{g.sources || 0}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-mute)' }}>{(g.content?.flashcards || []).length}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-mute)' }}>{relativeShort(g.generatedAt)}</span>
                  <span style={{ color: 'var(--ink-whisper)' }}>{Icon.dots}</span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </Page>
  );
}

function relativeShort(iso) {
  if (!iso) return '';
  const sec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return 'now';
  if (sec < 3600) return Math.floor(sec / 60) + 'm';
  if (sec < 86400) return Math.floor(sec / 3600) + 'h';
  return Math.floor(sec / 86400) + 'd';
}

Object.assign(window, { LibraryScreen });
