@props([
    'label',
    'name',
    'id' => '',
    'value' => null,
    'col' => 12,
    'existingImages' => [],
    'deleteRoute' => null,
    'primaryRoute' => null,
])

<div class="col-md-{{ $col }} col-12 mb-3">
    <label class="form-label mb-2">{{ $label }}</label>

    <div class="upload-box">
        <input class="form-control file-input" type="file" id="files{{ $name }}" name="{{ $name }}[]" multiple accept="image/*">
        <i class="fas fa-images upload-icon"></i>
        <span class="upload-text">{{ __('dashboard.drop_files_here') }}</span>
    </div>

    {{-- Existing Images (for edit mode) --}}
    @if(count($existingImages) > 0)
    <div class="existing-images mt-3">
        <label class="form-label mb-2 text-muted">{{ __('dashboard.current_images') }}</label>
        <div class="d-flex flex-wrap gap-2" id="existingImages{{ $name }}">
            @foreach($existingImages as $image)
                <div class="position-relative existing-image-item" data-id="{{ $image->id }}" style="width: 120px;">
                    <img src="{{ viewImage($image->image) }}" class="rounded border"
                         style="width: 120px; height: 120px; object-fit: cover;">
                    @if($image->is_primary ?? false)
                        <span class="badge bg-success position-absolute top-0 start-0 m-1">
                            <i class="ri-star-fill"></i>
                        </span>
                    @endif
                    <div class="position-absolute bottom-0 start-0 end-0 p-1 bg-dark bg-opacity-50 d-flex justify-content-center gap-1">
                        @if($primaryRoute && !($image->is_primary ?? false))
                            <button type="button" class="btn btn-success btn-sm set-primary-btn"
                                    data-url="{{ route($primaryRoute, $image->id) }}"
                                    title="{{ __('dashboard.set_primary') }}">
                                <i class="ri-star-line"></i>
                            </button>
                        @endif
                        @if($deleteRoute)
                            <button type="button" class="btn btn-danger btn-sm delete-image-btn"
                                    data-url="{{ route($deleteRoute, $image->id) }}"
                                    title="{{ __('dashboard.delete') }}">
                                <i class="ri-delete-bin-line"></i>
                            </button>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>
    </div>
    @endif

    {{-- New Images Preview --}}
    <div class="carousel-inner preview-container mt-3" id="preview{{ $name }}"></div>

    @error($name)
        <span class="text-danger d-block mt-2">
            <small class="errorTxt">{{ $message }}</small>
        </span>
    @enderror
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle delete existing image
    document.querySelectorAll('#existingImages{{ $name }} .delete-image-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const url = this.dataset.url;
            const imageItem = this.closest('.existing-image-item');

            Swal.fire({
                title: "{{ __('dashboard.are_you_sure') }}",
                text: "{{ __('dashboard.delete_image_warning') }}",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: "{{ __('dashboard.yes_delete') }}",
                cancelButtonText: "{{ __('dashboard.cancel') }}"
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch(url, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            imageItem.remove();
                            toastr.success(data.message);
                        } else {
                            toastr.error(data.message);
                        }
                    })
                    .catch(() => toastr.error("{{ __('dashboard.operation_failed') }}"));
                }
            });
        });
    });

    // Handle set primary image
    document.querySelectorAll('#existingImages{{ $name }} .set-primary-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const url = this.dataset.url;
            const imageItem = this.closest('.existing-image-item');

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Remove all primary badges
                    document.querySelectorAll('#existingImages{{ $name }} .badge.bg-success').forEach(b => b.remove());
                    // Add primary badge to this image
                    const img = imageItem.querySelector('img');
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-success position-absolute top-0 start-0 m-1';
                    badge.innerHTML = '<i class="ri-star-fill"></i>';
                    imageItem.insertBefore(badge, img.nextSibling);
                    // Hide this button
                    this.remove();
                    toastr.success(data.message);
                } else {
                    toastr.error(data.message);
                }
            })
            .catch(() => toastr.error("{{ __('dashboard.operation_failed') }}"));
        });
    });
});
</script>
@endpush
