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

@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)));
    $isInline = $layout === 'inline';
@endphp

<x-ui.form.field
    :id="$id"
    :name="$name"
    :label="$label"
    :required="$required"
>
    <input type="hidden" name="{{ $name }}[]" value="">

    @if ($isInline)
        <div class="d-flex flex-wrap align-items-center gap-3">
            @forelse ($options as $value => $optionLabel)
                @php($checkboxId = $id.'_'.$value)
                <label for="{{ $checkboxId }}" class="d-inline-flex align-items-center gap-2 mb-0">
                    <input
                        id="{{ $checkboxId }}"
                        type="checkbox"
                        name="{{ $name }}[]"
                        value="{{ $value }}"
                        class="form-check-input flex-shrink-0 m-0"
                        @checked(in_array((string) $value, $currentSelected, true))
                    >
                    <span class="form-check-label">{{ $optionLabel }}</span>
                </label>
            @empty
                <div class="text-muted small">
                    {{ __('common.no_options') }}
                </div>
            @endforelse
        </div>
    @else
        <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>
    @endif
</x-ui.form.field>
