// Library — kệ sách theo trạng thái

function Library({ books, loading, onOpenBook, density, onNav }) {
  const [query, setQuery] = React.useState("");
  const [genreFilter, setGenreFilter] = React.useState(null);
  const [expanded, setExpanded] = React.useState({});

  const normalize = (s) =>
    (s || "").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/đ/g, "d").replace(/Đ/g, "d");

  const filtered = React.useMemo(() => {
    const q = normalize(query.trim());
    const tokens = q.split(/\s+/).filter(Boolean);
    return books.filter((b) => {
      if (tokens.length > 0) {
        const haystack = normalize(b.title) + " " + normalize(b.author);
        if (!tokens.every((t) => haystack.includes(t))) return false;
      }
      if (genreFilter && !(b.genres || []).includes(genreFilter)) return false;
      return true;
    });
  }, [books, query, genreFilter]);

  const shelves = [
    { id: "reading", label: "Đang đọc" },
    { id: "finished", label: "Đã đọc" },
    { id: "want", label: "Muốn đọc" },
  ];

  function sortForShelf(items, shelfId) {
    if (shelfId === "finished") {
      return [...items].sort((a, b) => (b.finished || "").localeCompare(a.finished || ""));
    }
    if (shelfId === "reading") {
      return [...items].sort((a, b) => (b.started || "").localeCompare(a.started || ""));
    }
    return items;
  }

  const allGenres = React.useMemo(() => {
    const set = new Set();
    books.forEach((b) => (b.genres || []).forEach((g) => {
      if (g !== "Hard copy" && g !== "Ebook") set.add(g);
    }));
    return Array.from(set).sort();
  }, [books]);

  const coverSize = density === "compact" ? "sm" : "md";
  const SHELF_CAP = density === "compact" ? 60 : 30;

  return (
    <div className="library">
      <Shelf books={filtered} onOpenBook={onOpenBook} />
      {loading && (
        <div className="library-loading">
          <div className="library-loading-bar"></div>
        </div>
      )}
      <header className="library-header" id="tu-sach">
        <div className="library-header-row">
          <div>
            <div className="eyebrow">
              Người hay đọc · tủ sách của tôi
            </div>
            <h1 className="library-title">Phòng Đọc</h1>
            <p className="library-sub">{books.length} cuốn · {books.filter(b=>b.status==="reading").length} đang đọc · {books.filter(b=>b.status==="finished").length} đã đọc · {books.filter(b=>b.status==="want").length} trên kệ chờ</p>
          </div>
        </div>

        <div className="library-controls">
          <div className="search-box">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="6" cy="6" r="4.2" stroke="currentColor" strokeWidth="1.2"/><path d="M9.2 9.2L12 12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>
            <input
              type="text"
              placeholder="Tìm theo tên sách hoặc tác giả…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
          </div>
          <div className="genre-chips">
            <button className={"chip " + (genreFilter === null ? "chip-on" : "")} onClick={() => setGenreFilter(null)}>Tất cả</button>
            {allGenres.map((g) => (
              <button key={g} className={"chip " + (genreFilter === g ? "chip-on" : "")} onClick={() => setGenreFilter(g === genreFilter ? null : g)}>{g}</button>
            ))}
          </div>
        </div>
      </header>

      <main className="shelves">
        {shelves.map((sh) => {
          const items = sortForShelf(filtered.filter((b) => b.status === sh.id), sh.id);
          const isExpanded = !!expanded[sh.id];
          const showAll = items.length <= SHELF_CAP || isExpanded;
          const visible = showAll ? items : items.slice(0, SHELF_CAP);
          return (
            <section key={sh.id} className="shelf" data-screen-label={`shelf-${sh.id}`}>
              <div className="shelf-header">
                <h2 className="shelf-title">{sh.label}</h2>
                <span className="shelf-count">{items.length}{items.length > SHELF_CAP && !isExpanded ? ` · hiển thị ${visible.length}` : ""}</span>
              </div>
              {items.length === 0 ? (
                <div className="shelf-empty">Kệ này trống{query || genreFilter ? " với bộ lọc hiện tại" : ""}.</div>
              ) : (
                <React.Fragment>
                  <div className={"shelf-row " + (density === "compact" ? "shelf-row-compact" : "")}>
                    {visible.map((b) => (
                      <div key={b.id} className="shelf-item" onClick={() => onOpenBook(b.id)}>
                        <Cover book={b} size={coverSize} onClick={() => onOpenBook(b.id)} />
                        <div className="shelf-meta">
                          <div className="shelf-meta-title">{b.title}</div>
                          <div className="shelf-meta-author">{b.author}</div>
                          {b.status === "reading" && b.pages && b.progress > 0 && (
                            <div className="progress-bar">
                              <div className="progress-fill" style={{ width: `${Math.round((b.progress / b.pages) * 100)}%` }}></div>
                            </div>
                          )}
                          {b.status === "finished" && b.rating > 0 && (
                            <div className="stars">
                              {[1,2,3,4,5].map(n => <span key={n} className={n <= b.rating ? "star star-on" : "star"}>★</span>)}
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                  {items.length > SHELF_CAP && (
                    <button
                      className="shelf-expand"
                      onClick={() => setExpanded({ ...expanded, [sh.id]: !isExpanded })}
                    >
                      {isExpanded ? `Thu gọn` : `Xem tất cả ${items.length}`}
                      <span className="shelf-expand-arrow">{isExpanded ? "↑" : "↓"}</span>
                    </button>
                  )}
                </React.Fragment>
              )}
              <div className="shelf-board"></div>
            </section>
          );
        })}
      </main>
    </div>
  );
}

window.Library = Library;
