@props([
    'id'           => '',       // unique ID
    'class'        => '',       // extra CSS classes
    'name'         => '',       // select name
    'options'      => [],       // array of options, optgroups, or rich option defs
    'selected'     => null,     // selected value (falls back to old())
    'placeholder'  => '',       // optional placeholder option (disabled)
    'style'        => '',       // raw style string
    'required'     => false,    // true/false or truthy value
    'autocomplete' => '',
])

@php
    // prefer old() value if present, otherwise selected prop
    $current = old($name, $selected);

    $isSelected = function ($value) use ($current) {
        // cast to string so '1' and 1 match
        return (string) $value === (string) $current;
    };

    $renderOption = function ($value, $label, $attrs = []) use ($isSelected) {
        $attrString = collect($attrs)->map(function ($v, $k) {
            if (is_bool($v)) return $v ? $k : '';
            return $k.'="'.e($v).'"';
        })->filter()->implode(' ');

        $selectedAttr = $isSelected($value) ? ' selected' : '';

        return '<option value="'.e($value).'"'.$selectedAttr.($attrString ? ' '.$attrString : '').'>'.e($label).'</option>';
    };
@endphp

<select id="{{ $id }}" name="{{ $name }}" autocomplete="{{ $autocomplete }}"
        {{ $attributes->merge(['class' => 'select '.$class]) }}
        @if($style !== '') style="{{ $style }}" @endif
        @required($required)>

    @if($placeholder !== '')
        <option value="" disabled @selected((string) $current === '')>
            {{ $placeholder }}
        </option>
    @endif

    @foreach($options as $key => $opt)
        {{-- optgroup: 'Group label' => [ ...options... ] --}}
        @if(is_array($opt) && is_string($key))
            <optgroup label="{{ $key }}">
                @foreach($opt as $value => $label)
                    {{-- allow rich options inside optgroups too --}}
                    @if(is_array($label) && array_key_exists('value', $label))
                        {!! $renderOption($label['value'], $label['label'] ?? $label['value'], $label['attrs'] ?? []) !!}
                    @else
                        {!! $renderOption($value, $label) !!}
                    @endif
                @endforeach
            </optgroup>

        {{-- rich option: [ 'value' => 'en', 'label' => 'English', 'attrs' => ['data-x' => 'y', 'disabled' => true] ] --}}
        @elseif(is_array($opt) && array_key_exists('value', $opt))
            {!! $renderOption($opt['value'], $opt['label'] ?? $opt['value'], $opt['attrs'] ?? []) !!}

        {{-- simple options: [ 'en' => 'English', ... ] --}}
        @else
            {!! $renderOption($key, $opt) !!}
        @endif
    @endforeach
</select>
