{# LIBRARIES #}
{{ attach_library('ui_patterns/libraries.bs_forms') }}
{{ attach_library('ui_patterns/form-form.form_lib') }}
{{ attach_library('ui_patterns/libraries.bs_card') }}

{# VARIABLES #}
{% set attributes = attributes|default(create_attribute()) %}

{% set legend_attributes = legend_attributes|default(create_attribute()) %}
{% set content_attributes = content_attributes|default(create_attribute()) %}
{% set description_display = description_display|default('before') %}

{% set content_classes = content_classes|default('') %}
{% set legend_classes = legend_classes|default('') %}
{% set classes = classes|default('') %}

{% if title_display == 'inline' %}
  {% set type = 'input' %}
{% endif %}

{% set classes = [
  classes ? classes : '',
  type != 'input' ? 'card',
  title_display == 'inline' ? 'form-row row',
  'js-form-wrapper',
] %}

{% set legend_classes = [
  legend_classes ? legend_classes : '',
  'fieldset-legend',
  required ? 'js-form-required',
  required ? 'form-required',
  type != 'input' ? 'card-header',
  title_display == 'inline' ? 'col-md-3',
] %}

{% set content_classes = [
  content_classes ? content_classes : '',
  'fieldset-wrapper',
  type != 'input' ? 'card-body',
  title_display == 'inline' ? 'col-md-9',
] %}

<fieldset {{ attributes.addClass(classes) }}>

  <legend {{ legend_attributes.addClass(legend_classes) }}>
    <span class="legend-title">
      {% if title_prefix %}
        {{ title_prefix|raw }}
      {% endif %}
      {{ legend_title|raw }}
      {%- if required -%}
        <span class="reqd">*</span>
      {%- endif -%}
      {% if title_suffix %}
        {{ title_suffix|raw }}
      {% endif %}
    </span>
  </legend>

  <div {{ content_attributes.addClass(content_classes) }}>

    {% if description_display == 'before' and description_content %}
      <small{{ description_attributes }} class="help-block fshb">
        {{ description_content }}
      </small>
    {% endif %}

    {% if prefix %}
      <span class="field-prefix">{{ prefix }}</span>
    {% endif %}

    {{ children }}

    {% if suffix %}
      <span class="field-suffix">{{ suffix }}</span>
    {% endif %}

    {% if errors %}
      <div class="alert alert-danger form-item--error-message">
        <strong>{{ errors }}</strong>
      </div>
    {% endif %}

    {% if description_display in ['after', 'invisible'] and description_content %}
      <small{{ description_attributes }} class="help-block fshb">
        {{ description_content }}
      </small>
    {% endif %}

  </div>
</fieldset>
