{% extends "forms/field.html.twig" %}

{% macro spanToggle(input, length, markdown) %}
  {% set space = repeat('&nbsp;&nbsp;', (length - input|length) / 2) %}
  {# GHSA-5xv4-g337-2pg7: escape the option label unless the field opts in with `markdown: true`;
     only the &nbsp; padding is always raw. #}
  {% set label = markdown ? input|markdown(false) : input|e %}
  {{ (space ~ label ~ space)|raw }}
{% endmacro %}

{% import _self as macro %}

{% set has_hidden = false %}
{% for key, text in field.options %}
  {% if key is empty %}
    {% set has_hidden = true %}
  {% endif %}
{% endfor %}

{% block global_attributes %}
  {{ parent() }}
  data-grav-field-name="{{ (scope ~ field.name)|fieldName }}"
{% endblock %}

{% block input %}
  <div class="switch-toggle switch-grav {{ field.size }} switch-{{ field.options|length }} {{ field.classes }}">
    {% set maxLen = 0 %}
    {% for text in field.options %}
      {% set translation = text|t|trim %}
      {% set maxLen = max(translation|length, maxLen) %}
    {% endfor %}

    {# Value falls back to highlight instead of default #}
    {% set highlight = field.highlight|string %}
    {% set value = (value ?? default ?? highlight)|string %}

    {% for key, text in field.options %}
      {% set key = key|string %}
      {% set id = (field.id ?? ("toggle_" ~ field.name)) ~ key %}
      {% set translation = text|t|trim %}

      <input type="radio"
             value="{{ key }}"
             id="{{ id }}"
             name="{{ (scope ~ field.name)|fieldName }}"
             {% if highlight is same as(key) %}class="highlight"{% endif %}
             {% if field.disabled or isDisabledToggleable %}disabled="disabled"{% endif %}
             {% if key is same as(value) %}checked="checked"{% endif %}
             {% if required %}required="required"{% endif %}
             {% if field.tabindex %}tabindex="{{ field.tabindex }}"{% endif %}
      />
      <label for="{{ id }}">{{ (macro.spanToggle(translation, maxLen, field.markdown)|trim)|raw }}</label>
    {% endfor %}
  </div>
{% endblock %}
