{% from '_includes/forms' import text %}

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

{% set containerAttributes = {
    for: id,
    id: labelId,
}|merge(containerAttributes ?? []) %}

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

{% set inputAttributes = {
    type: 'radio',
    id: id,
    class: (class ?? [])|explodeClass|merge(['radio']),
    name: name ?? false,
    value: value ?? '1',
    checked: checked ?? false,
    autofocus: (autofocus ?? false) and not craft.app.request.isMobileBrowser(true),
    disabled: disabled ?? false,
    aria: {
        describedby: describedBy ?? false,
    },
}|merge(inputAttributes ?? [], recursive=true) %}

{{ tag('input', inputAttributes) }}

{% tag 'label' with containerAttributes %}
    {% if custom ?? false %}
        {{ 'Other:'|t('app') }}
    {% else %}
        <div class="flex flex-nowrap gap-xs">
            {% if icon or color %}
                {% 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>
            {% else %}
                {{ label }}
            {% endif %}
        </div>
    {% endif %}
{% endtag %}

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

    {% js %}
        (() => {
            const $radio = $('#{{ id|namespaceInputId }}');
            const $text = $('#{{ textId|namespaceInputId }}');
            $text.on('input', () => {
                $radio.val($text.val());
            });
        })();
    {% endjs %}
{% endif %}
