<div id="relationship_table_section" class="overflow-x-auto nb-card mb-10">
  <table class="nb-table">
    <thead>
      <tr>
        <th class="text-left">Origin</th>
        <th class="text-left">Target</th>
        <th class="text-left">Type</th>
        <th class="text-left">Actions</th>
      </tr>
    </thead>
    <tbody>
      {% for row in relationships %}
      {% set relationship = row.relationship %}
      <tr>
        <!-- Origin column -->
        <td>
          {% for entity in entities if entity.id == relationship.in %}
          <span> {{ entity.name }}
          </span>
          {% else %}
          {{ relationship.in }}
          {% endfor %}
        </td>
        <!-- Target column -->
        <td>
          {% for entity in entities if entity.id == relationship.out %}
          <span>
            {{ entity.name }}
          </span>
          {% else %}
          {{ relationship.out }}
          {% endfor %}
        </td>
        <td class="uppercase tracking-wide text-xs">{{ row.relationship_type_label }}</td>
        <td>
          <button class="nb-btn btn-xs" hx-delete="/knowledge-relationship/{{ relationship.id }}"
            hx-target="#relationship_table_section" hx-swap="outerHTML">
            {% include "icons/delete_icon.html" %}
          </button>
        </td>
      </tr>
      {% endfor %}
      <!-- New linking row -->
      <tr id="new_relationship">
        <td>
          <select name="in_" class="nb-select w-full new_relationship_input">
            <option disabled selected>Select Origin</option>
            {% for entity in entities %}
            <option value="{{ entity.id }}">
              {{ entity.name }}
            </option>
            {% endfor %}
          </select>
        </td>
        <td>
          <select name="out" class="nb-select w-full new_relationship_input">
            <option disabled selected>Select Target</option>
            {% for entity in entities %}
            <option value="{{ entity.id }}">{{ entity.name }}</option>
            {% endfor %}
          </select>
        </td>
        <td>
          <input id="relationship_type_input" name="relationship_type" type="text" placeholder="RelatedTo"
            class="nb-input w-full new_relationship_input" value="{{ default_relationship_type }}" />
        </td>
        <td>
          <button id="save_relationship_button" type="button" class="nb-btn btn-sm" hx-post="/knowledge-relationship"
            hx-target="#relationship_table_section" hx-swap="outerHTML" hx-include=".new_relationship_input">
            Save
          </button>
        </td>
      </tr>
    </tbody>
  </table>
</div>
<script>
  document.getElementById('relationship_type_input').addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
      event.preventDefault(); // Prevent form submission if within a form
      document.getElementById('save_relationship_button').click();
    }
  });
</script>
