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

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

:root {
  --brand: #bd2b76;
  --brand-soft: #fff5fb;
  --brand-border: #f5c7e2;
}

body {
  background: #f4f5f8;
  font-family: Vazir, IRANSans, Tahoma;
}

#public-resolutions-app {
  direction: rtl;
  max-width: 1100px;
  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: space-between;
  gap: 12px;
  margin-bottom: 18px;
}

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

.public-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.public-btn {
  border: none;
  background: var(--brand);
  color: #fff;
  border-radius: 9px;
  padding: 8px 14px;
  cursor: pointer;
  font-family: inherit;
  font-size: 13px;
}

.public-btn:hover {
  opacity: 0.9;
}

.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;
}

.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(189,43,118,0.25);
}

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

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

#publicTable th {
  background: #f5f6fb;
  color: #1f2933;
  border: 1px solid #e5e7eb;
  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: #fafafa;
}

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

.public-loading {
  background: #f8fafc;
  color: #334155;
}

.public-empty {
  background: #fff7ed;
  color: #9a3412;
}

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

.public-link {
  color: #2563eb;
  font-weight: 800;
  text-decoration: none;
}

.public-link:hover {
  text-decoration: underline;
}
</style>

<div id="public-resolutions-app">
  <div class="public-header">
    <h1 class="public-title">📌 مصوبات عمومی</h1>
    <div class="public-actions">
      <button type="button" class="public-btn" id="refreshPublicBtn">🔄 بروزرسانی</button>
    </div>
  </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>
          <th style="width:8%;">صورتجلسه</th>
        </tr>
      </thead>
      <tbody id="publicBody"></tbody>
    </table>
  </div>
</div>

<script>
(function () {
  const PUBLIC_RESOLUTIONS_PAGE_ID = 120520717;
  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");
  const refreshBtn = document.getElementById("refreshPublicBtn");

  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 load 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 [];
    }
  }

  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 pageId = r.pageId || "";
      const pageLink = pageId
        ? `${baseUrl}/pages/viewpage.action?pageId=${encodeURIComponent(pageId)}`
        : "";

      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>
        <td>
          ${
            pageLink
              ? `<a class="public-link" href="${pageLink}" target="_self">مشاهده</a>`
              : ""
          }
        </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);
      allRows = Array.isArray(data) ? data : [];

      allRows = allRows.filter(function (r) {
        return r && String(r.title || "").trim();
      });

      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);
  refreshBtn.addEventListener("click", loadPublicResolutions);

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