@props([
  'title' => 'Bloque',
  'name' => 'bloque',
  'required' => true,
  'accept' => 'image/*',
  'currentUrl' => null,
  'descripcion' => null,
  'imgLabel' => 'Imagen (JPG/PNG/WebP)',
  'descLabel' => 'Descripción',
])

@php
  $id = preg_replace('/[^a-z0-9_]/i','_', $name);
  $req = filter_var($required, FILTER_VALIDATE_BOOLEAN);
@endphp

<div {{ $attributes->merge(['class' => 'mt-6 border rounded-lg p-4']) }}
     x-data="{
       previews: [],
       onFileChange(e) {
         // Limpia previas URLs
         (this.previews||[]).forEach(u => { try{ URL.revokeObjectURL(u); }catch(_){} });
         this.previews = [];
         const files = Array.from(e.target.files || []);
         this.previews = files.map(f => URL.createObjectURL(f));
       },
       clear() {
         const input = $refs.file_{{ $id }};
         if (input) { input.value = ''; }
         (this.previews||[]).forEach(u => { try{ URL.revokeObjectURL(u); }catch(_){} });
         this.previews = [];
       }
     }">

  <h3 class="field is-required">{{ $title }}</h3>

  <div class="grid md:grid-cols-2 gap-4">
    <div>
      <label class="block text-sm text-gray-600 mb-1">
        {{ $imgLabel }} @if($req)*@endif
      </label>
      <input type="file" multiple
             x-ref="file_{{ $id }}"
             name="{{ $name }}[imagen][]"
             accept="{{ $accept }}"
             class="block w-full border rounded p-2"
             style="color:black"
             @change="onFileChange"
             @if($req) required @endif>
      <template x-if="(previews||[]).length">
        <div class="mt-3 grid grid-cols-2 md:grid-cols-3 gap-3">
          <template x-for="(u,idx) in previews" :key="idx">
            <div class="border rounded p-1">
              <img :src="u" alt="Vista previa" class="max-h-40 rounded border w-full object-contain bg-white">
            </div>
          </template>
          <div class="col-span-full mt-1">
            <button type="button" class="text-sm px-2 py-1 border rounded" @click="clear()">Quitar imágenes</button>
          </div>
        </div>
      </template>
      @if($currentUrl)
        <div class="mt-2 text-sm">
          <span class="text-gray-600">Actual:</span>
          <a href="{{ $currentUrl }}" target="_blank" class="text-blue-600 underline">ver imagen</a>
        </div>
      @endif
    </div>

    <div>
      <label class="field-label">{{ $descLabel }} @if($req)*@endif</label>
      <textarea name="{{ $name }}[descripcion]" rows="6"
                class="w-full border rounded p-2"
                style="color:black"
                placeholder="Escribe aquí..."
                @if($req) required @endif>{{ old($name.'.descripcion', $descripcion) }}</textarea>
    </div>
  </div>
</div>
