{% extends 'scopes.html' %}
{% import "bootstrap/wtf.html" as wtf %}
{% import "macros.html" as macros %}

{% set btn_back = true %}

{% block nav_client %} active {% endblock %}
{% block nav_client_search %} active {% endblock %}
{% block content %}

<h2 class="mx-5 subhead-heading">
  {{ _('Search clients') }}
</h2>

<div class="mx-5 my-3">
  <label for="name-filter">{{ _('Name') }}</label>
  <input type="text" id="name-filter" class="form-control mb-2">

  <label for="ip-filter">{{ _('IP Address') }}</label>
  <input type="text" id="ip-filter" class="form-control mb-2">

  <button id="search-button" class="btn btn-primary">{{ _('Search') }}</button>
</div>

<div id="clients-container" class="mx-5 mt-3"></div>

<script>
  let clients = {{ clients|tojson|safe }};

  function renderClients(data) {
    const container = document.getElementById('clients-container');
    container.innerHTML = '';

    let currentPath = null;
    let ul = null;

    data.forEach(client => {
      if (client.tree_path !== currentPath) {
        currentPath = client.tree_path;

        const pathElement = document.createElement('p');
        pathElement.innerHTML = `<strong>${currentPath}</strong>:`;
        container.appendChild(pathElement);

        ul = document.createElement('ul');
        container.appendChild(ul);
      }

      const li = document.createElement('li');
      li.textContent = `${client.name} (IP: ${client.ip.join(', ')})`;
      ul.appendChild(li);
    });
  }

  function filterClients() {
    const nameFilter = document.getElementById('name-filter').value.toLowerCase();
    const ipFilter = document.getElementById('ip-filter').value;

    // If both filters are empty, don't display any clients
    if (!nameFilter && !ipFilter) {
      document.getElementById('clients-container').innerHTML = '';
      return;
    }

    const filtered = clients.filter(client => {
      const matchesName = nameFilter ? client.name.toLowerCase().includes(nameFilter) : true;
      const matchesIP = ipFilter ? client.ip.some(ip => ip.includes(ipFilter)) : true;
      return matchesName && matchesIP;
    });

    renderClients(filtered);
  }

  filterClients();
  document.getElementById('search-button').addEventListener('click', filterClients);

  // Search on Enter key press
  document.querySelectorAll('#name-filter, #ip-filter').forEach(input => {
    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') {
        event.preventDefault();
        filterClients();
      }
    });
  });
</script>


{% endblock %}