// Book Detail — read-only view of book metadata, summary, review, highlights, comments

const DETAIL_EASE = "cubic-bezier(.2,.8,.2,1)";
const DETAIL_RM = matchMedia("(prefers-reduced-motion: reduce)").matches;

// One masked line: its inner element slides up through an overflow-hidden mask.
function Rise({ children, className }) {
  return <div className="rise-m"><div className={className} data-rise>{children}</div></div>;
}

// Cover that bleeds in as ragged ink blots (SVG mask + displacement filter).
const INK_BLOBS = [[127, 220, 0], [287, 400, 120], [211, 80, 220], [76, 507, 300], [338, 167, 360], [219, 573, 420], [194, 313, 180]];
function InkPoster({ book, startDelay }) {
  const [state, setState] = React.useState(book.cover ? "loading" : "err");
  const [ratio, setRatio] = React.useState(1.5);
  const circles = React.useRef([]);
  React.useEffect(() => {
    if (!book.cover) { setState("err"); return; }
    setState("loading");
    const im = new Image();
    im.referrerPolicy = "no-referrer";
    im.onload = () => { setRatio(im.naturalHeight / im.naturalWidth || 1.5); setState("ok"); };
    im.onerror = () => setState("err");
    im.src = book.cover;
  }, [book.cover]);
  React.useEffect(() => {
    if (state !== "ok") return;
    let raf = 0;
    const start = performance.now() + startDelay - (DETAIL_RM ? 5000 : 0);
    const tick = (now) => {
      const el = now - start;
      circles.current.forEach((c, i) => {
        if (!c) return;
        const p = Math.min(1, Math.max(0, (el - INK_BLOBS[i][2]) / 1250));
        c.setAttribute("r", 620 * (1 - Math.pow(1 - p, 3)));
      });
      if (el < 2400) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [state, book.id]);
  if (state === "err") return <Cover book={book} size="xl" />;
  if (state === "loading") return <div className="ink-poster ink-poster-wait"></div>;
  return (
    <svg className="ink-poster" viewBox={`0 0 400 ${400 * ratio}`} aria-hidden="true">
      <defs>
        <filter id="bd-ink" filterUnits="userSpaceOnUse" x="-200" y="-200" width="800" height="1000">
          <feTurbulence type="fractalNoise" baseFrequency=".011" numOctaves="3" seed="7" result="n" />
          <feDisplacementMap in="SourceGraphic" in2="n" scale="100" xChannelSelector="R" yChannelSelector="G" />
        </filter>
        <mask id="bd-ink-mask" maskUnits="userSpaceOnUse" x="-200" y="-200" width="800" height="1000">
          <g filter="url(#bd-ink)" fill="#fff">
            {INK_BLOBS.map((b, i) => <circle key={i} ref={(el) => { circles.current[i] = el; }} cx={b[0]} cy={b[1]} r="0" />)}
          </g>
        </mask>
      </defs>
      <g mask="url(#bd-ink-mask)">
        <image href={book.cover} x="0" y="0" width="400" height={400 * ratio} preserveAspectRatio="none" />
      </g>
    </svg>
  );
}

function BookDetail({ book, onBack, density }) {
  const [tab, setTab] = React.useState("overview");
  const [commentCount, setCommentCount] = React.useState(() => (book.comments || []).length);
  const rootRef = React.useRef(null);
  const tabsRef = React.useRef(null);
  const fromSheet = React.useRef(!!window.__sheetOpened).current;
  const activeTabRef = React.useRef(null);

  React.useEffect(() => {
    setTab("overview");
    setCommentCount((book.comments || []).length);
  }, [book.id]);

  // masked text rise; the paper sheet overlay (if any) is removed once we have painted
  React.useLayoutEffect(() => {
    window.__sheetOpened = false;
    const base = DETAIL_RM ? 0 : fromSheet ? 620 : 80;
    [...rootRef.current.querySelectorAll("[data-rise]")].forEach((el, i) => {
      const a = el.animate(
        [{ transform: "translateY(110%)" }, { transform: "translateY(0)" }],
        { duration: DETAIL_RM ? 1 : 900, delay: DETAIL_RM ? 0 : base + i * 75, easing: DETAIL_EASE, fill: "both" }
      );
      a.onfinish = () => { a.cancel(); el.parentElement.classList.add("rise-done"); };
    });
    requestAnimationFrame(() => document.querySelectorAll(".sheet-grow").forEach((s) => s.remove()));
  }, [book.id]);

  React.useEffect(() => {
    if (activeTabRef.current && tabsRef.current) {
      activeTabRef.current.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" });
    }
  }, [tab]);

  const progressPct = book.pages ? Math.round((book.progress / book.pages) * 100) : 0;
  const genres = (book.genres || []).filter(g => g !== "Hard copy" && g !== "Ebook");
  const shopLinks = Array.isArray(book.shopLinks) && book.shopLinks.length
    ? book.shopLinks
    : book.shopUrl ? [{ label: "Mua sách", url: book.shopUrl }] : [];

  return (
    <div className="detail" ref={rootRef}>
      <div className="detail-topbar">
        <button className="box lbl detail-back" onClick={onBack}>← Tủ sách</button>
      </div>

      <div className="detail-hero">
        <div className="detail-cover-wrap">
          <InkPoster book={book} startDelay={fromSheet ? 520 : 100} />
        </div>

        <div className="detail-meta">
          <Rise><div className="eyebrow">{genres.join(" · ") || "Chưa phân loại"}</div></Rise>
          <Rise><h1 className="detail-title">{book.title}</h1></Rise>
          <Rise><div className="detail-author">{book.author ? `của ${book.author}` : "—"}</div></Rise>

          <Rise><div className="rating-row">
            <span className="rating-label">Đánh giá</span>
            <div className="stars-large">
              {[1,2,3,4,5].map((n) => (
                <span key={n} className={"star-btn " + (n <= book.rating ? "star-on" : "")}>★</span>
              ))}
            </div>
          </div></Rise>

          <Rise><dl className="meta-grid">
            <div><dt>Định dạng</dt><dd>{book.type || "—"}</dd></div>
            <div><dt>Số trang</dt><dd>{book.pages ? `${book.pages} trang` : "—"}</dd></div>
          </dl></Rise>

          {genres.length > 0 && (
            <Rise><div className="category-editor">
              <span className="category-label mono">Thể loại</span>
              <div className="category-chips">
                {genres.map(cat => (
                  <span key={cat} className="cat-chip">{cat}</span>
                ))}
              </div>
            </div></Rise>
          )}

          {shopLinks.length > 0 && (
            <Rise><div className="shop-links">
              <span className="category-label mono">Mua sách</span>
              <div className="shop-links-list">
                {shopLinks.map((link, i) => {
                  const preset = SHOP_PRESETS.find(p => p.label.toLowerCase() === (link.label || "").toLowerCase())
                    || { label: link.label || "Shop", icon: "↗", color: "#6a6a6a" };
                  return (
                    <a key={i} href={link.url} target="_blank" rel="noopener noreferrer" className="shop-btn">
                      <span className="shop-btn-icon" style={{ background: preset.color }}>{preset.icon}</span>
                      <span className="shop-btn-label">{link.label}</span>
                      <span className="affiliate-tag-sm">affiliate</span>
                      <svg width="11" height="11" viewBox="0 0 11 11" fill="none" className="shop-btn-ext">
                        <path d="M4 2h5v5M9 2L3 8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </a>
                  );
                })}
              </div>
            </div></Rise>
          )}
        </div>
      </div>

      <Rise><div className="detail-tabs" ref={tabsRef}>
        {[
          { id: "overview", label: "Giới thiệu" },
          { id: "review", label: "Cảm nhận" },
          { id: "highlights", label: `Trích dẫn (${(book.highlights||[]).length})` },
          { id: "comments", label: `Bình luận (${commentCount})` },
          { id: "notes", label: "Ghi chú" },
        ].map((t) => (
          <button
            key={t.id}
            ref={tab === t.id ? activeTabRef : null}
            className={"detail-tab " + (tab === t.id ? "detail-tab-on" : "")}
            onClick={() => setTab(t.id)}
          >{t.label}</button>
        ))}
      </div></Rise>

      <Rise><div className="detail-body">
        {tab === "overview" && (
          <div className="detail-section">
            <h3 className="section-title">Giới thiệu sách</h3>
            {book.summary ? (
              <p className="section-body">{book.summary}</p>
            ) : (
              <p className="section-body muted">Chưa có giới thiệu.</p>
            )}

            {(book.highlights || []).slice(0, 2).length > 0 && (
              <React.Fragment>
                <h3 className="section-title" style={{ marginTop: 40 }}>Trích dẫn gần đây</h3>
                {(book.highlights || []).slice(0, 2).map((h, i) => (
                  <blockquote key={i} className="highlight">
                    <p>{h.text}</p>
                    {h.page && <cite>— tr. {h.page}</cite>}
                  </blockquote>
                ))}
              </React.Fragment>
            )}
          </div>
        )}

        {tab === "review" && (
          <div className="detail-section">
            <h3 className="section-title">Cảm nhận của tôi</h3>
            {book.review ? (
              <p className="section-body review-body">{book.review}</p>
            ) : (
              <p className="section-body muted">Chưa có cảm nhận.</p>
            )}
          </div>
        )}

        {tab === "highlights" && (
          <div className="detail-section">
            <h3 className="section-title">Trích dẫn & câu hay</h3>
            {(book.highlights || []).length === 0 ? (
              <p className="section-body muted">Chưa có trích dẫn nào.</p>
            ) : (
              (book.highlights || []).map((h, i) => (
                <blockquote key={i} className="highlight">
                  <p>{h.text}</p>
                  {h.page && <cite>— tr. {h.page}</cite>}
                </blockquote>
              ))
            )}
          </div>
        )}

        {tab === "comments" && (
          <window.Comments book={book} onCountChange={setCommentCount} />
        )}

        {tab === "notes" && (
          <div className="detail-section">
            <h3 className="section-title">Ghi chú</h3>
            {book.notes ? (
              <p className="section-body" style={{ whiteSpace: "pre-wrap" }}>{book.notes}</p>
            ) : (
              <p className="section-body muted">Không có ghi chú.</p>
            )}
          </div>
        )}
      </div></Rise>
    </div>
  );
}

function formatDate(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  return d.toLocaleDateString("vi-VN", { day: "numeric", month: "short", year: "numeric" });
}

const SHOP_PRESETS = [
  { label: "Tiki", icon: "T", color: "#1A94FF" },
  { label: "Fahasa", icon: "F", color: "#C92127" },
  { label: "Shopee", icon: "S", color: "#EE4D2D" },
  { label: "Nhã Nam", icon: "N", color: "#3F7A3D" },
  { label: "Kim Đồng", icon: "K", color: "#E5A02E" },
  { label: "Amazon", icon: "A", color: "#FF9900" },
  { label: "Hiệu sách độc lập", icon: "•", color: "#8a5a3a" },
  { label: "Khác", icon: "↗", color: "#6a6a6a" },
];

window.BookDetail = BookDetail;
window.formatDate = formatDate;
