{% extends "dashboard_base.html" %}
{% block title %}{{ team_name }} Settings — calrs{% endblock %}
{% block dashboard_content %}
<div class="card">
  <div style="display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;">
    <h1 style="margin-bottom: 0;">{{ team_name }}</h1>
    {% if visibility == "public" %}
      <span class="badge badge-success">public</span>
    {% else %}
      <span class="badge badge-muted">private</span>
    {% endif %}
  </div>
  <p style="color: var(--text-muted); font-size: 0.875rem; margin-top: 0.25rem;">Team settings &mdash; team admins can edit these.</p>

  {% if success %}
    <div class="success" style="margin-top: 1rem; padding: 0.75rem 1rem; border-radius: var(--radius); background: var(--success-bg, #e6f9e6); color: var(--success, #2d7a2d); border: 1px solid var(--success, #2d7a2d);">{{ success }}</div>
  {% endif %}

  {% if visibility == "public" and team_slug %}
  <div style="margin-top: 1.25rem; padding: 1rem; border-radius: var(--radius); background: var(--accent-subtle, rgba(99,102,241,0.06)); border: 1px solid var(--accent-border, rgba(99,102,241,0.2));">
    <label style="display: block; font-weight: 500; margin-bottom: 0.5rem; font-size: 0.875rem;">Public URL</label>
    <p style="color: var(--text-muted); font-size: 0.8rem; margin-bottom: 0.5rem;">Anyone can book via this link.</p>
    <div style="display: flex; gap: 0.5rem; align-items: center;">
      <input type="text" id="public-url" readonly value="" style="flex: 1; font-size: 0.85rem; padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); color: var(--text); font-family: monospace;">
      <button type="button" id="copy-public-btn" class="slot-btn" style="cursor: pointer; font-weight: 600; color: var(--accent); border-color: var(--accent); white-space: nowrap;">Copy</button>
      <a id="open-public-link" href="/team/{{ team_slug }}" target="_blank" rel="noopener noreferrer" class="slot-btn" style="text-decoration: none; font-size: 0.85rem; white-space: nowrap;">Open &#8599;</a>
    </div>
  </div>
  <script>
  (function() {
    var url = window.location.origin + '/team/{{ team_slug }}';
    document.getElementById('public-url').value = url;
    document.getElementById('open-public-link').href = url;
    document.getElementById('copy-public-btn').addEventListener('click', function() {
      var btn = this;
      navigator.clipboard.writeText(url).then(function() {
        btn.textContent = 'Copied!';
        btn.style.color = 'var(--success)';
        btn.style.borderColor = 'var(--success)';
        setTimeout(function() { btn.textContent = 'Copy'; btn.style.color = 'var(--accent)'; btn.style.borderColor = 'var(--accent)'; }, 1500);
      });
    });
  })();
  </script>
  {% elif visibility == "private" and invite_token %}
  <div style="margin-top: 1.25rem; padding: 1rem; border-radius: var(--radius); background: var(--accent-subtle, rgba(99,102,241,0.06)); border: 1px solid var(--accent-border, rgba(99,102,241,0.2));">
    <label style="display: block; font-weight: 500; margin-bottom: 0.5rem; font-size: 0.875rem;">Invite link</label>
    <p style="color: var(--text-muted); font-size: 0.8rem; margin-bottom: 0.5rem;">Share this link to give people access to this private team's booking page.</p>
    <div style="display: flex; gap: 0.5rem; align-items: center;">
      <input type="text" id="invite-url" readonly value="" style="flex: 1; font-size: 0.85rem; padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); color: var(--text); font-family: monospace;">
      <button type="button" id="copy-invite-btn" class="slot-btn" style="cursor: pointer; font-weight: 600; color: var(--accent); border-color: var(--accent); white-space: nowrap;">Copy</button>
      <a id="open-invite-link" href="/team/{{ team_slug }}?invite={{ invite_token }}" target="_blank" rel="noopener noreferrer" class="slot-btn" style="text-decoration: none; font-size: 0.85rem; white-space: nowrap;">Open &#8599;</a>
    </div>
  </div>
  <script>
  (function() {
    var url = window.location.origin + '/team/{{ team_slug }}?invite={{ invite_token }}';
    document.getElementById('invite-url').value = url;
    document.getElementById('open-invite-link').href = url;
    document.getElementById('copy-invite-btn').addEventListener('click', function() {
      var btn = this;
      navigator.clipboard.writeText(url).then(function() {
        btn.textContent = 'Copied!';
        btn.style.color = 'var(--success)';
        btn.style.borderColor = 'var(--success)';
        setTimeout(function() { btn.textContent = 'Copy'; btn.style.color = 'var(--accent)'; btn.style.borderColor = 'var(--accent)'; }, 1500);
      });
    });
  })();
  </script>
  {% endif %}

  <!-- Avatar -->
  <div style="margin-top: 1.25rem;">
    <label style="display: block; font-weight: 500; margin-bottom: 0.5rem; font-size: 0.875rem;">Team avatar</label>
    <div style="display: flex; align-items: center; gap: 1rem;">
      <div style="width: 64px; height: 64px; border-radius: 50%; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 1.25rem; flex-shrink: 0; overflow: hidden;">
        {% if team_has_avatar %}
          <img src="/team-avatar/{{ team_id }}" alt="" style="width: 100%; height: 100%; object-fit: cover;">
        {% else %}
          {{ team_initials }}
        {% endif %}
      </div>
      <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
        <form method="post" action="/dashboard/teams/{{ team_id }}/avatar" enctype="multipart/form-data" style="margin: 0; display: flex; gap: 0.5rem; align-items: center;">
          <input type="file" name="avatar" accept="image/*" required style="font-size: 0.85rem;">
          <button type="submit" class="slot-btn" style="cursor: pointer; font-weight: 600; color: var(--accent); border-color: var(--accent);">Upload</button>
        </form>
        {% if team_has_avatar %}
        <form method="post" action="/dashboard/teams/{{ team_id }}/avatar/delete" style="margin: 0;">
          <button type="submit" class="slot-btn" style="cursor: pointer; font-size: 0.85rem; color: var(--error-text);">Remove</button>
        </form>
        {% endif %}
      </div>
    </div>
  </div>
</div>

<!-- Unified settings form -->
<form method="POST" id="settings-form">
  <!-- Profile section -->
  <div class="card" style="margin-top: 1.25rem;">
    <h2 style="font-size: 1rem; margin-bottom: 0.75rem;">Profile</h2>

    <div class="form-group">
      <label for="name">Team name</label>
      <input type="text" id="name" name="name" required value="{{ team_name }}" placeholder="Engineering">
    </div>

    <div class="form-group">
      <label for="slug">Slug <span class="hint">(URL-friendly identifier)</span></label>
      <input type="text" id="slug" name="slug" required value="{{ team_slug }}" placeholder="engineering" pattern="[a-z0-9\-]+" title="Lowercase letters, numbers, and dashes only">
      <span class="hint" style="font-size: 0.8rem; color: var(--text-muted); display: block; margin-top: 0.25rem;">Used in the team URL: /team/{{ team_slug }}</span>
    </div>

    <div class="form-group">
      <label for="description">Description</label>
      <div style="border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden;">
        <div class="md-toolbar" data-target="description" style="display: flex; gap: 0.25rem; padding: 0.375rem 0.5rem; background: var(--surface-hover); border-bottom: 1px solid var(--border);">
          <button type="button" data-action="bold" title="Bold" style="padding: 0.25rem 0.5rem; background: none; border: 1px solid transparent; border-radius: 3px; cursor: pointer; font-weight: 700; font-size: 0.85rem; color: var(--text); font-family: inherit; line-height: 1;">B</button>
          <button type="button" data-action="italic" title="Italic" style="padding: 0.25rem 0.5rem; background: none; border: 1px solid transparent; border-radius: 3px; cursor: pointer; font-style: italic; font-size: 0.85rem; color: var(--text); font-family: inherit; line-height: 1;">I</button>
          <button type="button" data-action="link" title="Insert link" style="padding: 0.25rem 0.5rem; background: none; border: 1px solid transparent; border-radius: 3px; cursor: pointer; font-size: 0.85rem; color: var(--text); font-family: inherit; line-height: 1;">&#128279;</button>
          <div style="flex: 1;"></div>
          <button type="button" class="md-preview-toggle" title="Toggle preview" style="padding: 0.25rem 0.5rem; background: none; border: 1px solid transparent; border-radius: 3px; cursor: pointer; font-size: 0.75rem; color: var(--text-muted); font-family: inherit; line-height: 1;">Preview</button>
        </div>
        <textarea id="description" name="description" rows="3" placeholder="Tell people about this team..." style="border: none; border-radius: 0; width: 100%; resize: vertical; padding: 0.5rem 0.75rem; font-family: inherit; font-size: 0.9rem; background: var(--surface); color: var(--text); box-sizing: border-box;">{{ team_description }}</textarea>
        <div id="description-preview" style="display: none; padding: 0.5rem 0.75rem; min-height: 4rem; font-size: 0.9rem; color: var(--text); background: var(--surface);"></div>
      </div>
      <span class="hint" style="font-size: 0.8rem; color: var(--text-muted); display: block; margin-top: 0.25rem;">Shown on the team's public booking page. Supports **bold**, *italic*, and [links](url).</span>
    </div>

    <fieldset style="border: none; padding: 0; margin: 0;">
      <legend style="font-weight: 500; font-size: 0.9rem; margin-bottom: 0.375rem;">Visibility</legend>
      <div style="display: flex; gap: 1rem;">
        <label style="display: inline-flex; align-items: center; gap: 0.375rem; padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 0.9rem; transition: all 0.15s ease;">
          <input type="radio" name="visibility" value="public" {% if visibility == "public" %}checked{% endif %} style="accent-color: var(--accent);">
          Public
        </label>
        <label style="display: inline-flex; align-items: center; gap: 0.375rem; padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 0.9rem; transition: all 0.15s ease;">
          <input type="radio" name="visibility" value="private" {% if visibility == "private" %}checked{% endif %} style="accent-color: var(--accent);">
          Private
        </label>
      </div>
      <span class="hint" style="font-size: 0.8rem; color: var(--text-muted); display: block; margin-top: 0.25rem;">Public teams are listed on the team profile page. Private teams require an invite link to access.</span>
    </fieldset>
  </div>

  <!-- Members section -->
  <div class="card" style="margin-top: 1.25rem;">
    <h2 style="font-size: 1rem; margin-bottom: 0.75rem;">Members</h2>
    <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1rem;">Manage who belongs to this team. Add individual users or link OIDC groups for automatic sync.</p>

    <!-- Unified member + group list -->
    <div id="members-list" style="margin-bottom: 1rem;">
      {% for m in members %}
      <div class="member-row" data-id="{{ m.id }}" data-type="user" style="display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; {% if not loop.last or linked_groups %}border-bottom: 1px solid var(--border);{% endif %}">
        <div style="width: 32px; height: 32px; border-radius: 50%; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 0.7rem; flex-shrink: 0; overflow: hidden;">
          {% if m.has_avatar %}
            <img src="/avatar/{{ m.id }}" alt="" style="width: 100%; height: 100%; object-fit: cover;">
          {% else %}
            {{ m.initials }}
          {% endif %}
        </div>
        <span style="font-size: 0.9rem; flex: 1;">{{ m.name }}</span>
        {% if m.source == "group" %}<span class="badge badge-muted">OIDC</span>{% endif %}
        <select class="role-select" data-user-id="{{ m.id }}" style="font-size: 0.8rem; padding: 0.25rem 0.5rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); color: var(--text); cursor: pointer; font-family: inherit;">
          <option value="member" {% if m.role != "admin" %}selected{% endif %}>Member</option>
          <option value="admin" {% if m.role == "admin" %}selected{% endif %}>Admin</option>
        </select>
        {% if m.source != "group" %}
        <button type="button" class="slot-btn remove-member-btn" data-user-id="{{ m.id }}" style="font-size: 0.75rem; color: var(--error-text); cursor: pointer;">Remove</button>
        {% endif %}
      </div>
      {% endfor %}
      {% for g in linked_groups %}
      <div class="member-row" data-id="{{ g.id }}" data-type="group" style="display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; {% if not loop.last %}border-bottom: 1px solid var(--border);{% endif %}">
        <div style="width: 32px; height: 32px; border-radius: 50%; background: var(--surface-hover); color: var(--text-muted); display: flex; align-items: center; justify-content: center; font-size: 1rem; flex-shrink: 0;">&#8862;</div>
        <span style="font-size: 0.9rem; flex: 1;">{{ g.name }}</span>
        <!-- Stacked member avatars -->
        <span style="display: inline-flex; align-items: center;">
          {% for m in g.members %}
          {% if loop.index0 < 6 %}
          <span title="{{ m.name }}" style="width: 22px; height: 22px; border-radius: 50%; background: var(--accent); color: #fff; display: inline-flex; align-items: center; justify-content: center; font-size: 0.55rem; font-weight: 600; flex-shrink: 0; overflow: hidden; border: 2px solid var(--surface);{% if loop.index0 > 0 %} margin-left: -8px;{% endif %}">
            {% if m.has_avatar %}<img src="/avatar/{{ m.id }}" style="width:100%;height:100%;object-fit:cover;">{% else %}{{ m.initials }}{% endif %}
          </span>
          {% endif %}
          {% endfor %}
          {% if g.member_count > 6 %}
          <span style="width: 22px; height: 22px; border-radius: 50%; background: var(--surface-hover); color: var(--text-muted); display: inline-flex; align-items: center; justify-content: center; font-size: 0.55rem; font-weight: 600; flex-shrink: 0; border: 2px solid var(--surface); margin-left: -8px;">+{{ g.member_count - 6 }}</span>
          {% endif %}
        </span>
        <span class="badge badge-muted">OIDC group</span>
        <button type="button" class="slot-btn remove-group-btn" data-group-id="{{ g.id }}" style="font-size: 0.75rem; color: var(--error-text); cursor: pointer;">Remove</button>
      </div>
      {% endfor %}
    </div>

    <!-- Unified search bar -->
    <div style="position: relative;">
      <input type="text" id="add-member-search" autocomplete="off" placeholder="Search users or groups..." style="width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: var(--radius); font-size: 0.85rem; font-family: inherit; background: var(--surface); color: var(--text);">
      <div id="add-member-results" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: var(--surface); border: 1px solid var(--border); border-top: none; border-radius: 0 0 var(--radius) var(--radius); max-height: 300px; overflow-y: auto; z-index: 10; box-shadow: var(--shadow);"></div>
    </div>

    <!-- Hidden inputs for members + groups + admin roles -->
    <div id="member-hidden-inputs"></div>
    <div id="group-hidden-inputs"></div>
    <div id="admin-hidden-inputs"></div>
  </div>

  <div style="margin-top: 1.25rem;">
    <button type="submit" class="btn">Save changes</button>
  </div>
</form>

<!-- Danger zone -->
<div class="card" style="margin-top: 2rem; border: 1px solid var(--error-text, #dc2626);">
  <h2 style="font-size: 1rem; margin-bottom: 0.75rem; color: var(--error-text);">Danger zone</h2>
  <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.75rem;">Permanently delete this team. Event types will be unlinked (not deleted). This cannot be undone.</p>
  <button type="button" class="slot-btn" style="font-size: 0.85rem; color: var(--error-text); border-color: var(--error-text); cursor: pointer;" data-confirm="Delete team '{{ team_name }}'? This cannot be undone." onclick="if(confirm(this.dataset.confirm)) this.nextElementSibling.submit();">Delete this team</button>
  <form method="post" action="/dashboard/teams/{{ team_id }}/delete" style="display: none;"></form>
</div>

<script>
(function() {
  var allUsers = [
    {% for u in all_users %}
    { id: "{{ u.id }}", name: "{{ u.name }}", email: "{{ u.email }}", hasAvatar: {{ u.has_avatar | lower }}, initials: "{{ u.initials }}", isMember: {{ u.is_member | lower }} },
    {% endfor %}
  ];

  var allGroups = [
    {% if oidc_groups %}
    {% for g in oidc_groups %}
    { id: "{{ g.id }}", name: "{{ g.name }}", count: {{ g.member_count }}, linked: {{ g.linked | lower }}, members: [
      {% for m in g.members %}{ id: "{{ m.id }}", name: "{{ m.name }}", hasAvatar: {{ m.has_avatar | lower }}, initials: "{{ m.initials }}" },{% endfor %}
    ] },
    {% endfor %}
    {% endif %}
  ];

  // Track current direct members (excludes OIDC-synced)
  var currentMembers = {};
  {% for m in members %}
  {% if m.source != "group" %}
  currentMembers["{{ m.id }}"] = true;
  {% endif %}
  {% endfor %}

  // Track admin members
  var adminMembers = {};
  {% for m in members %}
  {% if m.role == "admin" %}
  adminMembers["{{ m.id }}"] = true;
  {% endif %}
  {% endfor %}

  // Track linked groups
  var linkedGroups = {};
  allGroups.forEach(function(g) { if (g.linked) linkedGroups[g.id] = g; });

  var searchEl = document.getElementById('add-member-search');
  var resultsEl = document.getElementById('add-member-results');
  var hiddenEl = document.getElementById('member-hidden-inputs');
  var groupHiddenEl = document.getElementById('group-hidden-inputs');
  var listEl = document.getElementById('members-list');

  var adminHiddenEl = document.getElementById('admin-hidden-inputs');

  function syncHidden() {
    hiddenEl.innerHTML = '';
    var inp = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'members'; inp.value = Object.keys(currentMembers).join(',');
    hiddenEl.appendChild(inp);

    groupHiddenEl.innerHTML = '';
    var ginp = document.createElement('input');
    ginp.type = 'hidden'; ginp.name = 'group_ids'; ginp.value = Object.keys(linkedGroups).join(',');
    groupHiddenEl.appendChild(ginp);

    adminHiddenEl.innerHTML = '';
    var ainp = document.createElement('input');
    ainp.type = 'hidden'; ainp.name = 'admin_members'; ainp.value = Object.keys(adminMembers).join(',');
    adminHiddenEl.appendChild(ainp);
  }

  function stackedAvatars(members, total) {
    var wrap = document.createElement('span');
    wrap.style.cssText = 'display: inline-flex; align-items: center;';
    var shown = members.slice(0, 6);
    shown.forEach(function(m, i) {
      var av = document.createElement('span');
      av.title = m.name;
      av.style.cssText = 'width: 22px; height: 22px; border-radius: 50%; background: var(--accent); color: #fff; display: inline-flex; align-items: center; justify-content: center; font-size: 0.55rem; font-weight: 600; flex-shrink: 0; overflow: hidden; border: 2px solid var(--surface);' + (i > 0 ? ' margin-left: -8px;' : '');
      if (m.hasAvatar) {
        av.innerHTML = '<img src="/avatar/' + m.id + '" style="width:100%;height:100%;object-fit:cover;">';
      } else {
        av.textContent = m.initials;
      }
      wrap.appendChild(av);
    });
    if (total > 6) {
      var more = document.createElement('span');
      more.style.cssText = 'width: 22px; height: 22px; border-radius: 50%; background: var(--surface-hover); color: var(--text-muted); display: inline-flex; align-items: center; justify-content: center; font-size: 0.55rem; font-weight: 600; flex-shrink: 0; border: 2px solid var(--surface); margin-left: -8px;';
      more.textContent = '+' + (total - 6);
      wrap.appendChild(more);
    }
    return wrap;
  }

  function addMember(user) {
    currentMembers[user.id] = true;
    var row = document.createElement('div');
    row.className = 'member-row';
    row.dataset.id = user.id;
    row.dataset.type = 'user';
    row.style.cssText = 'display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; border-top: 1px solid var(--border);';
    var avatar = document.createElement('div');
    avatar.style.cssText = 'width: 32px; height: 32px; border-radius: 50%; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 0.7rem; flex-shrink: 0; overflow: hidden;';
    if (user.hasAvatar) {
      avatar.innerHTML = '<img src="/avatar/' + user.id + '" style="width:100%;height:100%;object-fit:cover;">';
    } else {
      avatar.textContent = user.initials;
    }
    row.appendChild(avatar);
    var name = document.createElement('span');
    name.style.cssText = 'font-size: 0.9rem; flex: 1;';
    name.textContent = user.name;
    row.appendChild(name);
    var roleSelect = document.createElement('select');
    roleSelect.className = 'role-select';
    roleSelect.dataset.userId = user.id;
    roleSelect.style.cssText = 'font-size: 0.8rem; padding: 0.25rem 0.5rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); color: var(--text); cursor: pointer; font-family: inherit;';
    roleSelect.innerHTML = '<option value="member" selected>Member</option><option value="admin">Admin</option>';
    roleSelect.onchange = function() { setRole(user.id, this.value); };
    row.appendChild(roleSelect);
    var removeBtn = document.createElement('button');
    removeBtn.type = 'button';
    removeBtn.className = 'slot-btn';
    removeBtn.style.cssText = 'font-size: 0.75rem; color: var(--error-text); cursor: pointer;';
    removeBtn.textContent = 'Remove';
    removeBtn.onclick = function() { removeMember(user.id); };
    row.appendChild(removeBtn);
    listEl.appendChild(row);
    syncHidden();
    searchEl.value = '';
    resultsEl.style.display = 'none';
  }

  function removeMember(userId) {
    delete currentMembers[userId];
    delete adminMembers[userId];
    var row = document.querySelector('.member-row[data-id="' + userId + '"][data-type="user"]');
    if (row) row.remove();
    syncHidden();
  }

  function setRole(userId, role) {
    if (role === 'admin') {
      adminMembers[userId] = true;
    } else {
      delete adminMembers[userId];
    }
    syncHidden();
  }

  function addGroup(group) {
    linkedGroups[group.id] = group;
    var row = document.createElement('div');
    row.className = 'member-row';
    row.dataset.id = group.id;
    row.dataset.type = 'group';
    row.style.cssText = 'display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; border-top: 1px solid var(--border);';
    var icon = document.createElement('div');
    icon.style.cssText = 'width: 32px; height: 32px; border-radius: 50%; background: var(--surface-hover); color: var(--text-muted); display: flex; align-items: center; justify-content: center; font-size: 1rem; flex-shrink: 0;';
    icon.innerHTML = '&#8862;';
    row.appendChild(icon);
    var name = document.createElement('span');
    name.style.cssText = 'font-size: 0.9rem; flex: 1;';
    name.textContent = group.name;
    row.appendChild(name);
    if (group.members && group.members.length > 0) {
      row.appendChild(stackedAvatars(group.members, group.count));
    }
    var badge = document.createElement('span');
    badge.className = 'badge badge-muted';
    badge.textContent = 'OIDC group';
    row.appendChild(badge);
    var removeBtn = document.createElement('button');
    removeBtn.type = 'button';
    removeBtn.className = 'slot-btn';
    removeBtn.style.cssText = 'font-size: 0.75rem; color: var(--error-text); cursor: pointer;';
    removeBtn.textContent = 'Remove';
    removeBtn.onclick = function() { removeGroup(group.id); };
    row.appendChild(removeBtn);
    listEl.appendChild(row);
    syncHidden();
    searchEl.value = '';
    resultsEl.style.display = 'none';
  }

  function removeGroup(groupId) {
    delete linkedGroups[groupId];
    var row = document.querySelector('.member-row[data-id="' + groupId + '"][data-type="group"]');
    if (row) row.remove();
    syncHidden();
  }

  // Wire up role dropdowns on server-rendered member rows
  document.querySelectorAll('.role-select').forEach(function(sel) {
    sel.addEventListener('change', function() { setRole(this.dataset.userId, this.value); });
  });

  // Wire up remove buttons on server-rendered member rows
  document.querySelectorAll('.remove-member-btn').forEach(function(btn) {
    btn.addEventListener('click', function() { removeMember(this.dataset.userId); });
  });

  // Wire up remove buttons on server-rendered group rows
  document.querySelectorAll('.remove-group-btn').forEach(function(btn) {
    btn.addEventListener('click', function() { removeGroup(this.dataset.groupId); });
  });

  function renderResults(query) {
    var q = (query || '').toLowerCase();

    var userMatches = allUsers.filter(function(u) {
      if (currentMembers[u.id] || u.isMember) return false;
      if (q === '') return true;
      return u.name.toLowerCase().indexOf(q) !== -1 || u.email.toLowerCase().indexOf(q) !== -1;
    }).slice(0, 8);

    var groupMatches = allGroups.filter(function(g) {
      if (linkedGroups[g.id]) return false;
      if (q === '') return true;
      return g.name.toLowerCase().indexOf(q) !== -1;
    }).slice(0, 5);

    if (userMatches.length === 0 && groupMatches.length === 0) {
      resultsEl.style.display = 'none';
      return;
    }

    resultsEl.innerHTML = '';

    if (userMatches.length > 0) {
      var header = document.createElement('div');
      header.textContent = 'Users';
      header.style.cssText = 'padding: 0.5rem 0.75rem 0.25rem; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);';
      resultsEl.appendChild(header);
      userMatches.forEach(function(u) {
        var row = document.createElement('div');
        row.style.cssText = 'display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0.75rem; cursor: pointer; transition: background 0.1s;';
        row.onmouseenter = function() { this.style.background = 'var(--surface-hover)'; };
        row.onmouseleave = function() { this.style.background = 'none'; };
        row.onclick = function() { addMember(u); };
        var avatar = document.createElement('div');
        avatar.style.cssText = 'width: 28px; height: 28px; border-radius: 50%; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 0.65rem; font-weight: 600; flex-shrink: 0; overflow: hidden;';
        if (u.hasAvatar) {
          avatar.innerHTML = '<img src="/avatar/' + u.id + '" style="width:100%;height:100%;object-fit:cover;">';
        } else {
          avatar.textContent = u.initials;
        }
        row.appendChild(avatar);
        var info = document.createElement('div');
        var nameEl = document.createElement('strong');
        nameEl.style.fontSize = '0.85rem';
        nameEl.textContent = u.name;
        var emailEl = document.createElement('span');
        emailEl.style.cssText = 'color:var(--text-muted);font-size:0.8rem;';
        emailEl.textContent = u.email;
        info.appendChild(nameEl);
        info.appendChild(document.createTextNode(' '));
        info.appendChild(emailEl);
        row.appendChild(info);
        resultsEl.appendChild(row);
      });
    }

    if (groupMatches.length > 0) {
      if (userMatches.length > 0) {
        var sep = document.createElement('div');
        sep.style.cssText = 'border-top: 1px solid var(--border); margin: 0.25rem 0;';
        resultsEl.appendChild(sep);
      }
      var header = document.createElement('div');
      header.textContent = 'OIDC Groups';
      header.style.cssText = 'padding: 0.5rem 0.75rem 0.25rem; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted);';
      resultsEl.appendChild(header);
      groupMatches.forEach(function(g) {
        var row = document.createElement('div');
        row.style.cssText = 'display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0.75rem; cursor: pointer; transition: background 0.1s;';
        row.onmouseenter = function() { this.style.background = 'var(--surface-hover)'; };
        row.onmouseleave = function() { this.style.background = 'none'; };
        row.onclick = function() { addGroup(g); };
        var info = document.createElement('div');
        info.style.cssText = 'display: flex; align-items: center; gap: 0.5rem; flex: 1;';
        var gNameEl = document.createElement('strong');
        gNameEl.style.fontSize = '0.85rem';
        gNameEl.textContent = g.name;
        info.appendChild(gNameEl);
        if (g.members && g.members.length > 0) {
          info.appendChild(stackedAvatars(g.members, g.count));
        } else {
          var countEl = document.createElement('span');
          countEl.style.cssText = 'color:var(--text-muted);font-size:0.8rem;';
          countEl.textContent = ' (' + g.count + ' member' + (g.count !== 1 ? 's' : '') + ')';
          info.appendChild(countEl);
        }
        row.appendChild(info);
        resultsEl.appendChild(row);
      });
    }

    resultsEl.style.display = 'block';
  }

  searchEl.addEventListener('input', function() { renderResults(this.value); });
  searchEl.addEventListener('focus', function() { renderResults(this.value); });
  document.addEventListener('click', function(e) {
    if (!searchEl.contains(e.target) && !resultsEl.contains(e.target)) {
      resultsEl.style.display = 'none';
    }
  });

  syncHidden();
})();
</script>
{% endblock %}
