@props(['name' => null, 'value' => null, 'label' => null, 'icon' => '', 'color' => '', 'active' => false])

@php
    $isActive = $active || $attributes->get('checked') || str_contains($attributes->get('class', ''), 'active');
@endphp

<label {{ $attributes->only('class')->merge(['class' => 'custom-control custom-control-primary ' . ($isActive ? 'active' : '')]) }} style="display: inline-flex; cursor: pointer;">
    <input type="radio" 
        {{ $attributes->except('class')->merge([
            'class' => 'custom-control ' . ($name ?? '') . ' radio',
            'name' => $name,
            'value' => $value,
            'checked' => $isActive
        ]) }} 
    />
    <i style="color:#{{ $color }}" class="{{ $icon }}"></i> 
    <span class="">{{ $label }}</span>
</label>

<script>
    if (typeof statusRadioScriptInitialized === 'undefined') {
        window.statusRadioScriptInitialized = true;
        document.addEventListener("DOMContentLoaded", function() {
            // Use event delegation to handle potential dynamic content and avoid multiple listeners
            document.body.addEventListener('change', function(e) {
                if (e.target && e.target.matches('.custom-control.radio')) {
                    const radio = e.target;
                    // Find all radios with the same name
                    const name = radio.name;
                    // Provide a more specific scope if possible, or search globally if names are unique enough
                    // The original logic used a class selector matching the name, which works if the name is safe
                    document.querySelectorAll(`.custom-control.${name}`).forEach(el => {
                        // Remove active class from the wrapper (label)
                        if (el.parentElement.classList.contains('custom-control-primary')) {
                             el.parentElement.classList.remove('active');
                        }
                    });
                    // Add active class to the checked wrapper
                    if (radio.parentElement.classList.contains('custom-control-primary')) {
                        radio.parentElement.classList.add('active');
                    }
                }
            });
        });
    }
</script>
