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

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

:root {
  --brand: #78B491;
  --brand-soft: #eef8ee;
  --brand-border: #c8e6c9;
}
body {
  background: #f4f5f8;
  font-family: Vazir, IRANSans, Tahoma;
}

#public-resolutions-app {
  direction: rtl;
  max-width: 1150px;
  margin: 30px auto;
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 14px rgba(0,0,0,0.10);
  font-family: Vazir, IRANSans, Tahoma;
}

.public-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18px;
}

.public-title {
  color: var(--brand);
  font-size: 20px;
  font-weight: 900;
  margin: 0;
}

.public-filters {
  background: var(--brand-soft);
  border: 1px solid var(--brand-border);
  border-radius: 14px;
  padding: 14px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 16px;
}

.public-field {
  flex: 1 1 180px;
}

.public-field label {
  display: block;
  font-weight: 800;
  font-size: 13px;
  margin-bottom: 5px;
  color: #2f6f35;
}

.public-field input,
.public-field select {
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #d1d5db;
  border-radius: 9px;
  padding: 8px 10px;
  font-family: inherit;
  font-size: 13px;
  background: #fff;
}

.public-field input:focus,
.public-field select:focus {
  outline: none;
  border-color: var(--brand);
  box-shadow: 0 0 5px rgba(120,180,145,.35);
}

.public-table-wrap {
  width: 100%;
  overflow-x: auto;
  border-radius: 14px;
  border: 1px solid #e5e7eb;
}

#publicTable {
  width: 100%;
  min-width: 850px;
  border-collapse: collapse;
  background: #fff;
  font-size: 13px;
}

#publicTable th {
  background: #e8f5e9;
  color: #2f6f35;
  border: 1px solid #c8e6c9;
  padding: 10px;
  text-align: center;
  font-weight: 900;
}

#publicTable td {
  border: 1px solid #e5e7eb;
  padding: 9px 10px;
  text-align: center;
  vertical-align: middle;
}

#publicTable td.title-cell {
  text-align: right;
  line-height: 2;
  white-space: pre-wrap;
}

#publicTable tbody tr:nth-child(even) {
  background: #f5fbf5;
}

#publicTable tbody tr:hover {
  background: #e8f5e9;
  transition: .2s;
}

.public-empty,
.public-loading,
.public-error {
  text-align: center;
  padding: 18px;
  border-radius: 12px;
  margin-top: 14px;
  font-weight: 800;
}

public-loading {
  background: #eef8ee;
  color: #2f6f35;
  border: 1px solid #c8e6c9;
}
.public-empty {
  background: #eef8ee;
  color: #2f6f35;
  border: 1px solid #c8e6c9;
}

.public-error {
  background: #fff2f2;
  color: #b91c1c;
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-track {
  background: #eef8ee;
}

::-webkit-scrollbar-thumb {
  background: #78B491;
  border-radius: 20px;
}

::-webkit-scrollbar-thumb:hover {
  background: #5cae61;
}
</style>

<div id="public-resolutions-app">
  <div class="public-header">
    <h1 class="public-title">📌 مصوبات عمومی</h1>
  </div>

  <div class="public-filters">
    <div class="public-field">
      <label>جستجو در عنوان مصوبه</label>
      <input type="text" id="searchText" placeholder="مثلاً بخشی از عنوان مصوبه">
    </div>

    <div class="public-field">
      <label>کمیته</label>
      <select id="committeeFilter">
        <option value="">همه کمیته‌ها</option>
      </select>
    </div>

    <div class="public-field">
      <label>تاریخ جلسه</label>
      <input type="text" id="dateFilter" placeholder="مثلاً 1405/03/24">
    </div>
  </div>

  <div id="publicStatus" class="public-loading">در حال بارگذاری مصوبات عمومی...</div>

  <div class="public-table-wrap" style="display:none;" id="publicTableWrap">
    <table id="publicTable">
      <thead>
        <tr>
          <th style="width:5%;">ردیف</th>
          <th style="width:18%;">کمیته</th>
          <th style="width:12%;">تاریخ جلسه</th>
          <th style="width:35%;">عنوان مصوبه</th>
          <th style="width:12%;">مسئول پیگیری</th>
          <th style="width:12%;">مسئول اجرا</th>
          <th style="width:10%;">مهلت مقرر</th>
        </tr>
      </thead>
      <tbody id="publicBody"></tbody>
    </table>
  </div>
</div>

<script>
(function () {
  const PUBLIC_RESOLUTIONS_PAGE_ID = 109513356;
  const PUBLIC_RESOLUTIONS_FILE = "public_resolutions.json";

  const BASE = (() => {
    try {
      if (window.AJS && typeof AJS.contextPath === "function") return AJS.contextPath();
    } catch (e) {}

    const m = location.pathname.match(/^(.+?)\/pages\//);
    return m ? m[1] : "";
  })();

  const baseUrl =
    (window.AJS && window.AJS.params && (window.AJS.params.baseURL || window.AJS.params.baseUrl)) ||
    (location.origin + BASE);

  let allRows = [];

  const statusBox = document.getElementById("publicStatus");
  const tableWrap = document.getElementById("publicTableWrap");
  const tbody = document.getElementById("publicBody");
  const searchText = document.getElementById("searchText");
  const committeeFilter = document.getElementById("committeeFilter");
  const dateFilter = document.getElementById("dateFilter");

  function safeText(v) {
    v = String(v || "");
    var amp = String.fromCharCode(38);

    v = v.replace(/&/g, amp + "amp;");
    v = v.replace(/</g, amp + "lt;");
    v = v.replace(/>/g, amp + "gt;");
    v = v.replace(/"/g, amp + "quot;");
    v = v.replace(/'/g, amp + "#39;");

    return v;
  }

  function normalize(v) {
    return String(v || "")
      .replace(/\u200c/g, "")
      .replace(/\s+/g, " ")
      .trim();
  }

  function toPersianDigits(v) {
    return String(v || "").replace(/\d/g, function (d) {
      return "۰۱۲۳۴۵۶۷۸۹"[d];
    });
  }

  async function loadJSON(pageId, filename) {
    try {
      const directUrl =
        `${BASE}/download/attachments/${pageId}/${encodeURIComponent(filename)}?api=v2&cb=${Date.now()}`;

      const r1 = await fetch(directUrl, {
        credentials: "include",
        headers: { Accept: "application/json,text/plain,*/*" }
      });

      if (r1.ok) {
        const txt = await r1.text();
        if (txt && txt.trim()) return JSON.parse(txt);
      }
    } catch (e1) {
      console.warn("direct loadJSON failed:", e1);
    }

    try {
      const metaUrl =
        `${BASE}/rest/api/content/${pageId}/child/attachment?filename=${encodeURIComponent(filename)}&expand=version`;

      const r2 = await fetch(metaUrl, {
        credentials: "include",
        headers: { Accept: "application/json" }
      });

      if (!r2.ok) return [];

      const meta = await r2.json();
      const att = meta && meta.results && meta.results[0] ? meta.results[0] : null;

      if (!att || !att._links || !att._links.download) return [];

      let dl = att._links.download;
      let downloadUrl = dl.indexOf("http") === 0 ? dl : (baseUrl + dl);
      downloadUrl += (downloadUrl.indexOf("?") >= 0 ? "&" : "?") + "cb=" + Date.now();

      const r3 = await fetch(downloadUrl, {
        credentials: "include",
        headers: { Accept: "application/json,text/plain,*/*" }
      });

      if (!r3.ok) return [];

      const txt = await r3.text();
      if (!txt || !txt.trim()) return [];

      return JSON.parse(txt);
    } catch (e2) {
      console.error("loadJSON error:", e2);
      return [];
    }
  }

  async function pageExists(pageId) {
    pageId = String(pageId || "").trim();

    if (!pageId) return false;

    try {
      const res = await fetch(`${baseUrl}/rest/api/content/${encodeURIComponent(pageId)}`, {
        credentials: "include",
        headers: { Accept: "application/json" }
      });

      return res.ok;
    } catch (e) {
      return false;
    }
  }

  async function getAttachmentByName(pageId, filename) {
    try {
      const url =
        `${BASE}/rest/api/content/${pageId}/child/attachment?filename=${encodeURIComponent(filename)}&expand=version`;

      const r = await fetch(url, {
        credentials: "include",
        headers: { Accept: "application/json" }
      });

      if (!r.ok) return null;

      const j = await r.json();
      return j.results && j.results[0] ? j.results[0] : null;
    } catch (e) {
      console.error("getAttachmentByName error:", e);
      return null;
    }
  }

  async function updateData(pageId, attachmentId, file, filename) {
    const fd = new FormData();
    fd.append("file", file, filename);

    const r = await fetch(`${BASE}/rest/api/content/${pageId}/child/attachment/${attachmentId}/data`, {
      method: "POST",
      credentials: "include",
      headers: {
        "X-Atlassian-Token": "no-check",
        Accept: "application/json"
      },
      body: fd
    });

    if (!r.ok) {
      throw new Error(await r.text());
    }
  }

  async function uploadNew(pageId, file, filename) {
    const fd = new FormData();
    fd.append("file", file, filename);

    const r = await fetch(`${BASE}/rest/api/content/${pageId}/child/attachment`, {
      method: "POST",
      credentials: "include",
      headers: {
        "X-Atlassian-Token": "no-check",
        Accept: "application/json"
      },
      body: fd
    });

    if (!r.ok) {
      throw new Error(await r.text());
    }
  }

  async function savePublicRows(rows) {
    const blob = new Blob([JSON.stringify(rows, null, 2)], {
      type: "application/json"
    });

    const existing = await getAttachmentByName(PUBLIC_RESOLUTIONS_PAGE_ID, PUBLIC_RESOLUTIONS_FILE);

    if (existing) {
      await updateData(PUBLIC_RESOLUTIONS_PAGE_ID, existing.id, blob, PUBLIC_RESOLUTIONS_FILE);
    } else {
      await uploadNew(PUBLIC_RESOLUTIONS_PAGE_ID, blob, PUBLIC_RESOLUTIONS_FILE);
    }
  }

  async function removeDeletedMeetingRows(rows) {
    const validRows = [];

    for (const r of rows) {
      if (!r || !String(r.title || "").trim()) continue;

      const pageId = String(r.pageId || "").trim();

      if (!pageId) continue;

      const exists = await pageExists(pageId);

      if (exists) {
        validRows.push(r);
      }
    }

    return validRows;
  }

  function fillCommitteeFilter(rows) {
    const oldValue = committeeFilter.value || "";

    const committees = Array.from(new Set(
      rows.map(r => normalize(r.committee)).filter(Boolean)
    )).sort();

    committeeFilter.innerHTML =
      `<option value="">همه کمیته‌ها</option>` +
      committees.map(c => `<option value="${safeText(c)}">${safeText(c)}</option>`).join("");

    committeeFilter.value = oldValue;
  }

  function getFilteredRows() {
    const q = normalize(searchText.value);
    const c = normalize(committeeFilter.value);
    const d = normalize(dateFilter.value);

    return allRows.filter(function (r) {
      const title = normalize(r.title);
      const committee = normalize(r.committee);
      const meetingDate = normalize(r.meetingDate);

      if (q && !title.includes(q)) return false;
      if (c && committee !== c) return false;
      if (d && !meetingDate.includes(d)) return false;

      return true;
    });
  }

  function render() {
    const rows = getFilteredRows();

    tbody.innerHTML = "";

    if (!rows.length) {
      tableWrap.style.display = "none";
      statusBox.style.display = "block";
      statusBox.className = "public-empty";
      statusBox.textContent = "موردی برای نمایش وجود ندارد.";
      return;
    }

    rows.forEach(function (r, index) {
      const tr = document.createElement("tr");

      tr.innerHTML = `
        <td>${toPersianDigits(index + 1)}</td>
        <td>${safeText(r.committee || "")}</td>
        <td>${safeText(toPersianDigits(r.meetingDate || ""))}</td>
        <td class="title-cell">${safeText(r.title || "")}</td>
        <td>${safeText(r.followup || "")}</td>
        <td>${safeText(r.executor || "")}</td>
        <td>${safeText(toPersianDigits(r.deadline || ""))}</td>
      `;

      tbody.appendChild(tr);
    });

    statusBox.style.display = "none";
    tableWrap.style.display = "block";
  }

  async function loadPublicResolutions() {
    statusBox.style.display = "block";
    statusBox.className = "public-loading";
    statusBox.textContent = "در حال بارگذاری مصوبات عمومی...";
    tableWrap.style.display = "none";

    try {
      const data = await loadJSON(PUBLIC_RESOLUTIONS_PAGE_ID, PUBLIC_RESOLUTIONS_FILE);
      const rows = Array.isArray(data) ? data : [];

      const validRows = await removeDeletedMeetingRows(rows);

      allRows = validRows;

      if (validRows.length !== rows.length) {
        await savePublicRows(validRows);
      }

      fillCommitteeFilter(allRows);
      render();

    } catch (e) {
      console.error(e);
      statusBox.style.display = "block";
      statusBox.className = "public-error";
      statusBox.textContent = "خطا در بارگذاری مصوبات عمومی.";
      tableWrap.style.display = "none";
    }
  }

  searchText.addEventListener("input", render);
  committeeFilter.addEventListener("change", render);
  dateFilter.addEventListener("input", render);

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