/* page-library.jsx — list of available drafts (route '/') */

function PageLibrary() {
  const { loading, items, error } = useContent();

  if (loading) {
    return <div className="notice"><p><T zh="加载中……" en="Loading..." /></p></div>;
  }
  if (error) {
    return (
      <div className="notice">
        <p><T zh="无法加载内容索引：" en="Failed to load content index: " />{error}</p>
      </div>
    );
  }
  if (items.length === 0) {
    return (
      <div className="notice">
        <p><T zh="尚未发布任何作品。" en="No works published yet." /></p>
      </div>
    );
  }

  const stories = items.filter(i => i.type !== 'interactive');
  const interactives = items.filter(i => i.type === 'interactive');

  return (
    <main className="library">
      <h1><T zh="书架" en="Library" /></h1>
      <p className="lib-meta">
        <T
          zh={`${items.length} 篇可读 · 草稿全文`}
          en={`${items.length} works · full drafts`} />
      </p>
      {stories.length > 0 && (
        <section className="lib-section">
          <h2 className="lib-section-title"><T zh="作品" en="Stories" /></h2>
          <div className="lib-grid">
            {stories.map(item => (
              <LibraryCard key={`${item.type}/${item.slug}`} item={item} />
            ))}
          </div>
        </section>
      )}
      {interactives.length > 0 && (
        <section className="lib-section">
          <h2 className="lib-section-title"><T zh="互动可视化" en="Interactives" /></h2>
          <div className="lib-grid">
            {interactives.map(item => (
              <LibraryCard key={`${item.type}/${item.slug}`} item={item} />
            ))}
          </div>
        </section>
      )}
    </main>
  );
}

function LibraryCard({ item }) {
  const { lang } = useLang();
  const accent = (POV_LABEL[item.pov] || {}).accent || 'var(--ink)';
  const title = lang === 'zh' ? item.title_zh : (item.title_en || item.title_zh);
  const enUnder = (lang === 'zh' && item.title_en) ? item.title_en : null;
  const summary = lang === 'zh' ? item.summary_zh : item.summary_en;
  const wordCount = wordCountForLang(item, lang);

  return (
    <a className="lib-card" href={`#/read/${item.type}/${item.slug}`}>
      <span className="lib-accent" style={{ background: accent }}></span>
      <h2 className="lib-title-zh">{title || item.slug}</h2>
      {enUnder && <p className="lib-title-en">{enUnder}</p>}
      {summary && <p className="lib-summary">{summary}</p>}
      <div className="lib-foot">
        <PovBadge pov={item.pov} />
        {item.publish_date && <span className="num">{item.publish_date}</span>}
        {wordCount > 0 && (
          <span className="num">
            {(wordCount / 1000).toFixed(1)}k
          </span>
        )}
      </div>
    </a>
  );
}

Object.assign(window, { PageLibrary, LibraryCard });
