@props([
    'name',
    'existing' => null,
    'required' => false,
])

@php
    $hasExisting = ! empty($existing);
    $inputId = 'file_'.\Illuminate\Support\Str::random(8);
@endphp

<div x-data="{
        fileName: '',
        previewUrl: '',
        isImage: false,
        pick(event) {
            const file = event.target.files[0];
            if (! file) {
                this.reset();
                return;
            }
            this.fileName = file.name;
            this.isImage = file.type.startsWith('image/');
            this.previewUrl = this.isImage ? URL.createObjectURL(file) : '';
        },
        reset() {
            this.fileName = '';
            this.previewUrl = '';
            this.isImage = false;
        }
    }"
    class="space-y-2">

    @if($hasExisting)
        <div x-show="! fileName">
            <p class="text-xs text-slate-500 mb-1">Fichier actuel :</p>
            <x-file-preview :path="$existing" />
        </div>
    @endif

    <label for="{{ $inputId }}" class="file-dropzone" :class="fileName ? 'file-dropzone--filled' : ''">
        <svg class="file-dropzone-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
            <path stroke-linecap="round" stroke-linejoin="round" d="M21.44 11.05 12.25 20.24a5.5 5.5 0 0 1-7.78-7.78l9.19-9.19a3.5 3.5 0 0 1 4.95 4.95l-9.2 9.19a1.5 1.5 0 0 1-2.12-2.12l8.49-8.49"/>
        </svg>
        <div class="file-dropzone-text">
            <template x-if="! fileName">
                <span><span class="file-dropzone-accent">Choisir un fichier</span> ou glisser-déposer</span>
            </template>
            <template x-if="fileName">
                <span class="file-dropzone-filename" x-text="fileName"></span>
            </template>
        </div>
        <input id="{{ $inputId }}" type="file" name="{{ $name }}" class="sr-only"
               @change="pick($event)"
               {{ $required && ! $hasExisting ? 'required' : '' }}>
    </label>

    <template x-if="previewUrl">
        <div class="file-input-local-preview">
            <img :src="previewUrl" alt="Aperçu" class="file-input-local-thumb">
        </div>
    </template>
</div>
