<div id="imagePickerModal" class="modal">
    <div class="modal-content">
        <!-- Sticky Header -->
        <div class="modal-header" style="display:flex; justify-content:space-between; align-items:center; padding: 1.2rem 2rem; border-bottom: 1px solid #edf2f7; background: #fff; flex-shrink: 0; z-index: 10;">
            <div style="display: flex; align-items: center; gap: 15px;">
                <h3 style="margin:0; color: #1a202c; font-weight: 700; font-size: 1.25rem;">Select Image</h3>
                <span id="currentPath" style="padding: 4px 12px; background: #f1f5f9; border-radius: 20px; font-size: 0.75rem; font-weight: 700; color: var(--primary-red); text-transform: uppercase;">Root</span>
            </div>
            <button type="button" class="btn btn-secondary" onclick="closePicker()" style="padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: #f1f5f9; color: #64748b;">
                <i class="fas fa-times" style="font-size: 0.9rem;"></i>
            </button>
        </div>

        <div style="flex: 1; overflow-y: auto; background: #fff; padding: 1.5rem 2rem;">
            <!-- 1. Upload Box -->
            <div id="pickerUploadBox" style="margin-bottom: 2rem; padding: 1.5rem; background: #f8fafc; border-radius: 16px; border: 2px dashed #cbd5e0; transition: 0.3s;">
                <form id="pickerUploadForm" onsubmit="handlePickerUpload(event)" enctype="multipart/form-data" style="display: flex; align-items: center; gap: 20px; margin: 0;">
                    @csrf
                    <input type="hidden" name="folder_id" id="pickerFolderId">
                    <div style="flex: 1;">
                        <input type="file" name="images[]" multiple required accept="image/*" style="font-size: 0.85rem; width: 100%; cursor: pointer; color: #64748b;">
                    </div>
                    <button type="submit" class="btn btn-primary" id="pickerUploadBtn" style="white-space: nowrap; padding: 0.6rem 1.5rem; border-radius: 10px; font-size: 0.9rem;">
                        <i class="fas fa-cloud-upload-alt" style="margin-right: 8px;"></i> Upload Now
                    </button>
                </form>
            </div>

            <!-- 2. Folders Section -->
            <div style="margin-bottom: 2rem;">
                <h4 style="font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; margin-bottom: 1rem; font-weight: 800;">Folders</h4>
                <div id="pickerFolders" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px;">
                    <!-- Folders Injected Here -->
                </div>
            </div>

            <!-- 3. Images Section -->
            <div>
                <h4 style="font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; color: #94a3b8; margin-bottom: 1rem; font-weight: 800;">Images</h4>
                <div id="pickerImages" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 1rem;">
                    <!-- Images Injected Here -->
                </div>
                <!-- Pagination -->
                <div id="pickerPagination" class="pagination" style="margin: 2.5rem 0; display: flex; justify-content: center; gap: 8px;"></div>
            </div>
        </div>

        <!-- Sticky Footer -->
        <div class="modal-footer" style="padding: 1.2rem 2rem; border-top: 1px solid #edf2f7; display:flex; justify-content:flex-end; align-items: center; gap: 15px; background: #fff; flex-shrink: 0; z-index: 10;">
            <span id="selectionInfo" style="margin-right: auto; color: #64748b; font-size: 0.85rem; font-weight: 600;">0 image(s) selected</span>
            <button type="button" class="btn btn-secondary" onclick="closePicker()" style="font-weight: 600; padding: 0.7rem 1.5rem;">Cancel</button>
            <button type="button" class="btn btn-primary" id="confirmSelectionBtn" onclick="confirmSelection()" style="padding: 0.7rem 2.5rem; border-radius: 12px; font-weight: 700;">
                Confirm Selection
            </button>
        </div>
    </div>
</div>

<style>
    #imagePickerModal .modal-content {
        max-width: 1100px;
        width: 95%;
        height: 90vh;
        background: #fff;
        border-radius: 20px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }

    #imagePickerModal .folder-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 18px;
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        margin: 5px;
        min-width: 150px;
    }

    #imagePickerModal .folder-card:hover {
        background: #f8fafc;
        border-color: var(--primary-red);
        transform: translateY(-2px);
    }

    #imagePickerModal .folder-card.active {
        border-color: var(--primary-red);
        background: #fff5f5;
        border-width: 2px;
    }

    #imagePickerModal .folder-card i {
        font-size: 1.25rem;
        color: #ffd43b;
    }

    #imagePickerModal .folder-card span {
        font-size: 0.9rem;
        font-weight: 700;
        color: #1e293b;
    }

    #imagePickerModal .picker-item {
        background: #fff;
        border: 1px solid #e2e8f0;
        border-radius: 14px;
        padding: 8px;
        cursor: pointer;
        transition: all 0.2s ease;
        position: relative;
        aspect-ratio: 1;
        margin: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: visible; /* Crucial for tick */
    }

    #imagePickerModal .picker-item:hover {
        border-color: var(--primary-red);
        transform: translateY(-4px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    }

    /* THE RED TICK */
    #imagePickerModal .picker-item.selected {
        border-color: var(--primary-red);
        border-width: 2px;
        box-shadow: 0 0 0 4px rgba(217, 4, 4, 0.1);
    }

    #imagePickerModal .picker-item.selected::after {
        content: '\f00c';
        font-family: 'Font Awesome 6 Free';
        font-weight: 900;
        position: absolute;
        top: -10px;
        right: -10px;
        background: var(--primary-red);
        color: white;
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        border: 3px solid white;
        font-size: 0.85rem;
        box-shadow: 0 4px 10px rgba(217, 4, 4, 0.3);
        z-index: 100;
    }

    #imagePickerModal .picker-thumb {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 10px;
    }

    @media (max-width: 768px) {
        #imagePickerModal .folder-grid {
            grid-template-columns: repeat(2, 1fr) !important;
        }
    }

    @media (max-width: 640px) {
        .modal-content {
            width: 100% !important;
            height: 100vh !important;
            border-radius: 0 !important;
        }
        #pickerFolders {
            grid-template-columns: repeat(2, 1fr) !important;
        }
    }
</style>

<script>
    window.ADMIN_BASE_URL = "{{ rtrim(url('/'), '/') }}";
    let selectionMode = 'single'; // 'single' or 'multiple'
    let selectedImages = [];
    let currentPickerFolder = 'root';
    let targetInputId = '';
    let targetPreviewId = '';
    let onConfirmCallback = null;

    function openPicker(mode = 'single', inputId = '', previewId = '', callback = null) {
        selectionMode = mode;
        targetInputId = inputId;
        targetPreviewId = previewId;
        onConfirmCallback = callback;
        selectedImages = [];
        updateSelectionUI();

        const modal = document.getElementById('imagePickerModal');
        modal.style.display = 'flex';
        setTimeout(() => modal.classList.add('show'), 10);

        fetchImages('root');
    }

    function closePicker() {
        const modal = document.getElementById('imagePickerModal');
        modal.classList.remove('show');
        setTimeout(() => modal.style.display = 'none', 300);
    }

    async function fetchImages(folderId, folderName = '', page = 1) {
        currentPickerFolder = folderId;
        document.getElementById('pickerFolderId').value = (folderId === 'root' ? '' : folderId);
        document.getElementById('currentPath').innerText = (folderName || 'Root');

        const response = await fetch(`{{ route('admin.images.ajax') }}?folder_id=${folderId}&page=${page}`);
        const data = await response.json();

        renderFolders(data.folders);
        renderPicker(data);
    }

    function renderFolders(folders) {
        const foldersDiv = document.getElementById('pickerFolders');
        let html = `
            <div class="folder-card ${currentPickerFolder === 'root' ? 'active' : ''}" onclick="fetchImages('root', 'Root')">
                <i class="fas fa-home"></i> <span>Root</span>
            </div>
        `;

        if (folders && folders.length > 0) {
            folders.forEach(folder => {
                html += `
                    <div class="folder-card ${currentPickerFolder == folder.id ? 'active' : ''}" onclick="fetchImages('${folder.id}', '${folder.name}')">
                        <i class="fas fa-folder"></i> <span>${folder.name}</span>
                    </div>
                `;
            });
        }
        foldersDiv.innerHTML = html;
    }

    function renderPicker(data) {
        const imagesDiv = document.getElementById('pickerImages');
        const paginationDiv = document.getElementById('pickerPagination');

        imagesDiv.innerHTML = '';

        if (data.images.data && data.images.data.length > 0) {
            data.images.data.forEach(image => {
                const isSelected = selectedImages.find(img => img.id === image.id);
                const imgPath = (image.path || '').replace(/^\/+/, '');
                const encodedPath = imgPath ? imgPath.split('/').map(s => encodeURIComponent(s)).join('/') : '';
                const imgSrc = encodedPath ? (window.ADMIN_BASE_URL ? window.ADMIN_BASE_URL + '/' + encodedPath : '/' + encodedPath) : '';
                imagesDiv.innerHTML += `
                    <div class="picker-item ${isSelected ? 'selected' : ''}" onclick="toggleSelect(${JSON.stringify(image).replace(/"/g, '&quot;')}, this)">
                        <img src="${imgSrc}" class="picker-thumb" alt="Image" onerror="this.style.background='#f1f5f9'; this.src='';">
                    </div>
                `;
            });
        } else {
            imagesDiv.innerHTML = `
                <div style="grid-column: 1/-1; text-align:center; color:#94a3b8; padding: 4rem 2rem; background: #f8fafc; border-radius: 12px; border: 1px dashed #e2e8f0;">
                    <i class="fas fa-images" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.3;"></i>
                    <p style="font-weight: 600; font-size: 0.9rem;">No images found in this folder</p>
                </div>
            `;
        }

        renderPagination(data.images, paginationDiv);
    }

    function renderPagination(data, container) {
        container.innerHTML = '';
        if (data.last_page <= 1) return;

        for (let i = 1; i <= data.last_page; i++) {
            const activeClass = i === data.current_page ? 'active' : '';
            container.innerHTML += `<button class="btn btn-secondary btn-sm ${activeClass}" onclick="fetchImages('${currentPickerFolder}', '', ${i})">${i}</button>`;
        }
    }

    function toggleSelect(image, element) {
        if (selectionMode === 'single') {
            selectedImages = [image];
            const allSelected = document.querySelectorAll('.picker-item.selected');
            allSelected.forEach(el => el.classList.remove('selected'));
            element.classList.add('selected');
        } else {
            const index = selectedImages.findIndex(img => img.id === image.id);
            if (index > -1) {
                selectedImages.splice(index, 1);
                element.classList.remove('selected');
            } else {
                selectedImages.push(image);
                element.classList.add('selected');
            }
        }
        updateSelectionUI();
    }

    function updateSelectionUI() {
        document.getElementById('selectionInfo').innerText = `${selectedImages.length} image(s) selected`;
    }

    function confirmSelection() {
        if (selectedImages.length === 0) {
            alert('Please select at least one image.');
            return;
        }

        if (onConfirmCallback) {
            onConfirmCallback(selectedImages);
        } else {
            // Default behavior: update input and preview
            const input = document.getElementById(targetInputId);
            const preview = document.getElementById(targetPreviewId);

            function encodedPath(path) {
                if (!path) return '';
                return path.replace(/^\/+/, '').split('/').map(s => encodeURIComponent(s)).join('/');
            }
            if (selectionMode === 'single') {
                const img = selectedImages[0];
                input.value = img.id;
                preview.innerHTML = `<img src="/${encodedPath(img.path)}" style="width:100%; height:100%; object-fit:cover;">`;
            } else {
                // Multiple selection for products gallery
                let ids = selectedImages.map(img => img.id);
                input.value = JSON.stringify(ids);

                preview.innerHTML = ''; // Clear placeholder
                selectedImages.forEach(img => {
                    preview.innerHTML += `
                        <div class="preview-item" style="width: 100px; height: 100px; border-radius: 8px; overflow: hidden; border: 1px solid #ddd; position: relative;">
                            <img src="/${encodedPath(img.path)}" style="width:100%; height:100%; object-fit:cover;">
                        </div>
                    `;
                });
            }
        }
        closePicker();
    }

    async function handlePickerUpload(e) {
        e.preventDefault();
        const btn = document.getElementById('pickerUploadBtn');
        btn.disabled = true;
        btn.innerText = 'Uploading...';

        const formData = new FormData(e.target);

        try {
            const response = await fetch("{{ route('admin.images.upload') }}", {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            // ImageController currently returns redirect, let's fix that or handle it
            // Since it's 'back()', we just refresh current folder
            fetchImages(currentPickerFolder);
            e.target.reset();
        } catch (error) {
            console.error(error);
            alert('Upload failed');
        } finally {
            btn.disabled = false;
            btn.innerText = 'Upload';
        }
    }
</script>