{% load i18n %}
<div class="horologia-schedule-periods" data-prefix="{{ widget.name }}">
  {{ widget.formset.management_form }}
  {% if widget.formset.non_form_errors %}
    <div class="errors">{{ widget.formset.non_form_errors }}</div>
  {% endif %}
  <table class="horologia-schedule-periods__table">
    <thead>
      <tr>
        <th>{% trans "Start period (seconds)" %}</th>
        <th>{% trans "Limit" %}</th>
        <th>{% trans "Number of phases" %}</th>
        <th>{% trans "Phase to use" %}</th>
        <th class="horologia-schedule-periods__actions">{% trans "Actions" %}</th>
      </tr>
    </thead>
    <tbody data-period-rows>
      {% for form in widget.formset.forms %}
        <tr class="horologia-schedule-periods__row" data-row-index="{{ forloop.counter0 }}">
          {% for field in form.visible_fields %}
            <td>
              {{ field }}
              {% if field.errors %}
                <div class="errors">{{ field.errors|join:", " }}</div>
              {% endif %}
            </td>
          {% endfor %}
          <td class="horologia-schedule-periods__actions">
            <button type="button" class="button delete-button" data-remove-row>{% trans "Remove" %}</button>
          </td>
          {% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %}
        </tr>
      {% endfor %}
    </tbody>
  </table>
  <template data-empty-form>
    <tr class="horologia-schedule-periods__row" data-row-index="__index__">
      {% for field in widget.formset.empty_form.visible_fields %}
        <td>{{ field }}</td>
      {% endfor %}
      <td class="horologia-schedule-periods__actions">
        <button type="button" class="button delete-button" data-remove-row>{% trans "Remove" %}</button>
      </td>
      {% for hidden in widget.formset.empty_form.hidden_fields %}{{ hidden }}{% endfor %}
    </tr>
  </template>
  <div class="horologia-schedule-periods__controls">
    <button type="button" class="button" data-add-row>{% trans "Add period" %}</button>
  </div>
</div>
<script>
  (function() {
    const container = document.currentScript.previousElementSibling;
    const tableBody = container.querySelector('[data-period-rows]');
    const emptyTemplate = container.querySelector('template[data-empty-form]');
    const addButton = container.querySelector('[data-add-row]');
    const totalFormsInput = container.querySelector(`[name="${container.dataset.prefix}-TOTAL_FORMS"]`);

    function replacePrefix(value, index) {
      return value
        .replace(/__prefix__/g, index)
        .replace(/-\d+-/, `-${index}-`)
        .replace(/_\d+_/, `_${index}_`);
    }

    function updateIndexes() {
      const rows = tableBody.querySelectorAll('.horologia-schedule-periods__row');
      rows.forEach((row, index) => {
        row.dataset.rowIndex = index;
        row.querySelectorAll('input, select, textarea').forEach((element) => {
          element.name = replacePrefix(element.name, index);
          element.id = replacePrefix(element.id, index);
        });
      });
      totalFormsInput.value = rows.length;
    }

    addButton?.addEventListener('click', () => {
      const clone = document.importNode(emptyTemplate.content, true);
      const newRow = clone.querySelector('.horologia-schedule-periods__row');
      tableBody.appendChild(clone);
      updateIndexes();
    });

    tableBody.addEventListener('click', (event) => {
      const target = event.target;
      if (target && target.matches('[data-remove-row]')) {
        const row = target.closest('.horologia-schedule-periods__row');
        const deleteInput = row?.querySelector('input[name$="-DELETE"]');
        if (deleteInput) {
          if (deleteInput.type === 'checkbox') {
            deleteInput.checked = true;
          } else {
            deleteInput.value = 'on';
          }
        }
        if (row) {
          row.style.display = 'none';
          row.classList.add('horologia-schedule-periods__row--deleted');
        }
      }
    });
  })();
</script>
