<h1 style="text-align:center; font-family:Vazir, Tahoma; color:#333;font-weight:600;">
  📚 کتابخانه
</h1>

<!-- نوار ابزار / جستجو -->
<div id="book-toolbar" style="max-width:900px; margin:0 auto 10px; padding:0 20px; display:flex; justify-content:flex-start; align-items:center; gap:10px; direction:rtl;">
  <input id="book-search" type="text"
         placeholder="جستجو در عنوان، حیطه، نویسنده یا سال..."
         style="flex:1; padding:8px 12px; border-radius:999px; border:1px solid #ddd; font-family:Vazir, Tahoma; font-size:13px; outline:none;">
</div>

<div id="book-grid" style="display:grid; grid-template-columns:repeat(3, 1fr); gap:20px; padding:10px 40px 60px; direction:rtl;"></div>




<style>

@font-face {
font-family: "IRANSans";
src: url("/download/attachments/106496142/IRANSansXVF.woff2") format("woff2");
}

@font-face {
font-family: "Vazir";
src: url("/download/attachments/106496142/Vazir-Regular.woff2") format("woff2");
}

  .card {
    background:#fff;
    border-radius:18px;
    box-shadow:0 4px 10px rgba(0,0,0,0.1);
    padding:16px;
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    transition: all 0.3s ease;
    flex-direction: row-reverse;
    font-family: Vazir, Tahoma;
  }
  .card-content { flex:1; text-align:right; padding-right:15px; }
  .card-content h3 { margin:0 0 8px; font-weight:600; font-size:14px; color:#333; }
  .card-content .dot-line { font-size:13px; color:#555; margin:2px 0; }

  .download-btn {
    display:inline-block; background:#b40074; color:#fff;
    border:none; border-radius:25px; padding:4px 14px;
    font-size:12px; text-decoration:none; margin-top:8px; cursor:pointer;
  }
  .download-btn:hover { background:#d50088; }

  .card-icon {
    background:#f7f7f7;
    border-radius:16px;
    padding:12px;
    display:flex;
    align-items:center;
    justify-content:center;
  }
  .card-icon img { width: 2cm; height: 2cm; }

  @media (max-width:900px){
    #book-grid{grid-template-columns:1fr;}
  }
</style>

<script>
(() => {
  /* ===== تنظیمات ===== */
  const LIB_ID             = "nikan-Sepid_library";     // با صفحه ثبت یکی باشد
  const FORCED_DATA_PAGE_ID = 106496142;          // صفحه‌ی فرم ثبت / ریشه دیتا
  const JSON_FILE_NAME     = `library-${LIB_ID}.json`;
  /* =================== */

  // تشخیص BASE (context path)
  function detectBase(){
    try{ if (window.AJS && typeof AJS.contextPath==="function") return AJS.contextPath(); }catch(e){}
    const meta = document.querySelector('meta[name="ajs-context-path"]')?.content;
    if (meta) return meta;
    const m = location.pathname.match(/^(.*)\/(pages|display|download)\//);
    if (m) return m[1];
    return '';
  }

  const BASE        = detectBase();
  const DATA_PAGE_ID = FORCED_DATA_PAGE_ID;   // چون می‌دانیم دیتا روی صفحه‌ی فرم ثبت است
  const ENDPOINT_ATTACH_LIST =
    `${BASE}/rest/api/content/${DATA_PAGE_ID}/child/attachment`;

  const grid        = document.getElementById("book-grid");
  const searchInput = document.getElementById("book-search");

  let allBooks = [];

  function createBookCard(book){
    const authorsBlock = (book.authors && book.authors.length)
      ? book.authors.map(a=>`<div class="dot-line">• ${a}</div>`).join("")
      : `<div class="dot-line">• بدون نویسنده</div>`;

    const card = document.createElement("div");
    card.className = "card";
    card.innerHTML = `
      <div class="card-content">
        <h3>${book.title || "-"}</h3>
        <div class="dot-line">• حیطه: ${book.category || "-"}</div>
        ${authorsBlock}
        <div class="dot-line">• تاریخ انتشار: ${book.year || "-"}</div>
        ${book.fileUrl ? `<a href="${book.fileUrl}" target="_blank" class="download-btn">دانلود</a>` : ""}
      </div>
      <div class="card-icon">
        <img src="https://kb.h-soft.ir/download/thumbnails/106496142/12%20-%20Copy.png?api=v2&nonce=1787955078206" alt="کتاب">
      </div>
    `;
    return card;
  }

  function renderBooks(list){
    grid.innerHTML = "";
    if (!list.length){
      grid.innerHTML = `
        <div style="grid-column:1/-1; text-align:center; font-family:Vazir, Tahoma; color:#777;
                    background:#fafafa; border:1px dashed #e4e4e4; padding:14px; border-radius:18px;">
          کتابی با این فیلتر پیدا نشد.
        </div>`;
      return;
    }
    list.forEach(b => grid.appendChild(createBookCard(b)));
  }

  async function getExistingAttachmentMeta() {
    const url = `${ENDPOINT_ATTACH_LIST}?filename=${encodeURIComponent(JSON_FILE_NAME)}&expand=results`;
    const res = await fetch(url, { credentials: "include" });
    if (!res.ok) return null;
    const data = await res.json();
    if (!data.results || !data.results.length) return null;
    return data.results[0];
  }

  async function loadJsonFromAttachment() {
    const meta = await getExistingAttachmentMeta();
    if (!meta) return { libId: LIB_ID, books: [] };

    const downloadLink = meta._links && meta._links.download;
    if (!downloadLink) return { libId: LIB_ID, books: [] };

    const res = await fetch(BASE + downloadLink, { credentials: "include" });
    if (!res.ok) throw new Error("خطا در دانلود JSON: " + res.status);
    const text = await res.text();
    if (!text.trim()) return { libId: LIB_ID, books: [] };

    try {
      const parsed = JSON.parse(text.replace(/^\uFEFF/, '').trim());
      if (!parsed.books) parsed.books = [];
      if (!parsed.libId) parsed.libId = LIB_ID;
      return parsed;
    } catch(e) {
      console.error("JSON parse error:", e);
      return { libId: LIB_ID, books: [] };
    }
  }

  async function loadBooks() {
    try {
      const data = await loadJsonFromAttachment();
      allBooks = data.books || [];
      if (!allBooks.length) {
        grid.innerHTML = `
          <div style="grid-column:1/-1; text-align:center; font-family:Vazir, Tahoma; color:#777;
                      background:#fafafa; border:1px dashed #e4e4e4; padding:14px; border-radius:18px;">
            هنوز کتابی ثبت نشده است.
          </div>`;
        return;
      }
      renderBooks(allBooks);
    } catch (e) {
      console.error(e);
      grid.innerHTML = `
        <div style="grid-column:1/-1; text-align:center; font-family:Vazir, Tahoma; color:#c00;
                    background:#fff5f5; border:1px dashed #f5b5b5; padding:14px; border-radius:18px;">
          خطا در خواندن کتاب‌ها: ${e.message}
        </div>`;
    }
  }

  // سرچ روی آرایه‌ی allBooks
  function handleSearch(){
    const q = (searchInput.value || "").trim().toLowerCase();
    if (!q){
      renderBooks(allBooks);
      return;
    }

    const filtered = allBooks.filter(b => {
      const title    = (b.title    || "").toLowerCase();
      const category = (b.category || "").toLowerCase();
      const year     = (b.year     || "").toLowerCase();
      const authors  = Array.isArray(b.authors) ? b.authors.join(" ") : (b.authors || "");
      const authorsL = authors.toLowerCase();

      const haystack = `${title} ${category} ${year} ${authorsL}`;
      return haystack.includes(q);
    });

    renderBooks(filtered);
  }

  searchInput.addEventListener("input", handleSearch);

  loadBooks();
})();
</script>