@props([
    'checked' => false,
    'loadingTarget' => null,
    'title' => null,
    'width' => 56, // total toggle width in px
    'height' => 24, // total toggle height in px
    'circlePadding' => 2, // px from top/left
])

@php
    $circleSize = $height - 2 * $circlePadding;
    $translateX = $width - $circleSize - 2 * $circlePadding;
@endphp

<button type="button" role="switch" aria-checked="{{ $checked ? 'true' : 'false' }}" wire:loading.attr="disabled"
    @if ($loadingTarget) wire:target="{{ $loadingTarget }}" @endif
    {{ $attributes->merge(['class' => 'relative rounded-full transition text-xs font-medium']) }}
    style="width: {{ $width }}px; height: {{ $height }}px;">

    {{-- Track --}}
    <span
        class="absolute inset-0 rounded-full transition-colors
               {{ $checked ? 'bg-emerald-500' : 'bg-red-500 dark:bg-red-700' }}">
        {{-- Optional title inside track --}}
        @if ($title)
            <span wire:loading.remove @if ($loadingTarget) wire:target="{{ $loadingTarget }}" @endif
                class="absolute inset-0 flex items-center justify-center text-white pointer-events-none">
                {{ $title }}
            </span>
        @endif
    </span>

    {{-- Toggle circle --}}
    <span wire:loading.remove @if ($loadingTarget) wire:target="{{ $loadingTarget }}" @endif
        class="absolute bg-white rounded-full shadow transition-transform duration-200"
        style="
            top: {{ $circlePadding }}px;
            left: {{ $circlePadding }}px;
            width: {{ $circleSize }}px;
            height: {{ $circleSize }}px;
            transform: translateX({{ $checked ? $translateX : 0 }}px);
        "></span>

    {{-- Loading spinner using Flux icon --}}
    <span wire:loading @if ($loadingTarget) wire:target="{{ $loadingTarget }}" @endif
        class="absolute inset-0 flex items-center justify-center text-white">
        <flux:icon.loading class="w-4 h-4" />
    </span>
</button>
