{% from '_includes/forms' import text %}
{%- apply spaceless %}

{% set id = id ?? "checkbox#{random()}" %}
{% set label = checkboxLabel ?? label ?? null %}
{% set labelId = labelId ?? "#{id}-label" %}
{% set color = color ?? null %}
{% set icon = icon ?? null %}

{% set aria = (inputAttributes.aria ?? {})|merge(aria ?? {}) %}
{% set inputAttributes = {
    id: id,
    class: (class ?? [])|explodeClass|merge([
        (targetPrefix ?? toggle ?? reverseToggle ?? false) ? 'fieldtoggle' : null,
        'checkbox'
    ]|filter),
    checked: (checked ?? false) and checked,
    autofocus: (autofocus ?? false) and not craft.app.request.isMobileBrowser(true),
    disabled: (disabled ?? false) ? true : false,
    aria: aria|merge({
        labelledby: (aria.label ?? false) ? false : (labelledBy ?? false),
        describedby: describedBy ?? aria.describedby ?? false,
    }),
    data: (data ?? {})|merge({
        'target-prefix': targetPrefix ?? false,
        target: toggle ?? false,
        'reverse-target': reverseToggle ?? false,
    }),
}|merge(inputAttributes ?? [], recursive=true) %}

{% if block('attr') is defined %}
    {%- set inputAttributes = inputAttributes|merge(('<div ' ~ block('attr') ~ '>')|parseAttr, recursive=true) %}
{% endif %}

{% if name is defined and (name|length < 3 or name|slice(-2) != '[]') %}
    {{ hiddenInput(name, '') }}
{% endif %}

{{ input('checkbox', name ?? null, value ?? 1, inputAttributes) }}

{% tag 'label' with {
    for: id,
    id: labelId,
} %}
    {% if custom ?? false %}
        {{ 'Custom:'|t('app') }}
    {% else %}
        {% if icon or color %}
            <div class="flex flex-nowrap gap-xs">
                {% if icon %}
                    {% set style = {
                        '--icon-color': color,
                    }|filter %}
                    {{ tag('span', {
                        class: 'cp-icon puny',
                        style,
                        html: iconSvg(icon),
                    }) }}
                {% else %}
                    <div class="color small">
                        <div class="color-preview" style="background-color: {{ color }}"></div>
                    </div>
                {% endif %}
                <span>{{ label }}</span>
            </div>
        {% else %}
            {{ label }}
        {% endif %}

    {% endif %}
    {% if info ?? null %}
        <span class="info">{{ info|md|raw }}</span>
    {% endif %}
{% endtag %}

{% if custom ?? false %}
    <div class="custom-option-wrapper">
        {{ text({
            value: value ?? null,
            class: 'small custom-option-input',
            labelledBy: labelId,
        }) }}
    </div>
{% endif %}
{% endapply -%}
