{% comment %}
Form Field Component
====================

A comprehensive form field component with label, input, help text, and error handling.

Purpose:
    Renders a complete form field with consistent styling, accessibility attributes,
    and optional HTMX validation support.

Usage Examples:
    Basic field:
        {% include 'forms/partials/form_field.html' with field=form.email %}

    Field with custom label:
        {% include 'forms/partials/form_field.html' with field=form.email label='Email Address' %}

    Field without label:
        {% include 'forms/partials/form_field.html' with field=form.hidden_field show_label=False %}

    Field with HTMX validation:
        {% include 'forms/partials/form_field.html' with field=form.username hx_validate=True hx_validate_url='/api/validate-username/' %}

    Inline field:
        {% include 'forms/partials/form_field.html' with field=form.email layout='inline' %}

    With success state:
        {% include 'forms/partials/form_field.html' with field=form.email show_success=True %}

Parameters:
    Required:
    - field: Django form field object

    Optional (labels):
    - label: Custom label text (default: field.label)
    - show_label: Show label (default: True)
    - label_class: Additional CSS classes for label

    Optional (input):
    - input_class: Additional CSS classes for input
    - placeholder: Custom placeholder text
    - autofocus: Add autofocus attribute (default: False)
    - disabled: Disable input (default: False)
    - readonly: Make input readonly (default: False)

    Optional (help/errors):
    - help_text: Custom help text (default: field.help_text)
    - show_help: Show help text (default: True)
    - show_errors: Show error messages (default: True)
    - show_success: Show success indicator when valid (default: False)

    Optional (HTMX validation):
    - hx_validate: Enable HTMX inline validation (default: False)
    - hx_validate_url: URL for validation endpoint
    - hx_validate_trigger: Trigger event (default: 'blur changed delay:500ms')
    - hx_validate_target: Target for validation response (default: auto-generated)

    Optional (layout):
    - layout: 'stacked' or 'inline' (default: 'stacked')
    - required_indicator: Show required indicator (default: True)
    - size: 'sm', 'md', 'lg' for input size (default: 'md')

Dependencies:
    - Tailwind CSS for styling
    - HTMX (optional, for inline validation)
    - Alpine.js (optional, for enhanced interactions)
    - common_filters template tags (for add_class filter)

Accessibility:
    - Label properly associated with input via for/id
    - aria-describedby links help text and errors to input
    - aria-invalid set when field has errors
    - aria-required set for required fields
    - Error messages use role="alert" for screen reader announcement
{% endcomment %}
{% load common_filters %}

{% with show_label=show_label|default:True show_help=show_help|default:True show_errors=show_errors|default:True show_success=show_success|default:False required_indicator=required_indicator|default:True layout=layout|default:'stacked' size=size|default:'md' %}

<div class="form-field {% if layout == 'inline' %}flex items-center gap-4{% else %}mb-4{% endif %}"
     data-field-name="{{ field.name }}"
     data-field-required="{{ field.field.required|yesno:'true,false' }}"
     {% if hx_validate %}x-data="{ valid: null, validating: false, touched: false }"{% endif %}>

    {# Label #}
    {% if show_label %}
    <label for="{{ field.id_for_label }}"
           class="{% if layout == 'inline' %}w-1/3 text-right{% else %}block mb-1.5{% endif %} {% if size == 'sm' %}text-xs{% elif size == 'lg' %}text-base{% else %}text-sm{% endif %} font-medium text-foreground {{ label_class }}">
        {{ label|default:field.label }}
        {% if required_indicator and field.field.required %}
        <span class="text-destructive ml-0.5" aria-hidden="true">*</span>
        <span class="sr-only">(required)</span>
        {% endif %}
    </label>
    {% endif %}

    {# Input wrapper #}
    <div class="{% if layout == 'inline' and show_label %}flex-1{% else %}w-full{% endif %} relative">
        {# Field input with enhanced attributes #}
        {# Base widget classes for sizing, spacing, and transitions #}
        {% with base_class='w-full border rounded-lg transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-0 bg-background text-foreground placeholder:text-muted-foreground' %}
        {# Size classes #}
        {% with size_class=size|default:'md'|yesno:'px-2.5 py-1.5 text-xs,px-3 py-2 text-sm,px-4 py-2.5 text-base' %}
        {% if size == 'sm' %}{% with actual_size='px-2.5 py-1.5 text-xs' %}
        {# Error-specific classes override border and focus ring colors #}
        {% with error_class='border-destructive focus:ring-destructive/30 focus:border-destructive' %}
        {# Success-specific classes #}
        {% with success_class='border-green-500 focus:ring-green-500/30 focus:border-green-500' %}
        {# Normal state classes for border and focus ring #}
        {% with normal_class='border-input focus:ring-ring/30 focus:border-ring' %}

        {# Render the field with base classes plus state-specific classes #}
        {% if field.errors %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:error_class|add_class:input_class }}
        {% else %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:normal_class|add_class:input_class }}
        {% endif %}

        {% endwith %}{% endwith %}{% endwith %}{% endwith %}
        {% elif size == 'lg' %}{% with actual_size='px-4 py-2.5 text-base' %}
        {% with error_class='border-destructive focus:ring-destructive/30 focus:border-destructive' %}
        {% with success_class='border-green-500 focus:ring-green-500/30 focus:border-green-500' %}
        {% with normal_class='border-input focus:ring-ring/30 focus:border-ring' %}
        {% if field.errors %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:error_class|add_class:input_class }}
        {% else %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:normal_class|add_class:input_class }}
        {% endif %}
        {% endwith %}{% endwith %}{% endwith %}{% endwith %}
        {% else %}{% with actual_size='px-3 py-2 text-sm' %}
        {% with error_class='border-destructive focus:ring-destructive/30 focus:border-destructive' %}
        {% with success_class='border-green-500 focus:ring-green-500/30 focus:border-green-500' %}
        {% with normal_class='border-input focus:ring-ring/30 focus:border-ring' %}
        {% if field.errors %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:error_class|add_class:input_class }}
        {% else %}
            {{ field|add_class:base_class|add_class:actual_size|add_class:normal_class|add_class:input_class }}
        {% endif %}
        {% endwith %}{% endwith %}{% endwith %}{% endwith %}
        {% endif %}
        {% endwith %}
        {% endwith %}

        {# HTMX validation attributes (when enabled) #}
        {% if hx_validate and hx_validate_url %}
        <script>
            (function() {
                var el = document.getElementById('{{ field.id_for_label }}');
                if (el) {
                    el.setAttribute('hx-post', '{{ hx_validate_url }}');
                    el.setAttribute('hx-trigger', '{{ hx_validate_trigger|default:"blur changed delay:500ms" }}');
                    el.setAttribute('hx-target', '#{{ field.name }}-feedback');
                    el.setAttribute('hx-swap', 'innerHTML');
                    el.setAttribute('hx-indicator', '#{{ field.name }}-indicator');
                    el.setAttribute('hx-include', '[name="{{ field.name }}"]');
                    if (typeof htmx !== 'undefined') htmx.process(el);
                }
            })();
        </script>
        {% endif %}

        {# Validation indicator (for HTMX) - positioned inside input #}
        {% if hx_validate %}
        <div id="{{ field.name }}-indicator" class="htmx-indicator absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
            <i class="fas fa-spinner fa-spin text-muted-foreground" aria-hidden="true"></i>
        </div>
        {% endif %}

        {# Success indicator (shown when valid and no errors) #}
        {% if show_success and not field.errors and field.value %}
        <div class="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
            <i class="fas fa-check-circle text-green-500" aria-hidden="true"></i>
        </div>
        {% endif %}

        {# Feedback area (errors, success, help) #}
        <div id="{{ field.name }}-feedback"
             class="field-feedback mt-1.5"
             aria-live="polite"
             aria-atomic="true">

            {# Error messages #}
            {% if show_errors and field.errors %}
            {% include 'forms/partials/field_error.html' with errors=field.errors %}
            {% endif %}

            {# Help text #}
            {% if show_help and field.help_text %}
            <p id="{{ field.name }}-help"
               class="{% if size == 'sm' %}text-xs{% elif size == 'lg' %}text-sm{% else %}text-xs{% endif %} text-muted-foreground {% if field.errors %}mt-1{% endif %}">
                {{ help_text|default:field.help_text }}
            </p>
            {% endif %}
        </div>
    </div>
</div>

{% endwith %}
