{# Form component — HTMX form submission with loading state, no Alpine #}
{% from 'macros/form_field.html' import render_field %}

{% if form %}
<div class="max-w-2xl">
  {# Header #}
  <div class="flex items-center justify-between mb-6">
    <h2 class="text-2xl font-bold">{{ form.title }}</h2>
  </div>

  {# Form — data-dz-form enables automatic submit button loading state #}
  <form data-dz-form data-dazzle-form="{{ form.entity_name }}" data-dazzle-form-mode="{{ form.mode }}"
        hx-{{ "put" if form.method == "put" else "post" }}="{{ form.action_url }}"
        hx-target="body"
        hx-swap="innerHTML"
        hx-headers='{"Content-Type": "application/json"}'
        hx-ext="json-enc"
        class="space-y-4">

    {# Form errors area (swapped by HTMX on validation failure) #}
    <div id="form-errors">
      {% include 'fragments/form_errors.html' %}
    </div>

    {# Fields #}
    {% for field in form.fields %}
      {{ render_field(field, form.initial_values) }}
    {% endfor %}

    {# Actions — loading state handled by dz.js via htmx events #}
    <div class="flex gap-3 pt-4">
      <button type="submit" class="btn btn-primary"
              data-dazzle-action="{{ form.entity_name }}.save">
        {% if form.mode == "edit" %}Save{% else %}Create{% endif %}
      </button>
      <a href="{{ form.cancel_url }}" class="btn btn-ghost">Cancel</a>
    </div>
  </form>
</div>
{% endif %}
