{{ define "buttons_admin_grid" }}
<div id="buttons-grid-admin" class="grid">
  {{ range .Buttons }}
    <div class="btn-tile draggable-tile" draggable="true" data-code="{{ .Code }}">
      {{ if .ImageURL }}
      <img class="thumb" src="{{ imgv .ImageURL }}" alt="" />
      {{ end }}
      <span class="tile-name">{{ .Label }}</span>
      <div class="btn-actions">
        <form class="remove"
              hx-post="/api/buttons/remove"
              hx-target="#buttons-grid-admin" hx-swap="outerHTML">
          <input type="hidden" name="code" value="{{ .Code }}">
          <button type="submit" class="btn danger">✕</button>
        </form>
      </div>
    </div>
  {{ else }}
    <p class="empty">{{ T "designer.empty" }}</p>
  {{ end }}
</div>
<script>
(function () {
  var grid = document.getElementById('buttons-grid-admin');
  var dragged = null;

  grid.addEventListener('dragstart', function (ev) {
    dragged = ev.target.closest('.draggable-tile');
    if (dragged) { dragged.classList.add('dragging'); ev.dataTransfer.effectAllowed = 'move'; }
  });
  grid.addEventListener('dragend', function () {
    if (dragged) dragged.classList.remove('dragging');
    dragged = null;
  });
  grid.addEventListener('dragover', function (ev) {
    ev.preventDefault();
    var over = ev.target.closest('.draggable-tile');
    if (!dragged || !over || over === dragged) return;
    var rect = over.getBoundingClientRect();
    var before = (ev.clientX - rect.left) < rect.width / 2;
    grid.insertBefore(dragged, before ? over : over.nextSibling);
  });
  grid.addEventListener('drop', function (ev) {
    ev.preventDefault();
    var codes = Array.prototype.map.call(grid.querySelectorAll('.draggable-tile'), function (t) { return t.dataset.code; });
    var fd = new FormData();
    codes.forEach(function (c) { fd.append('codes', c); });
    fetch('/api/buttons/reorder', { method: 'POST', body: fd }).then(function (res) {
      // If the save failed, reload so the grid shows the real order instead
      // of a reorder that only happened in the DOM.
      if (!res.ok) location.reload();
    });
  });
})();
</script>
{{ end }}

{{ define "buttons_admin" }}
<div class="products">
  <h2>{{ T "designer.search_title" }}</h2>

  <div class="card form-row search-box" style="position: relative;">
    <input type="search" name="search" id="search" placeholder="{{ T "designer.search_placeholder" }}"
           hx-get="/api/buttons/search" hx-target="#search-results" hx-trigger="keyup changed delay:300ms"
           hx-params="*"
           autocomplete="off">
    <div id="search-results" class="search-results" style="
      position:absolute;
      top: 100%;
      left:0;
      right:0;
      z-index:20;
      background:#fff;
      box-shadow:0 4px 12px rgba(0,0,0,0.12);
      max-height:240px;
      overflow-y:auto;
      display:none;
    "></div>
  </div>

  {{ template "buttons_admin_grid" . }}
</div>

<script>
document.getElementById('search').addEventListener('input', function() {
  const box = document.getElementById('search-results');
  if (this.value.length >= 3) {
    box.style.display = 'block';
  } else {
    box.style.display = 'none';
  }
});

htmx.on('#search-results', 'htmx:afterSwap', function(evt) {
  const box = document.getElementById('search-results');
  if (document.getElementById('search').value.length >= 3) {
    box.style.display = 'block';
  }
});

htmx.on('body', 'htmx:afterRequest', function(evt) {
  if (evt.detail.elt && evt.detail.elt.id === 'search') {
    const box = document.getElementById('search-results');
    if (box) box.style.display = 'block';
  }
});
</script>
{{ end }}

{{ define "buttons_search_results" }}
<div class="results">
  {{ range .Results }}
    <button class="btn inline result"
            type="button"
            hx-post="/api/buttons/add"
            hx-target="#buttons-grid-admin"
            hx-swap="outerHTML"
            hx-vals='{"label":"{{ .Name }}","code":"{{ .Barcode }}","itemId":"{{ .ItemID }}","imageUrl":"{{ .Image }}"}'
            hx-on="htmx:afterRequest: document.getElementById('search-results').style.display='none'">
      {{ if .Image }}<img class="thumb" src="{{ .Image }}" alt="{{ .Name }}" />{{ end }}
      <span class="text">
        <strong>{{ .Name }}</strong><br/>
        <small>{{ .Barcode }}</small>
      </span>
    </button>
  {{ else }}
    <p class="empty">{{ T "designer.no_matches" }}</p>
  {{ end }}
</div>
{{ end }}
