{# Form field macros - renders the appropriate input for each field type #}
{# Accessible version: aria-required, aria-invalid, aria-describedby #}

{% macro render_field(field, values={}, errors={}) %}
{% set value = values.get(field.name, field.default) if values else field.default %}
{% set error = errors.get(field.name, "") if errors else "" %}
{% set field_id = "field-" ~ field.name %}
{% set error_id = "error-" ~ field.name %}
{% set hint_id = "hint-" ~ field.name if field.hint is defined and field.hint else "" %}
{% set described_by = ([error_id] if error else []) + ([hint_id] if hint_id else []) %}

<div class="form-control w-full {% if error %}has-error{% endif %}">
  {% if field.type == "checkbox" %}
    {# Checkbox: label is inline #}
    <label class="label cursor-pointer justify-start gap-3">
      <input type="checkbox" name="{{ field.name }}"
             id="{{ field_id }}"
             data-dazzle-field="{{ field.name }}"
             class="checkbox checkbox-primary"
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %}
             {% if value %}checked{% endif %} />
      <span class="label-text">{{ field.label }}</span>
    </label>

  {% elif field.source %}
    {# Search-select: dynamic search with autofill #}
    <label class="label" for="search-input-{{ field.name }}">
      <span class="label-text">
        {{ field.label }}
        {% if field.required %}
          <span class="text-error" aria-hidden="true">*</span>
          <span class="sr-only">(required)</span>
        {% endif %}
      </span>
    </label>
    {% include "fragments/search_select.html" %}

  {% else %}
    {# Standard fields: label above #}
    <label class="label" for="{{ field_id }}">
      <span class="label-text">
        {{ field.label }}
        {% if field.required %}
          <span class="text-error" aria-hidden="true">*</span>
          <span class="sr-only">(required)</span>
        {% endif %}
      </span>
    </label>

    {% if field.hint is defined and field.hint %}
    <p id="{{ hint_id }}" class="label-text-alt text-base-content/60 mb-1">
      {{ field.hint }}
    </p>
    {% endif %}

    {% if field.type == "textarea" %}
      <textarea id="{{ field_id }}" name="{{ field.name }}"
                data-dazzle-field="{{ field.name }}"
                class="textarea textarea-bordered w-full {% if error %}textarea-error{% endif %}"
                placeholder="{{ field.placeholder }}"
                {% if field.required %}required aria-required="true"{% endif %}
                {% if error %}aria-invalid="true"{% endif %}
                {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %}
                rows="4">{{ value | default("", true) }}</textarea>

    {% elif field.type == "select" %}
      <select id="{{ field_id }}" name="{{ field.name }}"
              data-dazzle-field="{{ field.name }}"
              class="select select-bordered w-full {% if error %}select-error{% endif %}"
              {% if field.required %}required aria-required="true"{% endif %}
              {% if error %}aria-invalid="true"{% endif %}
              {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %}>
        <option value="" disabled {% if not value %}selected{% endif %}>
          {{ field.placeholder or ("Select " + field.label) }}
        </option>
        {% for opt in field.options %}
        <option value="{{ opt.value }}" {% if value == opt.value %}selected{% endif %}>
          {{ opt.label }}
        </option>
        {% endfor %}
      </select>

    {% elif field.type == "date" %}
      <input id="{{ field_id }}" type="date" name="{{ field.name }}"
             data-dazzle-field="{{ field.name }}"
             class="input input-bordered w-full {% if error %}input-error{% endif %}"
             value="{{ value | default('', true) }}"
             {% if field.required %}required aria-required="true"{% endif %}
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />

    {% elif field.type == "datetime" %}
      <input id="{{ field_id }}" type="datetime-local" name="{{ field.name }}"
             data-dazzle-field="{{ field.name }}"
             class="input input-bordered w-full {% if error %}input-error{% endif %}"
             value="{{ value | default('', true) }}"
             {% if field.required %}required aria-required="true"{% endif %}
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />

    {% elif field.type == "money" %}
      {# Money widget: major-unit display input + hidden minor-unit value #}
      {% set minor_val = values.get(field.name ~ '_minor', '') if values else '' %}
      {% if field.extra.get('currency_fixed', true) %}
      {# Pinned currency — static prefix symbol, Alpine dzMoney #}
      <div x-data="dzMoney" data-dz-currency="{{ field.extra.currency_code }}"
           data-dz-scale="{{ field.extra.scale }}">
        <div class="join w-full">
          <span class="join-item btn btn-ghost no-animation pointer-events-none dz-money-prefix"
                aria-hidden="true">
            {{ field.extra.symbol }}
          </span>
          <input type="text" inputmode="decimal" id="{{ field_id }}"
                 data-dazzle-field="{{ field.name }}"
                 x-model="displayValue" @input="onInput()" @blur="onBlur()"
                 class="input input-bordered join-item w-full {% if error %}input-error{% endif %}"
                 placeholder="0.00"
                 aria-label="{{ field.label }} ({{ field.extra.currency_code }})"
                 {% if field.required %}required aria-required="true"{% endif %}
                 {% if error %}aria-invalid="true"{% endif %}
                 {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />
        </div>
        <input type="hidden" name="{{ field.name }}_minor" x-model="minorValue"
               x-init="minorValue = '{{ minor_val }}'" />
        <input type="hidden" name="{{ field.name }}_currency"
               value="{{ field.extra.currency_code }}" />
      </div>
      {% else %}
      {# Unpinned currency — dropdown selector, Alpine dzMoney #}
      <div x-data="dzMoney" data-dz-scale="{{ field.extra.scale }}">
        <div class="join w-full">
          <select name="{{ field.name }}_currency"
                  @change="onCurrencyChange($event)"
                  class="select select-bordered join-item w-36"
                  aria-label="Currency for {{ field.label }}">
            {% for opt in field.extra.get('currency_options', []) %}
            <option value="{{ opt.code }}" data-scale="{{ opt.scale }}"
                    data-symbol="{{ opt.symbol }}"
                    {% if opt.code == field.extra.currency_code %}selected{% endif %}>
              {{ opt.symbol }} {{ opt.code }}
            </option>
            {% endfor %}
          </select>
          <input type="text" inputmode="decimal" id="{{ field_id }}"
                 data-dazzle-field="{{ field.name }}"
                 x-model="displayValue" @input="onInput()" @blur="onBlur()"
                 class="input input-bordered join-item w-full {% if error %}input-error{% endif %}"
                 placeholder="0.00"
                 aria-label="{{ field.label }}"
                 {% if field.required %}required aria-required="true"{% endif %}
                 {% if error %}aria-invalid="true"{% endif %}
                 {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />
        </div>
        <input type="hidden" name="{{ field.name }}_minor" x-model="minorValue"
               x-init="minorValue = '{{ minor_val }}'" />
      </div>
      {% endif %}

    {% elif field.type == "number" %}
      <input id="{{ field_id }}" type="number" name="{{ field.name }}"
             data-dazzle-field="{{ field.name }}"
             class="input input-bordered w-full {% if error %}input-error{% endif %}"
             value="{{ value | default('', true) }}"
             placeholder="{{ field.placeholder }}"
             {% if field.required %}required aria-required="true"{% endif %}
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />

    {% elif field.type == "email" %}
      <input id="{{ field_id }}" type="email" name="{{ field.name }}"
             data-dazzle-field="{{ field.name }}"
             class="input input-bordered w-full {% if error %}input-error{% endif %}"
             value="{{ value | default('', true) }}"
             placeholder="{{ field.placeholder }}"
             {% if field.required %}required aria-required="true"{% endif %}
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />

    {% elif field.type == "file" %}
      {# File upload: Alpine dzFileUpload component #}
      <div x-data="dzFileUpload" data-dz-file="{{ field.name }}" class="dz-file-upload"
           {% if value %}x-init="hasFile = true; filename = '{{ value | default('', true) | basename_or_url }}'"{% endif %}>
        <input type="hidden" name="{{ field.name }}" id="{{ field_id }}"
               data-dazzle-field="{{ field.name }}" data-dz-file-value
               value="{{ value | default('', true) }}" />
        {# File preview (shown when file exists) #}
        <div x-show="hasFile" class="flex items-center gap-2 p-3 bg-base-200 rounded-lg mb-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-success shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span class="text-sm truncate" x-text="filename"></span>
          <button type="button" @click="clear()" class="btn btn-ghost btn-xs ml-auto" aria-label="Remove file">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        {# Dropzone (shown when no file) #}
        <label x-show="!hasFile"
               @dragover.prevent="dragging = true"
               @dragleave="dragging = false"
               @drop="onDrop($event)"
               :class="dragging && 'border-primary bg-base-200/50'"
               class="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed border-base-300 rounded-lg cursor-pointer hover:border-primary hover:bg-base-200/50 transition-colors">
          <div class="flex flex-col items-center justify-center pt-5 pb-6">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 mb-2 text-base-content/40" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            <p class="text-sm text-base-content/60">Click to upload or drag and drop</p>
          </div>
          <input type="file" class="hidden" data-dz-file-input
                 @change="selectFile($event)"
                 accept="{{ field.extra.get('accept', '*/*') }}"
                 {% if field.extra.get('capture') %}capture="{{ field.extra.capture }}"{% endif %}
                 {% if field.required and not value %}required aria-required="true"{% endif %}
                 {% if error %}aria-invalid="true"{% endif %} />
        </label>
        {# Upload progress #}
        <div x-show="uploading" class="mt-2">
          <progress class="progress progress-primary w-full"></progress>
        </div>
        {# Error message #}
        <div x-show="error" class="text-error text-sm mt-1" x-text="error"></div>
      </div>

    {% else %}
      {# Default: text input #}
      <input id="{{ field_id }}" type="text" name="{{ field.name }}"
             data-dazzle-field="{{ field.name }}"
             class="input input-bordered w-full {% if error %}input-error{% endif %}"
             value="{{ value | default('', true) }}"
             placeholder="{{ field.placeholder }}"
             {% if field.required %}required aria-required="true"{% endif %}
             {% if error %}aria-invalid="true"{% endif %}
             {% if described_by %}aria-describedby="{{ described_by | join(' ') }}"{% endif %} />
    {% endif %}
  {% endif %}

  {% if error %}
  <p id="{{ error_id }}" class="label-text-alt text-error mt-1" role="alert">
    {{ error }}
  </p>
  {% endif %}
</div>
{% endmacro %}
