/* Ficha de libro: layout 2 columnas, datos técnicos, CTA Amazon, relacionados. */
(function () {
  const { useEffect } = React;

  function trackAmazon(book) {
    try { if (window.gtag) window.gtag("event", "amazon_click", { book_asin: book.asin, book_title: book.title }); } catch (e) {}
  }

  function fmtDate(iso) {
    try { return new Date(iso).toLocaleDateString("es-ES", { year: "numeric", month: "long" }); }
    catch (e) { return iso; }
  }

  function Detail({ slug, navigate }) {
    const book = window.FUN_BOOKS.find(b => b.slug === slug);
    useEffect(() => { window.scrollTo(0, 0); }, [slug]);
    if (!book) {
      return (
        <main className="wrap" style={{ padding: "120px 22px", textAlign: "center" }}>
          <h1 className="section-title">No encontramos ese libro</h1>
          <button className="btn" style={{ marginTop: 20 }} onClick={() => navigate("libros")}>Volver al catálogo</button>
        </main>
      );
    }

    const related = window.FUN_BOOKS
      .filter(b => b.asin !== book.asin && (b.category === book.category || b.bands.some(x => book.bands.includes(x))))
      .sort((a, b) => (b.category === book.category) - (a.category === book.category))
      .slice(0, 3);

    const specs = [
      ["Páginas", book.pages ? `${book.pages}` : "—"],
      ["Formato", book.format],
      ["Dimensiones", book.dimensions],
      ["Publicado", fmtDate(book.publication_date)],
    ];

    return (
      <main className="detail">
        {/* Breadcrumb */}
        <div className="wrap detail-crumb">
          <a href="#/home" onClick={(e) => { e.preventDefault(); navigate("home"); }}>Inicio</a>
          <Icon name="chevron-right" size={15} />
          <a href="#/libros" onClick={(e) => { e.preventDefault(); navigate("libros"); }}>Libros</a>
          <Icon name="chevron-right" size={15} />
          <span aria-current="page">{book.title}</span>
        </div>

        <div className="wrap detail-grid">
          {/* Izquierda: portada */}
          <div className="detail-left">
            <div className="detail-cover" style={{ "--cc": book.cat.color }}>
              <Cover book={book} eager />
            </div>
          </div>

          {/* Derecha: información */}
          <div className="detail-right">
            <div className="detail-tags">
              <span className="pill pill-age">{book.age_range} años</span>
              <span className="pill" style={{ borderColor: book.cat.color, color: book.cat.color }}>
                <span className="chip-dot" style={{ background: book.cat.color }}></span>{book.category}
              </span>
            </div>
            <h1 className="detail-title">{book.title}</h1>
            <div className="detail-rating">
              <Stars value={book.rating_value} size={19} />
              <strong>{book.rating_value.toFixed(1).replace(".", ",")}</strong>
              <span>· {book.rating_count} reseñas en Amazon</span>
            </div>
            <p className="detail-lead">{book.description_short}</p>
            <p className="detail-long">{book.description_long}</p>

            <div className="detail-features">
              <h2 className="detail-h">Qué encontrarás dentro</h2>
              <ul className="feature-list">
                {book.features.map((f, i) => (
                  <li key={i}><span className="feature-check"><Icon name="check" size={15} style={{ color: "#fff" }} /></span>{f}</li>
                ))}
              </ul>
            </div>

            <div className="detail-specs">
              {specs.map(([k, v]) => (
                <div className="spec" key={k}>
                  <span className="spec-k mono">{k}</span>
                  <span className="spec-v">{v}</span>
                </div>
              ))}
            </div>

            <div className="detail-buy">
              <a href={book.amazon_url} target="_blank" rel="nofollow noopener" className="btn btn-lg buy-btn" onClick={() => trackAmazon(book)}>
                Comprar en Amazon <Icon name="external" size={20} />
              </a>
            </div>
          </div>
        </div>

        {/* Relacionados */}
        {related.length > 0 && (
          <section className="section">
            <div className="wrap">
              <div className="section-head reveal in">
                <h2 className="section-title">También te puede gustar</h2>
              </div>
              <div className="book-grid related-grid">
                {related.map(b => <BookCard key={b.asin} book={b} onOpen={() => navigate("libro/" + b.slug)} />)}
              </div>
            </div>
          </section>
        )}
      </main>
    );
  }

  window.Detail = Detail;
})();
