@props([
    'name' => null,
    'id' => null,
    'title' => null,
    'open' => false,
])

@php
    $modalId = $id ?? $name ?? 'modal-' . uniqid();
@endphp

<div
    x-data="{ open: @js($open) }"
    x-on:open-modal.window="if ($event.detail === '{{ $modalId }}' || $event.detail === '{{ $name }}') open = true"
    x-on:close-modal.window="if ($event.detail === '{{ $modalId }}' || $event.detail === '{{ $name }}' || !$event.detail) open = false"
    x-on:keydown.escape.window="open = false"
    {{ $attributes->merge(['class' => 'relative z-50']) }}
>
    <div
        x-show="open"
        x-cloak
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
        role="dialog"
        aria-modal="true"
        @if ($title) aria-labelledby="{{ $modalId }}-title" @endif
        id="{{ $modalId }}"
    >
        <div
            class="absolute inset-0 bg-black/40"
            @click="open = false"
            aria-hidden="true"
        ></div>

        <div
            x-show="open"
            x-transition.opacity
            class="relative z-10 w-full max-w-lg rounded-[var(--radius-lg)] border border-[var(--color-border)] bg-[var(--color-card)] shadow-[var(--shadow-lg)]"
            @click.stop
        >
            <div class="flex items-center justify-between gap-3 border-b border-[var(--color-border)] px-4 py-3">
                @if ($title)
                    <h2 id="{{ $modalId }}-title" class="text-base font-semibold text-[var(--color-text)]">
                        {{ $title }}
                    </h2>
                @else
                    <span></span>
                @endif

                <button
                    type="button"
                    class="rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-bg)] hover:text-[var(--color-text)]"
                    @click="open = false"
                    aria-label="Close"
                >
                    <x-ui.icon name="x" class="h-5 w-5" />
                </button>
            </div>

            <div class="px-4 py-4">
                {{ $slot }}
            </div>
        </div>
    </div>
</div>
