<!-- فونت وزیر -->
<link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazir-font@v30.1.0/dist/font-face.css" rel="stylesheet" type="text/css" />

<h1 style="text-align:center; font-family:Vazir, Tahoma; color:#333;font-weight:600;">مستندات اعتبار بخشی</h1>

<!-- ردیف جستجو و فیلترها -->
<div id="search-filters" style="display:flex; justify-content:center; flex-wrap:wrap; gap:10px; margin:30px 0;">
  <input type="text" id="search" placeholder="جستجو بر اساس عنوان"
         style="flex:1 1 300px; max-width:400px; padding:10px 15px; border:none; background:#f3f3f3; border-radius:30px; font-size:14px; outline:none; text-align:right; font-family:Vazir, Tahoma; min-width:150px;">

  <select id="filter-mahvar" style="flex:0 1 150px; padding:10px 15px; border-radius:25px; border:1px solid #ccc; font-family:Vazir, Tahoma; font-size:14px; background:#fff; cursor:pointer;">
    <option value="">انتخاب محور</option>
  </select>

  <select id="filter-zirmohvar" style="flex:0 1 150px; padding:10px 15px; border-radius:25px; border:1px solid #ccc; font-family:Vazir, Tahoma; font-size:14px; background:#fff; cursor:pointer;">
    <option value="">انتخاب زیرمحور</option>
  </select>
</div>

<!-- کانتینر سه بخش -->
<div id="sections-container" style="padding:0 40px 60px; direction:rtl;"></div>

<!-- پیام وقتی چیزی پیدا نشد -->
<div id="no-result" style="display:none; text-align:center; color:#00A9C3; font-weight:600; font-size:16px; margin-top:20px;">
  هیچ سندی پیدا نشد.
</div>

<style>
  .card {
    background:#fff; border-radius:18px; box-shadow:0 4px 10px rgba(0,0,0,0.1);
    padding:20px; display:flex; align-items:center; justify-content:space-between;
    flex-direction:row-reverse; font-family:Vazir, Tahoma; transition:all 0.3s ease;
  }
  .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 ul { margin:0; padding-right:15px; list-style:disc; font-size:13px; color:#555; }
  .open-btn { display:inline-block; background:#00A9C3; color:#fff; border:none; border-radius:25px; padding:4px 18px; font-size:13px; text-decoration:none; margin-top:12px; cursor:pointer; }
  .open-btn:hover { background:#0090a8; }
  .card-icon { background:#f7f7f7; border-radius:16px; padding:12px; display:flex; align-items:center; justify-content:center; }
  .card-icon img { width:2cm; height:2cm; }
  .card:hover { transform:scale(1.03); background:#fdfdfd; }

  @media(max-width:900px){
    .section-grid{grid-template-columns:1fr;}
    #search-filters { flex-direction:column; align-items:center; }
    #search-filters input, #search-filters select { flex:1 1 auto; max-width:300px; }
  }
</style>

<script>
  const pageId = "85045112";
  const fileName = "form-data.json";
  let docs = [];
  let __allAttachmentsForDebug = []; // برای دیباگ

  /* ================== نرمال‌سازی قوی ================== */
  function normalize(name){
    return (name || "")
      .toLowerCase()
      .replace(/\u200c/g, "")            // نیم‌فاصله
      .replace(/\s+/g, "")              // فاصله‌ها
      .replace(/[ي]/g, "ی")
      .replace(/[ك]/g, "ک")
      .replace(/[ٔ]/g, "")
      .replace(/[ـ]/g, "")
      .replace(/[\(\)\[\]\{\}]/g, "")   // پرانتزها
      .replace(/[_\-–—]/g, "")          // underscore و خط‌ها
      .replace(/[\.٬،؛:!؟"']/g, "")     // علائم رایج
      .trim();
  }

  function stripExt(s){
    const t = (s || "").trim();
    const i = t.lastIndexOf(".");
    return i > 0 ? t.slice(0, i) : t;
  }

  function removeCopySuffix(s){
    // حذف (1) یا (2) و ... آخر اسم
    return (s || "").replace(/\(\d+\)\s*$/g, "").trim();
  }

  /* ================== بخش‌ها ================== */
  const sections = [
    { title: "رهبری و مدیریت", value: "رهبری و مدیریت" },
    { title: "مراقبت و درمان", value: "مراقبت و درمان" },
    { title: "حمایت از گیرنده خدمت", value: "حمایت از گیرنده خدمت" }
  ];

  const zirmohvarOptions = {
    "رهبری و مدیریت": [
      "رهبری و مدیریت کیفیت",
      "مدیریت خطر، حوادث و بلایا",
      "مدیریت منابع انسانی و سلامت حرفه‌ای",
      "مدیریت خدمات پرستاری",
      "فناوری و مدیریت اطلاعات سلامت",
      "بهداشت محیط",
      "مدیریت تجهیزات پزشکی"
    ],
    "مراقبت و درمان": [
      "مراقبت‌های عمومی بالینی",
      "مراقبت‌های حاد و اورژانس",
      "مراقبت‌های جراحی و بیهوشی",
      "مراقبت‌های مادر و نوزاد",
      "پیشگیری و کنترل عفونت",
      "مدیریت دارویی",
      "خدمات تصویربرداری",
      "خدمات آزمایشگاه",
      "طب انتقال خون",
      "خدمات سرپایی"
    ],
    "حمایت از گیرنده خدمت": [
      "تأمین تسهیلات برای گیرنده خدمت",
      "احترام به حقوق گیرنده خدمت"
    ]
  };

  /* ================== آیکن‌ها ================== */
  const sanadIcons = {
    "آیین": "https://kb.h-soft.ir/download/thumbnails/85045112/آیین نامه.png",
    "پروتکل": "https://kb.h-soft.ir/download/thumbnails/85045112/پروتکل.png",
    "خط": "https://kb.h-soft.ir/download/thumbnails/85045112/خط مشی.png",
    "دستور": "https://kb.h-soft.ir/download/thumbnails/85045112/دستورالعمل.png",
    "راهنما": "https://kb.h-soft.ir/download/thumbnails/85045112/راهنما.png",
    "روش": "https://kb.h-soft.ir/download/thumbnails/85045112/روش اجرایی.png",
    "فلوچارت": "https://kb.h-soft.ir/download/thumbnails/85045112/فلوچارت.png",
    "کتابچه": "https://kb.h-soft.ir/download/thumbnails/85045112/کتابچه.png",
    "default": "https://kb.h-soft.ir/download/thumbnails/85045112/سند.png"
  };

  function detectSanadIcon(type){
    const t = (type || "").toLowerCase();
    const k = Object.keys(sanadIcons).find(key => t.includes(key.toLowerCase()));
    return k ? sanadIcons[k] : sanadIcons.default;
  }

  /* ================== گرفتن descendant attachments با pagination ================== */
  async function fetchAllDescAttachments(rootPageId){
    const all = [];
    let next = `/rest/api/content/${rootPageId}/descendant/attachment?limit=200`;

    while (next) {
      const res = await fetch(next, { credentials: "include" });
      if (!res.ok) throw new Error("Failed to load descendant attachments: " + res.status);
      const data = await res.json();

      if (data.results && data.results.length) all.push(...data.results);
      next = data?._links?.next ? data._links.next : null;
    }
    return all;
  }

  /* ================== پیدا کردن URL فایل با Match فازی ================== */
  function findFileUrlForDoc(doc, attachmentIndex){
    // attachmentIndex:
    // {
    //   map: { [normKey]: url },
    //   list: [ {titleNorm, url, titleRaw} ]
    // }

    const raw = (doc.document_file_name || "").trim();
    const docName = (doc.document_name || "").trim();

    const variants = [
      raw,
      removeCopySuffix(raw),
      stripExt(raw),
      stripExt(removeCopySuffix(raw)),
      docName,
      stripExt(docName),
      removeCopySuffix(docName),
      stripExt(removeCopySuffix(docName))
    ]
    .filter(Boolean)
    .map(v => normalize(v))
    .filter(Boolean);

    // 1) Match مستقیم در Map
    for (const k of variants) {
      if (attachmentIndex.map[k]) return attachmentIndex.map[k];
    }

    // 2) Match فازی: contains دوطرفه
    // اولویت: جایی که title شامل کلید باشد
    for (const k of variants) {
      const hit = attachmentIndex.list.find(a => a.titleNorm.includes(k));
      if (hit) return hit.url;
    }
    // بعد: کلید شامل title باشد (برای حالت‌هایی که title کوتاه‌تر است)
    for (const k of variants) {
      const hit = attachmentIndex.list.find(a => k.includes(a.titleNorm));
      if (hit) return hit.url;
    }

    return null;
  }

  /* ================== دریافت JSON + پیوست‌ها ================== */
  async function loadJSON(){
    try {
      const allAtt = await fetchAllDescAttachments(pageId);
      __allAttachmentsForDebug = allAtt;

      // index ساختن
      const attachmentIndex = { map: {}, list: [] };

      allAtt.forEach(a => {
        const titleRaw = (a.title || "").trim();
        const url = new URL(a._links.download, window.location.origin).href;

        const keys = [
          titleRaw,
          removeCopySuffix(titleRaw),
          stripExt(titleRaw),
          stripExt(removeCopySuffix(titleRaw))
        ].map(x => normalize(x)).filter(Boolean);

        keys.forEach(k => attachmentIndex.map[k] = url);

        attachmentIndex.list.push({
          titleRaw,
          titleNorm: normalize(titleRaw),
          url
        });
      });

      // پیدا کردن JSON
      const jsonAtt = allAtt.find(a => (a.title || "").trim() === fileName);
      if (!jsonAtt) {
        console.warn(`JSON attachment "${fileName}" not found in descendants of pageId=${pageId}`);
        docs = [];
        populateMahvarFilter();
        renderSections();
        return;
      }

      const jsonUrl = new URL(jsonAtt._links.download, window.location.origin).href;
      const jsonText = await fetch(jsonUrl, { credentials:"include" }).then(r => r.text());

      docs = JSON.parse(jsonText).map(d => {
        const fileUrl = findFileUrlForDoc(d, attachmentIndex);
        return { ...d, _fileUrl: fileUrl };
      });

      populateMahvarFilter();
      renderSections();

      // دیباگ: دقیقاً کدام‌ها پیدا نشده
      const missing = docs.filter(x => !x._fileUrl).map(x => ({
        document_name: x.document_name,
        document_file_name: x.document_file_name
      }));
      if (missing.length) {
        console.warn("Missing fileUrl for docs:", missing);
        console.warn("Sample attachment titles (first 30):",
          __allAttachmentsForDebug.slice(0, 30).map(a => a.title)
        );
      }

    } catch (e) {
      console.error(e);
      docs = [];
      populateMahvarFilter();
      renderSections();
    }
  }

  /* ================== فیلترها ================== */
  function populateMahvarFilter(){
    const sel = document.getElementById("filter-mahvar");
    if (sel.dataset.filled === "1") return;

    sections.forEach(s => {
      const o = document.createElement("option");
      o.value = s.value;
      o.textContent = s.title;
      sel.appendChild(o);
    });

    sel.dataset.filled = "1";
  }

  function updateZirmohvarFilter(){
    const mahvar = document.getElementById("filter-mahvar").value;
    const sel = document.getElementById("filter-zirmohvar");
    sel.innerHTML = '<option value="">انتخاب زیرمحور</option>';
    (zirmohvarOptions[mahvar] || []).forEach(z => {
      const o = document.createElement("option");
      o.value = z;
      o.textContent = z;
      sel.appendChild(o);
    });
  }

  /* ================== کارت ================== */
  function createCard(doc){
  const card = document.createElement("div");
  card.className = "card";

  const pageUrl = `/pages/viewpage.action?pageId=${doc.page_id}`;

  card.innerHTML = `
    <div class="card-content">
      <h3>${doc.document_name || ""}</h3>
      <ul>
        <li>زیرمحور: ${doc.zirmohvar || "-"}</li>
        <li>نوع سند: ${doc.noe_sanad || "-"}</li>
        <li>شماره استاندارد: ${doc.standard_no || "-"}</li>
        <li>تاریخ بازنگری: ${doc.date || "-"}</li>
      </ul>

      ${
        doc.page_id
          ? `<a href="${pageUrl}" target="_blank" class="open-btn">مشاهده</a>`
          : `<span class="open-btn" style="background:#ccc">صفحه ندارد</span>`
      }
    </div>

    <div class="card-icon">
      <img src="${detectSanadIcon(doc.noe_sanad)}">
    </div>
  `;

  return card;
}


  /* ================== رندر ================== */
  function renderSections(){
    const search = (document.getElementById("search").value || "").toLowerCase();
    const m = document.getElementById("filter-mahvar").value;
    const z = document.getElementById("filter-zirmohvar").value;

    const container = document.getElementById("sections-container");
    container.innerHTML = "";
    let found = false;

    sections.forEach(sec => {
      const list = docs.filter(d =>
        d.mahvar === sec.value &&
        (!search || (d.document_name || "").toLowerCase().includes(search)) &&
        (!m || d.mahvar === m) &&
        (!z || d.zirmohvar === z)
      );

      if (!list.length) return;
      found = true;

      const grid = document.createElement("div");
      grid.className = "section-grid";
      grid.style.display = "grid";
      grid.style.gridTemplateColumns = "repeat(2,1fr)";
      grid.style.gap = "20px";

      [...list].reverse().forEach(d => grid.appendChild(createCard(d)));

      const h2 = document.createElement("h2");
      h2.textContent = sec.title;
      h2.style.textAlign = "center";

      const hr = document.createElement("hr");
      hr.style.border = "3px solid #00A9C3";
      hr.style.width = "80px";
      hr.style.margin = "0 auto 20px";

      container.append(h2, hr, grid);
    });

    document.getElementById("no-result").style.display = found ? "none" : "block";
  }

  /* ================== رویدادها ================== */
  document.getElementById("search").addEventListener("input", renderSections);
  document.getElementById("filter-mahvar").addEventListener("change", () => {
    updateZirmohvarFilter();
    renderSections();
  });
  document.getElementById("filter-zirmohvar").addEventListener("change", renderSections);

  loadJSON();
</script>