@props([
    'items' => [],
    'multiple' => false,
])

@php
    $accordionItems = collect($items)->values();
@endphp

<div
    x-data="{
        multiple: @js((bool) $multiple),
        open: @js($multiple ? [] : null),
        toggle(key) {
            if (this.multiple) {
                this.open = this.open.includes(key)
                    ? this.open.filter(k => k !== key)
                    : [...this.open, key];
            } else {
                this.open = this.open === key ? null : key;
            }
        },
        isOpen(key) {
            return this.multiple ? this.open.includes(key) : this.open === key;
        }
    }"
    {{ $attributes->merge(['class' => 'divide-y divide-[var(--color-border)] rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-card)]']) }}
>
    @forelse ($accordionItems as $index => $item)
        @php
            $key = $item['key'] ?? "item-{$index}";
            $title = $item['title'] ?? $item['label'] ?? "Item {$index}";
            $content = $item['content'] ?? '';
        @endphp
        <div>
            <button
                type="button"
                class="flex w-full items-center justify-between gap-3 px-4 py-3 text-left text-sm font-medium text-[var(--color-text)] hover:bg-[var(--color-bg)]"
                @click="toggle(@js($key))"
                :aria-expanded="isOpen(@js($key))"
            >
                <span>{{ $title }}</span>
                <span
                    class="inline-flex shrink-0 text-[var(--color-text-muted)] transition-transform"
                    :class="isOpen(@js($key)) ? 'rotate-180' : ''"
                >
                    <x-ui.icon name="chevron-down" class="h-4 w-4" />
                </span>
            </button>
            <div x-show="isOpen(@js($key))" x-cloak class="px-4 pb-3 text-sm text-[var(--color-text-muted)]">
                {!! $content !!}
            </div>
        </div>
    @empty
        {{ $slot }}
    @endforelse
</div>
