{% extends "base.html" %}
{% block title %}Resource access — {{ config.INSTANCE_NAME }}{% endblock %}

{% block content %}
<style>
  .container:has(.ax-page) { max-width: none; padding: 24px 16px; }
  .ax-page { max-width: 1400px; margin: 0 auto; padding: 0; }
  .ax-toolbar {
    display: flex; justify-content: space-between; align-items: center;
    gap: 16px; margin-bottom: 20px; flex-wrap: wrap;
  }
  .ax-title { margin: 0; font-size: 22px; font-weight: 600; }
  .ax-sub { margin: 0; font-size: 13px; color: var(--text-secondary, #6b7280); }

  .ax-layout {
    display: grid; grid-template-columns: 320px 1fr; gap: 20px;
    align-items: start;
  }
  @media (max-width: 900px) { .ax-layout { grid-template-columns: 1fr; } }

  .ax-card {
    background: var(--surface, #fff);
    border: 1px solid var(--border, #e5e7eb);
    border-radius: 12px;
    overflow: hidden;
  }
  .ax-card-head {
    display: flex; align-items: center; justify-content: space-between;
    padding: 14px 16px; border-bottom: 1px solid var(--border, #e5e7eb);
    background: var(--border-light, #f9fafb);
  }
  .ax-card-head h3 { margin: 0; font-size: 14px; font-weight: 600; }

  /* Groups list */
  .group-list { list-style: none; margin: 0; padding: 0; }
  .group-item {
    display: flex; align-items: center; gap: 10px;
    padding: 12px 14px; border-bottom: 1px solid var(--border-light, #f3f4f6);
    cursor: pointer; transition: background 0.12s;
  }
  .group-item:last-child { border-bottom: none; }
  .group-item:hover { background: var(--border-light, #fafafa); }
  .group-item.is-active { background: #eef2ff; }
  .group-item.is-active .group-name { color: var(--primary, #4338ca); }
  .group-dot {
    width: 8px; height: 8px; border-radius: 50%;
    background: #cbd5e1; flex-shrink: 0;
  }
  .group-item.is-active .group-dot { background: var(--primary, #6366f1); }
  .group-meta { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; }
  .group-name { font-size: 13px; font-weight: 500; color: var(--text-primary, #111827); }
  .group-name-sub {
    display: block;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
    font-size: 10px; color: var(--text-secondary, #6b7280);
    margin-top: 2px;
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  .origin-chip {
    display: inline-block;
    padding: 1px 6px; border-radius: 999px;
    font-size: 9px; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.4px;
    margin-left: 6px; vertical-align: middle;
  }
  .origin-system     { background: #fef3c7; color: #92400e; }
  .origin-custom     { background: #ede9fe; color: #6d28d9; }
  .origin-google_sync { background: #dcfce7; color: #166534; }
  .group-desc {
    font-size: 11px; color: var(--text-secondary, #6b7280);
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  .group-count {
    font-size: 10px; font-weight: 600; padding: 2px 7px; border-radius: 999px;
    background: #e0e7ff; color: #3730a3;
  }
  .group-row-actions { display: flex; gap: 4px; opacity: 0; transition: opacity 0.15s; }
  .group-item:hover .group-row-actions { opacity: 1; }
  .group-item.is-active .group-row-actions { opacity: 1; }
  .group-act-btn {
    background: transparent; border: 1px solid var(--border, #e5e7eb);
    color: var(--text-secondary, #6b7280);
    font-size: 10px; padding: 2px 6px; border-radius: 4px; cursor: pointer;
  }
  .group-act-btn:hover { color: var(--text-primary, #111827); border-color: #cbd5e1; background: #fff; }
  .group-act-btn.danger:hover { color: #b91c1c; border-color: #fecaca; background: #fef2f2; }

  .ax-empty {
    padding: 28px 16px; text-align: center;
    font-size: 13px; color: var(--text-secondary, #6b7280);
  }

  /* Right side — resource type sections + per-block collapsibles.
     Each resource type gets a colored left stripe + faint tinted banner
     so the three-level hierarchy (type → block/bucket → item) reads at
     a glance. Colors cycle 4-wide via :nth-child so adding more resource
     types in app/resource_types.py works without touching CSS. */
  .rt-section + .rt-section {
    border-top: 8px solid var(--border-light, #f1f5f9);
  }
  .rt-section-head {
    padding: 16px 20px;
    font-size: 12px; font-weight: 700; letter-spacing: 0.6px;
    text-transform: uppercase; color: #1e293b;
    border-bottom: 1px solid var(--border, #e5e7eb);
    border-left: 4px solid #0073D1;
    background: linear-gradient(to right,
      rgba(0, 115, 209, 0.10), rgba(0, 115, 209, 0.02));
  }
  .rt-section:nth-child(4n+2) > .rt-section-head {
    border-left-color: #10b981;
    background: linear-gradient(to right,
      rgba(16, 185, 129, 0.10), rgba(16, 185, 129, 0.02));
  }
  .rt-section:nth-child(4n+3) > .rt-section-head {
    border-left-color: #f59e0b;
    background: linear-gradient(to right,
      rgba(245, 158, 11, 0.10), rgba(245, 158, 11, 0.02));
  }
  .rt-section:nth-child(4n+4) > .rt-section-head {
    border-left-color: #f43f5e;
    background: linear-gradient(to right,
      rgba(244, 63, 94, 0.10), rgba(244, 63, 94, 0.02));
  }
  .mp-block { border-bottom: 1px solid var(--border-light, #f3f4f6); }
  .mp-block:last-child { border-bottom: none; }
  .mp-block-head {
    display: flex; align-items: center; gap: 10px;
    padding: 12px 16px; background: var(--border-light, #fafafa);
    cursor: pointer; user-select: none;
  }
  .mp-block-head h4 { margin: 0; font-size: 13px; font-weight: 600; color: var(--text-primary, #111827); }
  .mp-block-head .count {
    font-size: 11px; padding: 2px 7px; border-radius: 999px;
    background: #e0e7ff; color: #3730a3; font-weight: 600;
  }
  .mp-block-head .spacer { flex: 1; }
  .mp-block-head .chev { transition: transform 0.15s; color: #9ca3af; }
  .mp-block.is-collapsed .item-grid { display: none; }
  .mp-block.is-collapsed .mp-block-head .chev { transform: rotate(-90deg); }
  .bulk-btn {
    font-size: 11px; padding: 4px 8px; border: 1px solid var(--border, #e5e7eb);
    background: var(--surface, #fff); color: var(--text-secondary, #6b7280);
    border-radius: 6px; cursor: pointer;
  }
  .bulk-btn:hover { color: var(--text-primary, #111827); border-color: #cbd5e1; }

  .item-grid {
    display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 0; padding: 0;
  }
  .item-cell {
    display: flex; align-items: flex-start; gap: 10px;
    padding: 10px 16px;
    border-right: 1px solid var(--border-light, #f3f4f6);
    border-bottom: 1px solid var(--border-light, #f3f4f6);
    cursor: pointer; transition: background 0.1s;
  }
  .item-cell:hover { background: var(--border-light, #fafafa); }
  .item-cell input[type="checkbox"] {
    margin-top: 2px; width: 15px; height: 15px; cursor: pointer;
    accent-color: var(--primary, #6366f1);
  }
  .item-cell.is-granted { background: #f5f3ff; }
  .item-cell.is-granted:hover { background: #ede9fe; }
  .ic-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
  .ic-name {
    font-size: 13px; font-weight: 500; color: var(--text-primary, #111827);
    word-break: break-word;
  }
  .ic-meta { font-size: 11px; color: var(--text-secondary, #6b7280); }
  .ic-src {
    display: inline-block; padding: 1px 6px; border-radius: 4px;
    background: #f3f4f6; color: #374151; font-size: 10px; font-weight: 500;
    text-transform: uppercase; letter-spacing: 0.3px; margin-left: 4px;
  }
  /* v39: SYSTEM pill — same amber palette as the .origin-system chip on
     /admin/groups so the "system" semantic reads consistently across the
     admin surface. */
  .ic-system-pill {
    display: inline-block; padding: 1px 6px; border-radius: 999px;
    background: #fef3c7; color: #92400e; font-size: 10px; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.4px; margin-left: 4px;
  }
  .item-cell.is-system { background: #fffbeb; }
  .item-cell.is-system:hover { background: #fef3c7; }
  .item-cell input[type="checkbox"]:disabled { cursor: not-allowed; opacity: 0.7; }
  .ic-desc {
    font-size: 11px; color: var(--text-secondary, #6b7280);
    margin-top: 2px; line-height: 1.35;
    display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .ax-hint {
    padding: 14px 16px; font-size: 12px; color: var(--text-secondary, #6b7280);
    background: #fffbeb; border-bottom: 1px solid #fde68a;
  }
  .ax-hint a { color: var(--primary, #6366f1); }

  .ax-filter {
    padding: 10px 16px; border-bottom: 1px solid var(--border, #e5e7eb);
    background: var(--surface, #fff);
  }
  .ax-filter input {
    width: 100%; padding: 7px 10px 7px 30px;
    border: 1px solid var(--border, #e5e7eb); border-radius: 6px;
    font-size: 12px;
    background: #fff url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2'><circle cx='11' cy='11' r='8'/><path d='m21 21-4.35-4.35'/></svg>") no-repeat 9px center;
  }

  .ax-btn {
    padding: 6px 12px; border-radius: 6px; font-size: 12px; font-weight: 500;
    border: 1px solid var(--border, #e5e7eb); background: var(--surface, #fff);
    cursor: pointer;
  }
  .ax-btn:hover { background: var(--border-light, #f9fafb); }
  .ax-btn.primary { background: var(--primary, #6366f1); color: #fff; border-color: var(--primary, #6366f1); }
  .ax-btn.primary:hover { filter: brightness(1.05); }

  /* Modal */
  .modal-backdrop {
    position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55);
    display: none; align-items: center; justify-content: center; z-index: 1000;
    padding: 16px;
  }
  .modal-backdrop.is-open { display: flex; }
  .modal-card {
    background: var(--surface, #fff); border-radius: 12px;
    padding: 24px; width: 100%; max-width: 480px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
    max-height: 90vh; overflow-y: auto;
  }
  .modal-card h3 { margin: 0 0 6px; font-size: 17px; font-weight: 600; }
  .modal-card p.sub { margin: 0 0 18px; font-size: 13px; color: var(--text-secondary, #6b7280); }
  .modal-card label {
    display: block; font-size: 12px; font-weight: 500;
    color: var(--text-secondary, #6b7280); margin: 12px 0 6px;
  }
  .modal-card input[type="text"], .modal-card textarea {
    width: 100%; padding: 9px 12px; border: 1px solid var(--border, #e5e7eb);
    border-radius: 8px; font-size: 13px; box-sizing: border-box;
    background: var(--surface, #fff); color: var(--text-primary, #111827);
    font-family: inherit;
  }
  .modal-card textarea { min-height: 60px; resize: vertical; }
  .modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 20px; }
  .modal-btn {
    padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 500;
    border: 1px solid var(--border, #e5e7eb); background: var(--surface, #fff);
    cursor: pointer;
  }
  .modal-btn.primary { background: var(--primary, #6366f1); color: #fff; border-color: var(--primary, #6366f1); }
  .modal-btn.danger { background: #dc2626; color: #fff; border-color: #dc2626; }

  .toast-stack {
    position: fixed; bottom: 24px; right: 24px; z-index: 2000;
    display: flex; flex-direction: column; gap: 8px; pointer-events: none;
  }
  .toast {
    background: #111827; color: #fff; padding: 10px 16px;
    border-radius: 8px; font-size: 13px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
    opacity: 0; transform: translateY(8px); transition: opacity 0.2s, transform 0.2s;
    pointer-events: auto; max-width: 380px;
  }
  .toast.show { opacity: 1; transform: translateY(0); }
  .toast.success { background: #047857; }
  .toast.error { background: #b91c1c; }

  /* Tabs inside detail panel */
  .ax-tabs {
    display: flex; gap: 0;
    border-bottom: 1px solid var(--border, #e5e7eb);
    background: var(--surface, #fff);
    padding: 0 4px;
  }
  .ax-tab {
    padding: 11px 18px;
    background: transparent; border: 0; border-bottom: 2px solid transparent;
    font-size: 13px; font-weight: 500;
    color: var(--text-secondary, #6b7280);
    cursor: pointer; transition: color 0.12s, border-color 0.12s;
  }
  .ax-tab:hover { color: var(--text-primary, #111827); }
  .ax-tab.is-active {
    color: var(--primary, #4338ca);
    border-bottom-color: var(--primary, #6366f1);
  }
  .ax-pane { display: none; }
  .ax-pane.is-active { display: block; }

  /* Members table */
  .members-table-wrap { padding: 0; }
  .members-table { width: 100%; border-collapse: collapse; font-size: 13px; }
  .members-table thead th {
    text-align: left; padding: 10px 16px;
    background: var(--border-light, #f9fafb);
    border-bottom: 1px solid var(--border, #e5e7eb);
    font-weight: 600; color: var(--text-secondary, #6b7280);
    font-size: 11px; text-transform: uppercase; letter-spacing: 0.4px;
  }
  .members-table tbody td {
    padding: 10px 16px;
    border-bottom: 1px solid var(--border-light, #f3f4f6);
  }
  .members-table tbody tr:last-child td { border-bottom: none; }
  .members-table tbody tr:hover { background: var(--border-light, #fafafa); }
  .source-badge {
    display: inline-block; padding: 2px 7px; border-radius: 999px;
    font-size: 10px; font-weight: 600;
    text-transform: uppercase; letter-spacing: 0.4px;
  }
  .source-admin { background: #fef3c7; color: #92400e; }
  .source-google_sync { background: #dcfce7; color: #166534; }
  .source-system_seed { background: #e0e7ff; color: #3730a3; }

  /* Form for add-member */
  .ax-form {
    display: flex; gap: 8px; align-items: flex-end;
    padding: 14px 16px;
    border-top: 1px solid var(--border-light, #f3f4f6);
    background: var(--border-light, #f9fafb);
  }
  .ax-field { display: flex; flex-direction: column; gap: 4px; flex: 1; }
  .ax-field label {
    font-size: 11px; text-transform: uppercase;
    letter-spacing: 0.4px; color: var(--text-secondary, #6b7280); font-weight: 600;
  }
  .ax-field input {
    padding: 7px 10px;
    border: 1px solid var(--border, #e5e7eb); border-radius: 6px;
    font-size: 13px; background: var(--surface, #fff);
  }
</style>

<div class="ax-page">
  <div class="ax-toolbar">
    <div>
      <h2 class="ax-title">Resource access</h2>
      <p class="ax-sub">Pick a group on the left, check resources on the right to grant access.
        Manage groups and members on <a href="/admin/groups">Groups</a>.</p>
    </div>
  </div>

  <div class="ax-layout">
    <!-- LEFT: Groups (read-only picker — CRUD lives on /admin/groups) -->
    <div class="ax-card" id="groups-card">
      <div class="ax-card-head">
        <h3>User groups</h3>
        <a class="ax-btn" href="/admin/groups" title="Manage groups">Manage →</a>
      </div>
      <ul class="group-list" id="group-list"></ul>
      <div class="ax-empty" id="group-empty" style="display:none;">
        No groups yet.<br>
        Create one on <a href="/admin/groups">Groups</a>.
      </div>
    </div>

    <!-- RIGHT: Group detail with tabs -->
    <div class="ax-card" id="detail-card">
      <div class="ax-card-head">
        <div style="display:flex; flex-direction:column; gap:2px; min-width:0; flex:1;">
          <h3 id="detail-title" style="display:flex; align-items:center;">Select a group</h3>
          <span id="detail-mapped" class="group-name-sub" style="display:none;"></span>
        </div>
        <span id="detail-sub" style="font-size:11px; color: var(--text-secondary, #6b7280); flex-shrink:0;"></span>
      </div>

      <!-- Resources panel (no tab strip — this page is grants-only) -->
      <section data-pane="resources" style="display:none;">
        <div class="ax-hint" id="ax-hint" style="display:none;">
          No resources have been registered yet. Add a marketplace on the
          <a href="/admin/marketplaces">Marketplaces</a> page and run a sync.
        </div>
        <div class="ax-filter" id="resources-filter-wrap" style="display:none;">
          <input id="resources-filter" type="search" placeholder="Filter by name, marketplace, category…" autocomplete="off">
        </div>
        <div id="resources-body"></div>
      </section>

      <div class="ax-empty" id="detail-empty">
        Select a group on the left to assign resource grants.
      </div>
    </div>
  </div>
</div>


<div class="toast-stack" id="toast-stack" aria-live="polite"></div>

<script>
const OVERVIEW_API = "/api/admin/access-overview";
const GROUPS_API = "/api/admin/groups";
const GRANTS_API = "/api/admin/grants";
// Server-injected so the sidebar can derive a friendly display name from
// google-sync groups whose `name` is the raw Workspace email — same trick
// /admin/groups uses; keeping the surface identical here.
const GOOGLE_GROUP_PREFIX = {{ config.AGNES_GOOGLE_GROUP_PREFIX | tojson }};

function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }

function deriveDisplayName(fullEmail) {
  if (!fullEmail) return "";
  const local = String(fullEmail).split("@")[0] || String(fullEmail);
  const px = (GOOGLE_GROUP_PREFIX || "").toLowerCase();
  let s = local;
  if (px && s.toLowerCase().startsWith(px)) s = s.slice(px.length);
  s = s.replace(/^[_\-\s]+/, "");
  if (!s) return local;
  return s.charAt(0).toUpperCase() + s.slice(1);
}

function toast(msg, kind = "") {
  const el = document.createElement("div");
  el.className = "toast " + kind;
  el.textContent = msg;
  document.getElementById("toast-stack").appendChild(el);
  requestAnimationFrame(() => el.classList.add("show"));
  setTimeout(() => { el.classList.remove("show"); setTimeout(() => el.remove(), 250); }, 3500);
}

function openModal(id) { document.getElementById(id).classList.add("is-open"); }
function closeModal(id) { document.getElementById(id).classList.remove("is-open"); }
document.querySelectorAll("[data-close-modal]").forEach(el =>
  el.addEventListener("click", () => closeModal(el.dataset.closeModal)));
document.querySelectorAll(".modal-backdrop").forEach(el => {
  el.addEventListener("click", e => { if (e.target === el) el.classList.remove("is-open"); });
});
document.addEventListener("keydown", e => {
  if (e.key === "Escape") document.querySelectorAll(".modal-backdrop.is-open").forEach(m => m.classList.remove("is-open"));
});

// State
let state = {
  groups: [],          // [{id, name, description, is_system, member_count, grant_count}]
  resources: [],       // [{type_key, type_display, blocks: [{id, name, items: [{resource_id, name, ...}]}]}]
  grants: [],          // [{id, group_id, resource_type, resource_id}]
  activeGroupId: null,
  filter: "",
  editingGroupId: null,
};

async function loadOverview() {
  try {
    const r = await fetch(OVERVIEW_API, { credentials: "include" });
    if (!r.ok) throw new Error("HTTP " + r.status);
    const data = await r.json();
    state.groups = data.groups;
    state.resources = data.resources;
    state.grants = data.grants;
    if (state.activeGroupId && !state.groups.find(g => g.id === state.activeGroupId)) {
      state.activeGroupId = null;
    }
    renderGroups();
    renderDetail();
  } catch (e) {
    toast("Failed to load: " + e.message, "error");
  }
}

async function selectGroup(gid) {
  state.activeGroupId = gid;
  // Update URL so the group selection is shareable / deep-linkable.
  if (gid) {
    const u = new URL(window.location.href);
    u.searchParams.set("group", gid);
    history.replaceState(null, "", u.toString());
  }
  renderGroups();
  renderDetail();
}

function renderDetail() {
  const title = document.getElementById("detail-title");
  const mapped = document.getElementById("detail-mapped");
  const sub = document.getElementById("detail-sub");
  const empty = document.getElementById("detail-empty");
  const resourcesPane = document.querySelector('[data-pane="resources"]');

  if (!state.activeGroupId) {
    title.textContent = "Select a group";
    mapped.style.display = "none";
    mapped.textContent = "";
    sub.textContent = "";
    resourcesPane.style.display = "none";
    empty.style.display = "block";
    return;
  }
  empty.style.display = "none";
  resourcesPane.style.display = "block";

  const group = state.groups.find(g => g.id === state.activeGroupId);
  if (group) {
    // Mirror the sidebar's title rules: mapped_email present → big name
    // stays canonical, email goes to the subtitle line. Plain google-sync
    // group → derive a friendly name and put the raw email below.
    let bigName = group.name;
    let subtitleText = "";
    if (group.mapped_email) {
      subtitleText = group.mapped_email;
    } else if (group.is_google_managed) {
      bigName = deriveDisplayName(group.name);
      subtitleText = group.name;
    }
    const origin = group.origin || (group.is_system ? "system" : "custom");
    title.innerHTML = `<span>${esc(bigName)}</span><span class="origin-chip origin-${esc(origin)}">${esc(origin.replace("_"," "))}</span>`;
    if (subtitleText) {
      mapped.textContent = subtitleText;
      mapped.style.display = "block";
    } else {
      mapped.style.display = "none";
      mapped.textContent = "";
    }
  } else {
    title.textContent = "Group";
    mapped.style.display = "none";
    mapped.textContent = "";
  }
  const grantedCount = state.grants.filter(g => g.group_id === state.activeGroupId).length;
  sub.textContent = `${grantedCount} resource${grantedCount === 1 ? "" : "s"} granted`;

  renderResources();
}

function renderGroups() {
  const list = document.getElementById("group-list");
  const empty = document.getElementById("group-empty");
  if (state.groups.length === 0) {
    list.innerHTML = "";
    empty.style.display = "block";
    return;
  }
  empty.style.display = "none";
  list.innerHTML = "";
  for (const g of state.groups) {
    const li = document.createElement("li");
    li.className = "group-item"
      + (state.activeGroupId === g.id ? " is-active" : "");
    li.dataset.id = g.id;
    // Origin pill — single chip mirroring /admin/groups treatment. Mapped
    // Admin/Everyone report origin='google_sync' so the chip color matches
    // their actual source of truth (Workspace), not the seed mechanism.
    const origin = g.origin || (g.is_system ? "system" : "custom");
    const originPill = `<span class="origin-chip origin-${esc(origin)}">${esc(origin.replace("_"," "))}</span>`;
    // Big-title / subtitle rules — same logic as the /admin/groups list:
    //   - mapped_email present → big = canonical name, subtitle = mapped_email
    //   - google_managed user-created group → big = derived friendly name,
    //     subtitle = full Workspace email stored as `name`
    //   - everything else → big = name, subtitle = description (or none)
    let bigName, subtitle;
    if (g.mapped_email) {
      bigName = esc(g.name);
      subtitle = `<span class="group-name-sub">${esc(g.mapped_email)}</span>`;
    } else if (g.is_google_managed) {
      bigName = esc(deriveDisplayName(g.name));
      subtitle = `<span class="group-name-sub">${esc(g.name)}</span>`;
    } else {
      bigName = esc(g.name);
      subtitle = g.description ? `<span class="group-desc">${esc(g.description)}</span>` : "";
    }
    // Compute live from state.grants — g.grant_count is a server-side
    // snapshot from /access-overview that goes stale as soon as the user
    // toggles a checkbox; reading it here would clobber refreshCounts()
    // updates whenever the sidebar re-renders (e.g. on selectGroup).
    const liveCount = state.grants.filter(gr => gr.group_id === g.id).length;
    li.innerHTML = `
      <span class="group-dot"></span>
      <div class="group-meta">
        <span class="group-name">${bigName}${originPill}</span>
        ${subtitle}
      </div>
      <span class="group-count" title="Resources granted to this group">${liveCount}</span>
    `;
    li.addEventListener("click", () => selectGroup(g.id));
    list.appendChild(li);
  }
}

function isGranted(group_id, resource_type, resource_id) {
  return state.grants.some(g =>
    g.group_id === group_id &&
    g.resource_type === resource_type &&
    g.resource_id === resource_id
  );
}

function findGrant(group_id, resource_type, resource_id) {
  return state.grants.find(g =>
    g.group_id === group_id &&
    g.resource_type === resource_type &&
    g.resource_id === resource_id
  );
}

function renderResources() {
  const body = document.getElementById("resources-body");
  const hint = document.getElementById("ax-hint");
  const filterWrap = document.getElementById("resources-filter-wrap");

  if (!state.activeGroupId) {
    body.innerHTML = "";
    hint.style.display = "none";
    filterWrap.style.display = "none";
    return;
  }

  const totalItems = state.resources.reduce(
    (acc, rt) => acc + rt.blocks.reduce((a, b) => a + b.items.length, 0), 0,
  );
  if (totalItems === 0) {
    hint.style.display = "block";
    filterWrap.style.display = "none";
    body.innerHTML = "";
    return;
  }
  hint.style.display = "none";
  filterWrap.style.display = "block";

  const ft = state.filter.trim().toLowerCase();
  body.innerHTML = "";

  for (const rt of state.resources) {
    const section = document.createElement("div");
    section.className = "rt-section";
    section.innerHTML = `<div class="rt-section-head">${esc(rt.type_display)}</div>`;

    let sectionItemCount = 0;

    for (const block of rt.blocks) {
      const items = block.items.filter(it => {
        if (!ft) return true;
        return (it.name || "").toLowerCase().includes(ft)
            || (block.name || "").toLowerCase().includes(ft)
            || (it.category || "").toLowerCase().includes(ft)
            || (it.description || "").toLowerCase().includes(ft);
      });
      if (ft && items.length === 0) continue;
      sectionItemCount += items.length;

      const grantedHere = items.filter(it =>
        isGranted(state.activeGroupId, rt.type_key, it.resource_id)).length;

      const blockEl = document.createElement("div");
      blockEl.className = "mp-block";
      blockEl.innerHTML = `
        <div class="mp-block-head" data-toggle="collapse">
          <svg class="chev" width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
            <path d="M3 4.5l3 3 3-3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <h4>${esc(block.name)}</h4>
          <span class="count">${grantedHere}/${items.length}</span>
          <span class="spacer"></span>
          <button class="bulk-btn" data-bulk="all">Grant all</button>
          <button class="bulk-btn" data-bulk="none">Revoke all</button>
        </div>
        <div class="item-grid"></div>
      `;
      const grid = blockEl.querySelector(".item-grid");
      if (items.length === 0) {
        grid.innerHTML = `<div class="ax-empty" style="grid-column: 1/-1;">No items.</div>`;
      } else {
        for (const it of items) {
          const granted = isGranted(state.activeGroupId, rt.type_key, it.resource_id);
          // v39: system plugins are pre-granted to every group by mark_system
          // and the checkbox is locked here so admins can't revoke it via
          // the UI. Backend (DELETE /api/admin/grants) also refuses, but the
          // visual lock prevents the round-trip.
          const isSystem = !!it.is_system;
          const cellClasses = "item-cell"
            + (granted ? " is-granted" : "")
            + (isSystem ? " is-system" : "");
          const sysPill = isSystem
            ? `<span class="ic-system-pill" title="Mandatory plugin — managed via /admin/marketplaces">SYSTEM</span>`
            : "";
          const cell = document.createElement("label");
          cell.className = cellClasses;
          cell.innerHTML = `
            <input type="checkbox" ${granted || isSystem ? "checked" : ""} ${isSystem ? "disabled" : ""}
                   ${isSystem ? `title="System plugin — managed via /admin/marketplaces"` : ""}>
            <div class="ic-text">
              <div>
                <span class="ic-name">${esc(it.name)}</span>
                ${it.source_type ? `<span class="ic-src">${esc(it.source_type)}</span>` : ""}
                ${sysPill}
              </div>
              ${(it.version || it.category) ? `<div class="ic-meta">
                ${it.version ? `v${esc(it.version)}` : ""}${it.version && it.category ? " · " : ""}${it.category ? esc(it.category) : ""}
              </div>` : ""}
              ${it.description ? `<div class="ic-desc">${esc(it.description)}</div>` : ""}
            </div>
          `;
          const cb = cell.querySelector("input");
          if (!isSystem) {
            cb.addEventListener("change", () => toggleGrant(cb, cell, rt.type_key, it.resource_id));
          }
          grid.appendChild(cell);
        }
      }
      blockEl.querySelector('[data-toggle="collapse"]').addEventListener("click", e => {
        if (e.target.closest("[data-bulk]")) return;
        blockEl.classList.toggle("is-collapsed");
      });
      blockEl.querySelector('[data-bulk="all"]').addEventListener("click", () =>
        bulkSet(rt.type_key, items, true));
      blockEl.querySelector('[data-bulk="none"]').addEventListener("click", () =>
        bulkSet(rt.type_key, items, false));
      section.appendChild(blockEl);
    }

    if (sectionItemCount > 0 || !ft) {
      body.appendChild(section);
    }
  }
}

async function toggleGrant(checkbox, cell, resource_type, resource_id) {
  const grant = checkbox.checked;
  checkbox.disabled = true;
  try {
    if (grant) {
      const r = await fetch(GRANTS_API, {
        method: "POST", credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          group_id: state.activeGroupId,
          resource_type, resource_id,
        }),
      });
      if (!r.ok) {
        const err = await r.json().catch(() => ({}));
        toast("Grant failed: " + (err.detail || r.status), "error");
        checkbox.checked = false;
        return;
      }
      const created = await r.json();
      state.grants.push({
        id: created.id, group_id: state.activeGroupId,
        resource_type, resource_id,
      });
      cell.classList.add("is-granted");
    } else {
      const existing = findGrant(state.activeGroupId, resource_type, resource_id);
      if (!existing) { return; }
      const r = await fetch(`${GRANTS_API}/${encodeURIComponent(existing.id)}`, {
        method: "DELETE", credentials: "include",
      });
      if (!r.ok) {
        toast("Revoke failed: " + r.status, "error");
        checkbox.checked = true;
        return;
      }
      state.grants = state.grants.filter(g => g.id !== existing.id);
      cell.classList.remove("is-granted");
    }
    refreshCounts();
  } catch (e) {
    toast("Network error: " + e.message, "error");
    checkbox.checked = !grant;
  } finally {
    checkbox.disabled = false;
  }
}

async function bulkSet(resource_type, items, grant) {
  if (!state.activeGroupId) return;
  for (const it of items) {
    // v39: skip system plugins — the API refuses to revoke them and a
    // bulk grant on a checkbox that was already auto-granted by
    // mark_system is a noop. Lets "Grant all" / "Revoke all" finish
    // cleanly without 409s littering the toast log.
    if (it.is_system) continue;
    const has = isGranted(state.activeGroupId, resource_type, it.resource_id);
    if (grant === has) continue;
    try {
      if (grant) {
        const r = await fetch(GRANTS_API, {
          method: "POST", credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            group_id: state.activeGroupId,
            resource_type, resource_id: it.resource_id,
          }),
        });
        if (!r.ok) continue;
        const created = await r.json();
        state.grants.push({
          id: created.id, group_id: state.activeGroupId,
          resource_type, resource_id: it.resource_id,
        });
      } else {
        const existing = findGrant(state.activeGroupId, resource_type, it.resource_id);
        if (!existing) continue;
        const r = await fetch(`${GRANTS_API}/${encodeURIComponent(existing.id)}`, {
          method: "DELETE", credentials: "include",
        });
        if (!r.ok) continue;
        state.grants = state.grants.filter(g => g.id !== existing.id);
      }
    } catch (_e) { /* ignore */ }
  }
  toast(`${grant ? "Grant" : "Revoke"} all applied`, "success");
  renderDetail();
  refreshCounts();
}

function refreshCounts() {
  // Group list badges + detail sub-header.
  const grantedCount = state.grants.filter(g => g.group_id === state.activeGroupId).length;
  document.getElementById("detail-sub").textContent =
    `${grantedCount} resource${grantedCount === 1 ? "" : "s"} granted`;
  document.querySelectorAll(".group-item").forEach(li => {
    const gid = li.dataset.id;
    const badge = li.querySelector(".group-count");
    if (badge) badge.textContent = state.grants.filter(g => g.group_id === gid).length;
  });
  // Per-block counts inside the rendered tree
  document.querySelectorAll(".rt-section").forEach(section => {
    const typeDisplay = section.querySelector(".rt-section-head").textContent;
    const rt = state.resources.find(r => r.type_display === typeDisplay);
    if (!rt) return;
    section.querySelectorAll(".mp-block").forEach(blockEl => {
      const blockName = blockEl.querySelector(".mp-block-head h4").textContent;
      const block = rt.blocks.find(b => b.name === blockName);
      if (!block) return;
      const visibleItems = Array.from(blockEl.querySelectorAll(".item-cell"));
      const grantedHere = visibleItems.filter(c => c.classList.contains("is-granted")).length;
      blockEl.querySelector(".mp-block-head .count").textContent =
        `${grantedHere}/${visibleItems.length}`;
    });
  });
}

// Filter (resources tab)
document.getElementById("resources-filter").addEventListener("input", e => {
  state.filter = e.target.value;
  renderResources();
});

// Pre-select a group via ?group=<id> deep-link from /admin/groups/{id}.
// Pre-filter to a table via #table:<id> deep-link from /admin/tables's
// per-row Manage access button — drops the table_id into the resource
// filter so the operator sees just that row once they pick a group.
async function bootstrap() {
  await loadOverview();
  const params = new URLSearchParams(window.location.search);
  const target = params.get("group");
  if (target && state.groups.some(g => g.id === target)) {
    selectGroup(target);
  }
  // Hash-based deep link, e.g. #table:in.c-sales.orders → pre-fill the
  // resource filter with the table_id. The filter is name-substring based
  // and tables come through with the table_id as their `name`, so this
  // narrows the visible items to just the clicked row across all groups.
  const hash = window.location.hash || "";
  if (hash.startsWith("#table:")) {
    const tableId = decodeURIComponent(hash.slice("#table:".length));
    if (tableId) {
      const filterEl = document.getElementById("resources-filter");
      if (filterEl) {
        filterEl.value = tableId;
        state.filter = tableId;
        renderResources();
      }
    }
  }
}
bootstrap();
</script>
{% endblock %}
