{% extends "dashboard_base.html" %}
{% block title %}New team — calrs{% endblock %}
{% block dashboard_content %}

{% if error %}
  <div class="error" style="margin-bottom: 1rem;">{{ error }}</div>
{% endif %}

<form method="POST">

<!-- Profile -->
<div class="card">
  <h1 style="margin-bottom: 1rem;">New team</h1>

  <div class="form-group">
    <label for="name">Team name</label>
    <input type="text" id="name" name="name" required value="{{ form_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="{{ form_slug }}" placeholder="engineering" pattern="[a-z0-9\-]+" title="Lowercase letters, numbers, and dashes only">
  </div>

  <div class="form-group">
    <label for="description">Description <span class="hint">(optional)</span></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="What this team is about..." 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;">{{ form_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 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 form_visibility != "private" %}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 form_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;">Private teams get an invite token for sharing. Public teams are visible on the team profile page.</span>
  </fieldset>
</div>

<!-- Members -->
<div class="card" style="margin-top: 1rem;">
  <h2>Members</h2>
  <p style="color: var(--text-muted); font-size: 0.85rem; margin-bottom: 0.75rem;">You will be added as team admin automatically. Add individual users or link OIDC groups.</p>

  <!-- Selected members + groups (pills) -->
  <div id="selected-pills" style="display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 0.75rem;"></div>

  <!-- Hidden inputs for form submission -->
  <div id="member-inputs"></div>
  <input type="hidden" id="group-ids-input" name="group_ids" value="">

  <!-- Unified search bar -->
  <div style="position: relative;">
    <input type="text" id="member-search" autocomplete="off" placeholder="Search users or groups..." style="width: 100%; padding: 0.625rem 1rem; border: 1px solid var(--border); border-radius: var(--radius); font-size: 0.9rem; font-family: inherit; background: var(--surface); color: var(--text);">
    <div id="search-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>
</div>

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

</form>

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

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

  var selected = {};
  var selectedGroups = {};
  var pillsEl = document.getElementById('selected-pills');
  var inputsEl = document.getElementById('member-inputs');
  var groupIdsInput = document.getElementById('group-ids-input');
  var searchEl = document.getElementById('member-search');
  var resultsEl = document.getElementById('search-results');

  function syncInputs() {
    inputsEl.innerHTML = '';
    var inp = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'members'; inp.value = Object.keys(selected).join(',');
    inputsEl.appendChild(inp);
    groupIdsInput.value = Object.keys(selectedGroups).join(',');
  }

  function stackedAvatars(members, total) {
    var wrap = document.createElement('span');
    wrap.style.cssText = 'display: inline-flex; align-items: center; margin-left: 0.25rem;';
    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 renderPills() {
    pillsEl.innerHTML = '';
    // User pills
    Object.values(selected).forEach(function(u) {
      var pill = document.createElement('span');
      pill.style.cssText = 'display: inline-flex; align-items: center; gap: 0.375rem; padding: 0.3rem 0.5rem 0.3rem 0.3rem; background: var(--accent-subtle, rgba(99,102,241,0.1)); color: var(--accent); border-radius: 999px; font-size: 0.825rem; font-weight: 500;';
      var avatar = document.createElement('span');
      avatar.style.cssText = 'width: 24px; height: 24px; border-radius: 50%; background: var(--accent); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 0.6rem; 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;
      }
      pill.appendChild(avatar);
      var nameSpan = document.createElement('span');
      nameSpan.textContent = u.name;
      pill.appendChild(nameSpan);
      if (u.isSelf) {
        var youTag = document.createElement('span');
        youTag.textContent = '(you)';
        youTag.style.cssText = 'font-size: 0.75rem; opacity: 0.7;';
        pill.appendChild(youTag);
      } else {
        var removeBtn = document.createElement('button');
        removeBtn.type = 'button';
        removeBtn.textContent = '\u00d7';
        removeBtn.style.cssText = 'background: none; border: none; color: var(--accent); font-size: 1rem; cursor: pointer; padding: 0 0.125rem; line-height: 1;';
        removeBtn.onclick = function() { delete selected[u.id]; renderPills(); syncInputs(); };
        pill.appendChild(removeBtn);
      }
      pillsEl.appendChild(pill);
    });
    // Group pills with stacked avatars
    Object.values(selectedGroups).forEach(function(g) {
      var pill = document.createElement('span');
      pill.style.cssText = 'display: inline-flex; align-items: center; gap: 0.375rem; padding: 0.3rem 0.5rem 0.3rem 0.4rem; background: var(--surface-hover); color: var(--text); border-radius: 999px; font-size: 0.825rem; font-weight: 500; border: 1px solid var(--border);';
      var nameSpan = document.createElement('span');
      nameSpan.textContent = g.name;
      pill.appendChild(nameSpan);
      if (g.members && g.members.length > 0) {
        pill.appendChild(stackedAvatars(g.members, g.count));
      } else {
        var countSpan = document.createElement('span');
        countSpan.textContent = '(' + g.count + ')';
        countSpan.style.cssText = 'font-size: 0.75rem; color: var(--text-muted);';
        pill.appendChild(countSpan);
      }
      var removeBtn = document.createElement('button');
      removeBtn.type = 'button';
      removeBtn.textContent = '\u00d7';
      removeBtn.style.cssText = 'background: none; border: none; color: var(--text-muted); font-size: 1rem; cursor: pointer; padding: 0 0.125rem; line-height: 1;';
      removeBtn.onclick = function() { delete selectedGroups[g.id]; renderPills(); syncInputs(); };
      pill.appendChild(removeBtn);
      pillsEl.appendChild(pill);
    });
  }

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

    var userMatches = allUsers.filter(function(u) {
      if (selected[u.id]) 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 (selectedGroups[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 1rem 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 1rem; 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() { selected[u.id] = u; renderPills(); syncInputs(); searchEl.value = ''; resultsEl.style.display = 'none'; };
        var avatar = document.createElement('span');
        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 1rem 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 1rem; 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() { selectedGroups[g.id] = g; renderPills(); syncInputs(); searchEl.value = ''; resultsEl.style.display = 'none'; };
        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';
    }
  });

  // Auto-add current user
  var selfUser = allUsers.find(function(u) { return u.isSelf; });
  if (selfUser) { selected[selfUser.id] = selfUser; }
  renderPills();
  syncInputs();

  // Auto-generate slug from name
  var nameEl = document.getElementById('name');
  var slugEl = document.getElementById('slug');
  var slugManuallyEdited = slugEl.value !== '';
  slugEl.addEventListener('input', function() { slugManuallyEdited = true; });
  nameEl.addEventListener('input', function() {
    if (!slugManuallyEdited) {
      slugEl.value = nameEl.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    }
  });
})();
</script>
{% endblock dashboard_content %}
