<div class="d-flex justify-content-end mb-3">
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#abTeamModal" id="abNewTeamBtn"><i class="bi bi-plus-lg me-1"></i>New Team</button>
</div>

<div class="row g-3">
  <?php foreach ($teams as $t): ?>
  <div class="col-md-4">
    <div class="ab-card h-100">
      <div class="ab-card-body">
        <div class="d-flex justify-content-between align-items-start">
          <h3 class="fs-6"><?= e($t['name']) ?></h3>
          <div class="dropdown">
            <button class="btn btn-icon btn-light-soft btn-sm" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
            <ul class="dropdown-menu dropdown-menu-end">
              <li><a class="dropdown-item ab-view-team" href="#" data-id="<?= (int) $t['id'] ?>" data-name="<?= e($t['name']) ?>">Manage Members</a></li>
              <li><a class="dropdown-item text-danger ab-delete-team" href="#" data-id="<?= (int) $t['id'] ?>">Delete</a></li>
            </ul>
          </div>
        </div>
        <p class="ab-cell-sub"><?= e($t['description'] ?? 'No description') ?></p>
        <div class="d-flex gap-3 small ab-text-muted mb-2">
          <span><i class="bi bi-diagram-3 me-1"></i><?= e($t['department_name'] ?? 'No department') ?></span>
          <span><i class="bi bi-people me-1"></i><?= (int) $t['member_count'] ?> members</span>
        </div>
        <?php if ($t['lead_name']): ?><span class="ab-badge bg-secondary-soft">Lead: <?= e($t['lead_name']) ?></span><?php endif; ?>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
  <?php if (empty($teams)): ?>
  <div class="col-12"><div class="ab-empty"><i class="bi bi-people"></i><h3>No teams yet</h3></div></div>
  <?php endif; ?>
</div>

<div class="modal fade" id="abTeamModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title">New Team</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <form id="abTeamForm">
          <div class="mb-3"><label class="form-label ab-req">Name</label><input class="form-control" name="name" required></div>
          <div class="mb-0"><label class="form-label">Description</label><textarea class="form-control" name="description" rows="2"></textarea></div>
        </form>
      </div>
      <div class="modal-footer"><button class="btn btn-light-soft" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary" id="abTeamSaveBtn">Create Team</button></div>
    </div>
  </div>
</div>

<div class="modal fade" id="abMembersModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header"><h5 class="modal-title" id="abMembersModalTitle">Team Members</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <div id="abMembersList" class="mb-3"></div>
        <div class="input-group">
          <input type="number" class="form-control" id="abAddMemberUserId" placeholder="User ID to add">
          <button class="btn btn-primary" id="abAddMemberBtn">Add</button>
        </div>
        <div class="form-text">Phase 3 note: swap this for a searchable user picker once the Users API supports name search autocomplete.</div>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var currentTeamId = null;

  document.getElementById('abTeamSaveBtn').addEventListener('click', function () {
    var form = document.getElementById('abTeamForm');
    abFetch('<?= base_url('teams') ?>', { method: 'POST', body: { name: form.name.value, description: form.description.value } })
      .then(function (res) {
        abToast(res.message);
        bootstrap.Modal.getInstance(document.getElementById('abTeamModal')).hide();
        setTimeout(function () { window.location.reload(); }, 600);
      }).catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message, 'danger'); });
  });

  function loadMembers(teamId) {
    abFetch('<?= base_url('teams') ?>/' + teamId + '/members').then(function (res) {
      var list = document.getElementById('abMembersList');
      if (!res.data.length) { list.innerHTML = '<div class="ab-empty small">No members yet.</div>'; return; }
      list.innerHTML = res.data.map(function (m) {
        return '<div class="d-flex align-items-center gap-2 p-2 border-bottom ab-hairline">' +
          '<div class="ab-mini-avatar">' + (m.first_name[0] || '') + (m.last_name ? m.last_name[0] : '') + '</div>' +
          '<div class="flex-fill"><div class="small fw-semibold">' + m.first_name + ' ' + (m.last_name || '') + '</div><div class="ab-cell-sub">' + (m.job_title || '') + '</div></div>' +
          '<button class="btn btn-icon btn-light-soft btn-sm ab-remove-member" data-user-id="' + m.id + '"><i class="bi bi-x-lg"></i></button>' +
          '</div>';
      }).join('');

      document.querySelectorAll('.ab-remove-member').forEach(function (btn) {
        btn.addEventListener('click', function () {
          abFetch('<?= base_url('teams') ?>/' + currentTeamId + '/members/' + btn.dataset.userId, { method: 'DELETE' })
            .then(function () { loadMembers(currentTeamId); });
        });
      });
    });
  }

  document.querySelectorAll('.ab-view-team').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      currentTeamId = this.dataset.id;
      document.getElementById('abMembersModalTitle').textContent = this.dataset.name + ' — Members';
      loadMembers(currentTeamId);
      new bootstrap.Modal(document.getElementById('abMembersModal')).show();
    });
  });

  document.getElementById('abAddMemberBtn').addEventListener('click', function () {
    var userId = document.getElementById('abAddMemberUserId').value;
    if (!userId) return;
    abFetch('<?= base_url('teams') ?>/' + currentTeamId + '/members', { method: 'POST', body: { user_id: userId } })
      .then(function () { document.getElementById('abAddMemberUserId').value = ''; loadMembers(currentTeamId); })
      .catch(function (err) { abToast(err.message || 'Could not add member.', 'danger'); });
  });

  document.querySelectorAll('.ab-delete-team').forEach(function (link) {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      if (!confirm('Delete this team?')) return;
      abFetch('<?= base_url('teams') ?>/' + this.dataset.id, { method: 'DELETE' })
        .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
        .catch(function (err) { abToast(err.message, 'danger'); });
    });
  });
})();
</script>
