@props([
    'items' => [],
    'active' => null,
])

@php
    $tabItems = collect($items)->values();
    $initial = $active ?? ($tabItems->first()['key'] ?? ($tabItems->first()['label'] ?? 'tab-0'));
@endphp

<div x-data="{ active: @js($initial) }" {{ $attributes->merge(['class' => 'w-full']) }}>
    @if ($tabItems->isNotEmpty())
        <div class="flex flex-wrap gap-1 border-b border-[var(--color-border)]" role="tablist">
            @foreach ($tabItems as $index => $item)
                @php
                    $key = $item['key'] ?? ($item['label'] ?? "tab-{$index}");
                    $label = $item['label'] ?? $key;
                @endphp
                <button
                    type="button"
                    role="tab"
                    :aria-selected="active === @js($key)"
                    @click="active = @js($key)"
                    class="px-3 py-2 text-sm font-medium border-b-2 -mb-px transition-colors"
                    :class="active === @js($key)
                        ? 'border-[var(--color-primary)] text-[var(--color-primary)]'
                        : 'border-transparent text-[var(--color-text-muted)] hover:text-[var(--color-text)]'"
                >
                    {{ $label }}
                </button>
            @endforeach
        </div>

        <div class="pt-4">
            @foreach ($tabItems as $index => $item)
                @php
                    $key = $item['key'] ?? ($item['label'] ?? "tab-{$index}");
                    $panelSlot = ${'panel_' . str_replace('-', '_', $key)} ?? null;
                @endphp
                <div x-show="active === @js($key)" x-cloak role="tabpanel">
                    @if ($panelSlot)
                        {{ $panelSlot }}
                    @elseif (!empty($item['content']))
                        {!! $item['content'] !!}
                    @endif
                </div>
            @endforeach

            {{ $slot }}
        </div>
    @else
        {{ $slot }}
    @endif
</div>
