{% macro recursive_errors(form, level = 0) %}
{% import _self as macros %}
<ul
  class="ml-{{ level * 4 }}"
  x-data="
    {
        Focus(id) {
            let el = document.getElementById(id);
            if (el instanceof HTMLTextAreaElement) {
                const ckEditorEl = document.getElementById(`${id}_textarea`);
                if (ckEditorEl) {
                    el = ckEditorEl.querySelector('.ck-content');
                }
            }
            if (!el) return;

            const scrollToEl = () => {
                el.scrollIntoView({ behavior: 'smooth', block: 'center' });
            };

            const accordion = el.closest('[data-accordion]');

            // Si aucun accordéon
            if (!accordion) {
                el.focus({ preventScroll: true });
                if (document.activeElement !== el) {
                    scrollToEl();
                }
                return;
            }

            const alpineComponent = Alpine.closestDataStack(el)?.[0];
            if (alpineComponent) {
                alpineComponent.open = true;

                const tryFocus = () => {
                    if (el.offsetParent !== null) {
                        el.focus({ preventScroll: true });
                        if (document.activeElement !== el) {
                            scrollToEl();
                        }
                        clearInterval(timer);
                    }
                };

                const timer = setInterval(tryFocus, 50);
                setTimeout(() => clearInterval(timer), 2000);
            }
        }
    }
  ">
  {% for child in form %}
    {% set hasErrors = child.vars.errors|length > 0 %}
    {% set hasChildren = child|length > 0 %}
    {% if hasErrors or hasChildren %}
      <li class="mb-2">
        {% if hasErrors %}
          <div class="text-sm font-semibold text-red-800 dark:text-red-200">
            <a
              href="#{{ child.vars.id }}"
              class="hover:underline"
              x-on:click.prevent="Focus('{{ child.vars.id }}')">
              {% if child.parent and child.parent.vars.label %}{{ child.parent.vars.label }} - {% endif -%}
              {{- child.vars.label|default(child.vars.name) }}
            </a>
          </div>
          <ul class="ml-4 list-disc text-sm text-red-800 dark:text-red-200">
            {% for error in child.vars.errors %}
              <li>{{ error.message }}</li>
            {% endfor %}
          </ul>
        {% endif %}

        {% if hasChildren %}
          {{ macros.recursive_errors(child, level + 1) }}
        {% endif %}
      </li>
    {% endif %}
  {% endfor %}
</ul>
{% endmacro %}
