@props([
    'name',
    'label' => null,
    'options' => [],
    'selected' => [],
    'required' => false,
    'columns' => 2,
])

@php
    $id = $attributes->get('id') ?? $name;
    $submitted = old($name);
    $currentSelected = $submitted !== null ? (array) $submitted : (array) $selected;
    $currentSelected = array_map('strval', $currentSelected);

    $colClass = 'col-md-'.max(1, (int) floor(12 / max(1, (int) $columns)));
@endphp

<x-ui.form.field
    :id="$id"
    :name="$name"
    :label="$label"
    :required="$required"
>
    <input type="hidden" name="{{ $name }}[]" value="">
    <div class="row g-2">
        @forelse ($options as $value => $optionLabel)
            @php($checkboxId = $id.'_'.$value)
            <div class="{{ $colClass }}">
                <div class="form-check">
                    <input
                        id="{{ $checkboxId }}"
                        type="checkbox"
                        name="{{ $name }}[]"
                        value="{{ $value }}"
                        class="form-check-input"
                        @checked(in_array((string) $value, $currentSelected, true))
                    >
                    <label for="{{ $checkboxId }}" class="form-check-label">
                        {{ $optionLabel }}
                    </label>
                </div>
            </div>
        @empty
            <div class="col-12 text-muted small">
                {{ __('common.no_options') }}
            </div>
        @endforelse
    </div>
</x-ui.form.field>
