{% extends 'base.html' %}
{% block content %}
<div class="toolbar">
  <div>
    <h1>{{ t('duplicates.merge') }}</h1>
    <p class="muted">{{ t('duplicates.order_help') }}</p>
  </div>
  <a class="button button-secondary" href="/assets">{{ t('common.cancel') }}</a>
</div>

<form method="post" action="/assets/merge/preview">
  <div class="panel notice">
    <strong>{{ t('common.important') }}:</strong> {{ t('duplicates.order_notice') }}
  </div>
  <div class="table-scroll">
    <table class="data-table merge-order-table">
      <thead>
        <tr>
          <th>{{ t('common.order') }}</th><th>{{ t('assets.asset_id') }}</th><th>{{ t('common.category') }}</th><th>{{ t('field.name') }}</th>
          <th>{{ t('field.model') }}</th><th>{{ t('field.serial_number') }}</th><th>{{ t('field.hostname') }}</th><th>{{ t('field.notes') }}</th><th>{{ t('field.mesh_node_id') }}</th>
        </tr>
      </thead>
      <tbody id="merge-order-body">
      {% for asset in assets %}
        <tr draggable="true">
          <td class="merge-drag-handle">☰</td>
          <td>{{ asset.id }}<input type="hidden" name="asset_ids" value="{{ asset.id }}"></td>
          <td>{{ asset.category.name }}</td>
          <td>{{ asset.name }}</td>
          <td>{{ asset.model or '' }}</td>
          <td>{{ asset.serial_number or '' }}</td>
          <td>{{ asset.hostname or '' }}</td>
          <td class="multiline">{{ asset.notes or '' }}</td>
          <td class="multiline">{{ asset.mesh_node_id or '' }}</td>
        </tr>
      {% endfor %}
      </tbody>
    </table>
  </div>
  <div class="form-actions">
    <a class="button button-secondary" href="/assets">{{ t('common.cancel') }}</a>
    <button type="submit">{{ t('duplicates.preview') }}</button>
  </div>
</form>

<script>
(() => {
  const body = document.getElementById('merge-order-body');
  let dragged = null;
  body.querySelectorAll('tr').forEach(row => {
    row.addEventListener('dragstart', () => { dragged = row; row.classList.add('dragging'); });
    row.addEventListener('dragend', () => { row.classList.remove('dragging'); dragged = null; });
    row.addEventListener('dragover', event => {
      event.preventDefault();
      if (!dragged || dragged === row) return;
      const rect = row.getBoundingClientRect();
      body.insertBefore(dragged, event.clientY > rect.top + rect.height / 2 ? row.nextSibling : row);
    });
  });
})();
</script>
{% endblock %}
