/* global React */
// ============================================================================
// Biblioteca Digital — acervo de pesquisa estilo estante de livros
// Separado das aulas. Admin sobe PDFs (Drive/Mega/OneDrive); aluno pesquisa.
// ============================================================================
const { useState: useStateL, useEffect: useEffectL } = React;

// Paleta de cores das lombadas (couro/dourado), escolhida de forma estável por título
const SPINE_PALETTE = [
  { bg: "linear-gradient(180deg,#3a2414,#23150b)", edge: "#5a3a1e" },
  { bg: "linear-gradient(180deg,#4a3018,#2c1c0e)", edge: "#6b4423" },
  { bg: "linear-gradient(180deg,#2e1f12,#1a1009)", edge: "#4a3320" },
  { bg: "linear-gradient(180deg,#43250f,#271409)", edge: "#6a3c1a" },
  { bg: "linear-gradient(180deg,#352a18,#1e160c)", edge: "#574325" },
  { bg: "linear-gradient(180deg,#3d2a1a,#221710)", edge: "#604530" },
];
function spineFor(book) {
  if (book.spineColor) {
    return { bg: book.spineColor, edge: "rgba(255,255,255,0.12)" };
  }
  let h = 0;
  const s = (book.title || "") + (book.id || "");
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return SPINE_PALETTE[h % SPINE_PALETTE.length];
}

// Visor: tenta embed do Drive; senão usa a própria URL (Mega/OneDrive abrem o player deles)
function libraryEmbedUrl(url) {
  const drive = window.driveEmbedUrl(url);
  if (drive) return drive;
  return url; // OneDrive/Mega: a própria URL de compartilhamento
}

function LibraryPage({ user, go }) {
  const [books, setBooks] = useStateL([]);
  const [loading, setLoading] = useStateL(true);
  const [active, setActive] = useStateL(null);
  const [query, setQuery] = useStateL("");

  useEffectL(() => {
    let mounted = true;
    (async () => {
      try {
        const list = await window.BNSupa.listLibrary();
        if (mounted) setBooks(list);
      } catch (e) {
        console.error("Erro ao carregar biblioteca:", e);
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  // Filtra por busca
  const filtered = books.filter((b) => {
    if (!query) return true;
    const q = query.toLowerCase();
    return (
      (b.title || "").toLowerCase().includes(q) ||
      (b.author || "").toLowerCase().includes(q) ||
      (b.category || "").toLowerCase().includes(q)
    );
  });

  // Agrupa por categoria
  const groups = {};
  filtered.forEach((b) => {
    const cat = b.category || "Geral";
    (groups[cat] = groups[cat] || []).push(b);
  });
  const cats = Object.keys(groups).sort();

  return (
    <main className="library-page">
      {/* Cabeçalho da biblioteca */}
      <header className="lib-hero">
        <div className="lib-hero-inner">
          <div className="lib-hero-badge" />
          <div className="lib-hero-heb">אוֹצָר הַחָכְמָה</div>
          <h1 className="lib-hero-title">Biblioteca Digital</h1>
          <p className="lib-hero-sub">
            Acervo de estudo e pesquisa do Beit Net'zer. Escolha um volume da estante para abrir.
          </p>
          <div className="lib-search-wrap">
            <span className="lib-search-icon">⌕</span>
            <input
              className="lib-search"
              placeholder="Buscar por título, autor ou tema…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
          </div>
        </div>
      </header>

      {loading ? (
        <div className="lib-empty">
          <div className="lib-empty-heb">טוֹעֵן…</div>
          <p>Carregando o acervo…</p>
        </div>
      ) : books.length === 0 ? (
        <div className="lib-empty">
          <div className="brand-mark lib-empty-mark" />
          <div className="lib-empty-heb">שָׁלוֹם</div>
          <h2>A biblioteca está sendo montada</h2>
          <p>Em breve o acervo de pesquisa estará disponível aqui. Volte mais tarde.</p>
        </div>
      ) : filtered.length === 0 ? (
        <div className="lib-empty">
          <div className="lib-empty-heb">לֹא נִמְצָא</div>
          <h2>Nada encontrado</h2>
          <p>Nenhum volume corresponde a "{query}".</p>
        </div>
      ) : (
        <div className="lib-shelves">
          {cats.map((cat) => (
            <section key={cat} className="lib-shelf-block">
              <div className="lib-shelf-label">
                <span><span className="lib-shelf-icon">{window.categoryIcon(cat)}</span>{cat}</span>
                <span className="lib-shelf-count">{groups[cat].length} {groups[cat].length === 1 ? "volume" : "volumes"}</span>
              </div>
              <div className="lib-shelf">
                <div className="lib-shelf-books">
                  {groups[cat].map((b) => {
                    const sp = spineFor(b);
                    return (
                      <button
                        key={b.id}
                        className="lib-spine"
                        style={{ background: sp.bg, borderRightColor: sp.edge }}
                        onClick={() => setActive(b)}
                        title={b.title + (b.author ? " — " + b.author : "")}
                      >
                        <span className="lib-spine-top" />
                        <span className="lib-spine-text">{b.title}</span>
                        {b.hebrew && <span className="lib-spine-heb">{b.hebrew}</span>}
                        <span className="lib-spine-bottom" />
                      </button>
                    );
                  })}
                </div>
                <div className="lib-shelf-board" />
              </div>
            </section>
          ))}
        </div>
      )}

      {/* Visor de leitura */}
      {active && (
        <div className="lib-reader-backdrop" onClick={(e) => e.target === e.currentTarget && setActive(null)}>
          <div className="lib-reader">
            <header className="lib-reader-head">
              <div className="lib-reader-titlewrap">
                <div className="lib-reader-cat">{active.category}{active.author ? " · " + active.author : ""}</div>
                <h3 className="lib-reader-title">{active.title}</h3>
                {active.description && <p className="lib-reader-desc">{active.description}</p>}
              </div>
              <button className="lib-reader-close" onClick={() => setActive(null)} title="Fechar">✕</button>
            </header>
            <div className="lib-reader-body">
              {libraryEmbedUrl(active.url) ? (
                <>
                  <iframe
                    src={libraryEmbedUrl(active.url)}
                    title={active.title}
                    className="lib-reader-frame"
                    allow="autoplay; encrypted-media"
                    allowFullScreen
                  />
                  {/* Cobre o botão "abrir no Drive" no canto */}
                  <div className="lib-reader-cover" />
                </>
              ) : (
                <div className="lib-empty"><p>Link inválido.</p></div>
              )}
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

window.LibraryPage = LibraryPage;
