<div class="modal" id="imagePickerModal" style="display: none;">
    <div class="modal-content" style="max-width: 90%; height: 90vh; display: flex; flex-direction: column; padding: 0;">
        <div class="modal-header" style="padding: 1.5rem; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0; font-weight: 600;">Select Image</h3>
            <button type="button" class="btn-close" onclick="closeImagePicker()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #64748b;">&times;</button>
        </div>
        
        <div class="modal-body" style="flex: 1; overflow: hidden; display: flex;">
            <!-- Folders Sidebar -->
            <div id="modalFolders" style="width: 200px; border-right: 1px solid #f1f5f9; overflow-y: auto; padding: 1rem; background: #f8fafc;">
                <div class="folder-item active" onclick="fetchModalImages()" style="padding: 10px; border-radius: 8px; cursor: pointer; margin-bottom: 5px; font-weight: 500; transition: all 0.2s;">
                    <i class="fas fa-folder-open" style="margin-right: 8px; color: #d90404;"></i> All Images
                </div>
                <div id="foldersList"></div>
            </div>
            
            <!-- Images Grid -->
            <div id="modalImagesGrid" style="flex: 1; overflow-y: auto; padding: 1.5rem; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 1rem; align-content: start;">
                <!-- Skeleton loader or empty state -->
            </div>
        </div>
        
        <div class="modal-footer" style="padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 10px;">
            <button class="btn btn-secondary" onclick="closeImagePicker()">Cancel</button>
            <button class="btn btn-primary" id="confirmImageSelect" disabled>Select Image</button>
        </div>
    </div>
</div>

<style>
    .folder-item:hover { background: #e2e8f0; }
    .folder-item.active { background: #d90404; color: white !important; }
    .folder-item.active i { color: white !important; }
    
    .modal-image-card {
        aspect-ratio: 1;
        border-radius: 12px;
        overflow: hidden;
        border: 2px solid transparent;
        cursor: pointer;
        position: relative;
        transition: all 0.2s;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    
    .modal-image-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    .modal-image-card.selected { border-color: #d90404; background: rgba(217, 4, 4, 0.05); }
    .modal-image-card.selected::after {
        content: '\f058';
        font-family: 'Font Awesome 6 Free';
        font-weight: 900;
        position: absolute;
        top: 5px;
        right: 5px;
        color: #d90404;
        background: white;
        border-radius: 50%;
        font-size: 1.2rem;
    }
    
    .modal-image-card img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
</style>

<script>
    let selectedImageUrl = null;
    let targetInputId = null;
    let targetPreviewId = null;

    function openImagePicker(inputId, previewId) {
        targetInputId = inputId;
        targetPreviewId = previewId;
        openModal('imagePickerModal');
        fetchModalFolders();
        fetchModalImages();
    }

    function closeImagePicker() {
        closeModal('imagePickerModal');
    }

    function fetchModalFolders() {
        fetch('{{ route("admin.modal.folders") }}')
            .then(res => res.json())
            .then(folders => {
                const list = document.getElementById('foldersList');
                list.innerHTML = folders.map(f => `
                    <div class="folder-item" onclick="fetchModalImages(${f.id}, this)" style="padding: 10px; border-radius: 8px; cursor: pointer; margin-bottom: 5px; font-weight: 500; transition: all 0.2s;">
                        <i class="fas fa-folder" style="margin-right: 8px; color: #64748b;"></i> ${f.name}
                    </div>
                `).join('');
            });
    }

    function fetchModalImages(folderId = '', element = null) {
        if (element) {
            document.querySelectorAll('.folder-item').forEach(i => i.classList.remove('active'));
            element.classList.add('active');
        }
        
        const grid = document.getElementById('modalImagesGrid');
        grid.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 2rem; color: #64748b;"><i class="fas fa-spinner fa-spin"></i> Loading images...</div>';
        
        fetch(\`/admin/modal/images/\${folderId}\`)
            .then(res => res.json())
            .then(images => {
                if (images.length === 0) {
                    grid.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 2rem; color: #64748b;">No images found in this folder.</div>';
                    return;
                }
                grid.innerHTML = images.map(img => `
                    <div class="modal-image-card" onclick="selectModalImage(\${img.id}, '\${img.path}', this)">
                        <img src="/\${(img.path || '').replace(/^\/+/, '').split('/').map(s => encodeURIComponent(s)).join('/')}" alt="Image">
                    </div>
                `).join('');
            });
    }

    function selectModalImage(id, path, element) {
        document.querySelectorAll('.modal-image-card').forEach(c => c.classList.remove('selected'));
        element.classList.add('selected');
        selectedImageUrl = path;
        document.getElementById('confirmImageSelect').disabled = false;
    }

    document.getElementById('confirmImageSelect').onclick = function() {
        if (selectedImageUrl) {
            document.getElementById(targetInputId).value = selectedImageUrl;
            if (targetPreviewId) {
                document.getElementById(targetPreviewId).src = '/' + selectedImageUrl;
                document.getElementById(targetPreviewId).style.display = 'block';
            }
            closeImagePicker();
        }
    };
</script>
