/* Catálogo: header, filtros (edad / categoría / buscador), grid, empty state. */
(function () {
  const { useState, useMemo, useEffect } = React;

  function BookGrid({ books, navigate }) {
    return (
      <div className="book-grid">
        {books.map((b, i) => (
          <BookCard key={b.asin} book={b} eager={i < 4} onOpen={() => navigate("libro/" + b.slug)} />
        ))}
      </div>
    );
  }
  window.BookGrid = BookGrid;

  function Filters({ q, setQ, age, setAge, cat, setCat, cats, top }) {
    return (
      <div className={"filters" + (top ? " filters-top" : "")}>
        <div className="filter-group filter-group-search">
          <label className="filter-label" htmlFor="cat-search">Buscar</label>
          <div className="search-box">
            <Icon name="search" size={19} />
            <input id="cat-search" type="search" placeholder="Título o tema…" value={q}
              onChange={(e) => setQ(e.target.value)} className="search-input" />
          </div>
        </div>
        <div className="filter-group">
          <span className="filter-label">Edad</span>
          <div className="chips">
            {window.FUN_BANDS.map(b => (
              <button key={b.id} className={"chip" + (age === b.id ? " on" : "")}
                aria-pressed={age === b.id} onClick={() => setAge(age === b.id ? null : b.id)}>
                {b.label}
              </button>
            ))}
          </div>
        </div>
        <div className="filter-group">
          <span className="filter-label">Categoría</span>
          <div className="chips">
            {cats.map(c => (
              <button key={c} className={"chip chip-cat" + (cat === c ? " on" : "")}
                aria-pressed={cat === c}
                style={cat === c ? { "--chip": window.FUN_CATS[c].color } : { "--chip": window.FUN_CATS[c].color }}
                onClick={() => setCat(cat === c ? null : c)}>
                <span className="chip-dot" style={{ background: window.FUN_CATS[c].color }}></span>{c}
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  function Catalog({ navigate }) {
    const [q, setQ] = useState("");
    const [age, setAge] = useState(null);
    const [cat, setCat] = useState(null);
    const cats = useMemo(() => Object.keys(window.FUN_CATS).filter(c => window.FUN_BOOKS.some(b => b.category === c)), []);

    const result = useMemo(() => {
      const term = q.trim().toLowerCase();
      return window.FUN_BOOKS.filter(b => {
        if (age && !b.bands.includes(age)) return false;
        if (cat && b.category !== cat) return false;
        if (term) {
          const hay = (b.title + " " + b.topics.join(" ") + " " + b.description_short + " " + b.category).toLowerCase();
          if (!hay.includes(term)) return false;
        }
        return true;
      });
    }, [q, age, cat]);

    const active = (age ? 1 : 0) + (cat ? 1 : 0) + (q ? 1 : 0);
    const clear = () => { setQ(""); setAge(null); setCat(null); };

    return (
      <main className="catalog">
        <div className="catalog-head">
          <div className="wrap">
            <span className="kicker reveal in">Catálogo completo</span>
            <h1 className="catalog-title reveal in">Todos nuestros libros</h1>
            <p className="catalog-count reveal in">
              Tenemos <strong>{window.FUN_BOOKS.length} libros</strong> para ti, elegidos uno a uno.
            </p>
          </div>
          <Deco.Sparkle color="var(--mostaza)" size={28} style={{ position: "absolute", top: "30%", right: "12%" }} className="float-b" />
          <Deco.Sparkle color="var(--menta)" size={22} style={{ position: "absolute", bottom: "26%", right: "22%" }} className="float-c" />
        </div>

        <div className="wrap catalog-body">
          {/* Filtros en barra superior */}
          <div className="catalog-filters-top">
            <Filters {...{ q, setQ, age, setAge, cat, setCat, cats, top: true }} />
            {active > 0 && (
              <button className="clear-btn" onClick={clear}><Icon name="x" size={16} /> Quitar filtros ({active})</button>
            )}
          </div>

          <section className="catalog-main">
            <div className="catalog-result-bar">
              <span className="mono">{result.length} {result.length === 1 ? "resultado" : "resultados"}</span>
            </div>
            {result.length > 0 ? (
              <BookGrid books={result} navigate={navigate} />
            ) : (
              <div className="empty">
                <div className="empty-art" aria-hidden="true">
                  <Deco.Blob color="var(--beige-2)" style={{ width: 180 }} />
                  <Icon name="search" size={48} style={{ position: "absolute", color: "var(--carbon-soft)" }} />
                </div>
                <h3 className="empty-title">No encontramos libros con esos filtros</h3>
                <p className="empty-text">Prueba a quitar algún filtro o a buscar otra palabra.</p>
                <button className="btn" onClick={clear}>Ver todos los libros</button>
              </div>
            )}
          </section>
        </div>
      </main>
    );
  }

  window.Catalog = Catalog;
})();
