{{--
    Image / gallery input for the builder.
    Accepts a direct URL or an upload; uploads are routed through the builder's
    updatedUpload() so nested repeater paths resolve correctly.
--}}
@props(['path', 'id' => null, 'multiple' => false])

@php
    $inputId = $id ?: 'm-' . \Illuminate\Support\Str::slug(str_replace('.', '-', $path));
    $key = \Illuminate\Support\Str::after($path, 'form.');
@endphp

<div class="flex flex-col gap-2" wire:key="media-{{ $inputId }}">
    @php $current = data_get($this->form, $key); @endphp

    @if ($multiple)
        @if (is_array($current) && $current)
            <div class="grid grid-cols-4 gap-2">
                @foreach ($current as $i => $img)
                    <div class="relative group" wire:key="{{ $inputId }}-img-{{ $i }}">
                        <img src="{{ is_array($img) ? data_get($img, 'url') : $img }}" alt=""
                             class="w-full aspect-square object-cover rounded-lg border">
                        <button type="button" wire:click="removeMedia('{{ $path }}', {{ $i }})"
                                class="absolute top-1 end-1 rounded-full bg-red-600 text-white w-6 h-6 grid place-items-center opacity-0 group-hover:opacity-100 focus:opacity-100"
                                aria-label="{{ __('حذف الصورة') }}">
                            <x-ui.icon name="x-mark" class="w-3.5 h-3.5" />
                        </button>
                    </div>
                @endforeach
            </div>
        @endif
    @elseif ($current)
        <div class="relative inline-block">
            <img src="{{ $current }}" alt="" class="h-28 w-auto rounded-lg border object-cover">
            <button type="button" wire:click="removeMedia('{{ $path }}')"
                    class="absolute top-1 end-1 rounded-full bg-red-600 text-white w-6 h-6 grid place-items-center"
                    aria-label="{{ __('حذف الصورة') }}">
                <x-ui.icon name="x-mark" class="w-3.5 h-3.5" />
            </button>
        </div>
    @endif

    <div class="flex items-center gap-2">
        <input id="{{ $inputId }}" type="text" wire:model="{{ $path }}" dir="ltr"
               @if ($multiple) disabled placeholder="{{ __('ارفع صورًا بالأسفل') }}"
               @else placeholder="{{ __('رابط الصورة أو ارفع ملفًا') }}" @endif
               class="flex-1 rounded-lg border px-3 py-2 text-sm disabled:bg-gray-50">

        <label class="shrink-0 cursor-pointer rounded-lg border px-3 py-2 text-sm font-medium hover:bg-gray-50">
            <span wire:loading.remove wire:target="upload">{{ __('رفع') }}</span>
            <span wire:loading wire:target="upload">{{ __('جارٍ...') }}</span>
            <input type="file" accept="image/*" class="sr-only"
                   x-on:click="$wire.setUploadTarget('{{ $path }}')"
                   wire:model="upload">
        </label>
    </div>

    @error('upload') <p class="text-xs text-red-600">{{ $message }}</p> @enderror
</div>
