{# Custom image upload with preview, built on ClearableFileInput #}
<div class="space-y-2">
  <div>
    {% if widget.is_initial and widget.value %}
      {% if widget.value.url %}
        <img id="preview_{{ widget.attrs.id }}" src="{{ widget.value.url }}" alt="Current image" class="max-h-56 rounded border" />
      {% else %}
        <img id="preview_{{ widget.attrs.id }}" alt="Current image" class="hidden max-h-56 rounded border" />
      {% endif %}
    {% else %}
      <img id="preview_{{ widget.attrs.id }}" alt="Preview" class="hidden max-h-56 rounded border" />
    {% endif %}
  </div>

  <div class="flex items-center gap-3">
    <input type="file" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %} />
    <span id="filename_{{ widget.attrs.id }}" class="text-sm text-gray-600 truncate"></span>
    {% if not widget.required and widget.is_initial %}
      <label class="inline-flex items-center gap-2 text-sm text-gray-700">
        <input type="checkbox" name="{{ widget.clear_checkbox_name }}" id="{{ widget.clear_checkbox_id }}" />
        {{ widget.clear_checkbox_label }}
      </label>
    {% endif %}
  </div>

  {% if widget.is_initial and widget.value and widget.value.url %}
    <div>
      <a href="{{ widget.value.url }}" target="_blank" class="text-xs text-blue-600 hover:underline">Open current image</a>
    </div>
  {% endif %}

  <script>
    (function(){
      const input = document.getElementById('{{ widget.attrs.id }}');
      const preview = document.getElementById('preview_{{ widget.attrs.id }}');
      const filenameEl = document.getElementById('filename_{{ widget.attrs.id }}');
      if (!input || !preview) return;
      input.addEventListener('change', function (e) {
        const file = input.files && input.files[0];
        if (!file) return;
        if (filenameEl) filenameEl.textContent = file.name;
        const url = URL.createObjectURL(file);
        preview.src = url;
        preview.classList.remove('hidden');
      });
    })();
  </script>
</div>
