<?php ob_start(); ?>

<div class="content-header">
    <h2><?= __('admin.gallery_images.title', [':album' => $album['title']]) ?></h2>
    <div class="header-actions">
        <a href="/admin/gallery/edit/<?= (int) $album['id'] ?>" class="btn btn-secondary"><?= __('admin.gallery_images.edit_album') ?></a>
        <a href="/admin/gallery" class="btn btn-secondary"><?= __('admin.gallery_images.back') ?></a>
    </div>
</div>

<!-- Album meta -->
<div class="form-card" style="margin-bottom:1.5rem;">
    <div style="display:flex;gap:1rem;align-items:flex-start;">
        <?php if (!empty($album['cover_image'])): ?>
        <img src="<?= e(thumb_url($album['cover_image'])) ?>"
             alt="Cover"
             style="width:80px;height:80px;object-fit:cover;border-radius:6px;flex-shrink:0;">
        <?php endif; ?>
        <div>
            <strong><?= e($album['title']) ?></strong>
            <?php if (!empty($album['description'])): ?>
            <p style="margin:0.25rem 0 0;color:#666;font-size:0.9rem;"><?= e($album['description']) ?></p>
            <?php endif; ?>
            <span class="badge <?= $album['is_visible'] ? 'badge-success' : 'badge-draft' ?>" style="margin-top:0.4rem;display:inline-block;">
                <?= $album['is_visible'] ? __('admin.common.visible') : __('admin.common.hidden') ?>
            </span>
            <span style="margin-left:0.5rem;color:#888;font-size:0.85rem;"><?= __('admin.gallery_images.image_count', [':count' => count($images)]) ?></span>
        </div>
    </div>
</div>

<!-- Upload form -->
<div class="form-card" style="margin-bottom:1.5rem;">
    <h4 style="margin-top:0;"><?= __('admin.gallery_images.upload_image') ?></h4>
    <form method="POST"
          action="/admin/gallery/album/<?= (int) $album['id'] ?>/upload"
          enctype="multipart/form-data"
          id="galleryUploadForm"
          class="admin-form">
        <?= $csrf->field() ?>

        <!-- Upload zone: hidden native input + visual drop area -->
        <!-- Phase 2.2: Multi-file support (accept multiple files) -->
        <div class="form-group">
            <input type="file" id="gallery_image" name="image"
                   accept="image/jpeg,image/png,image/gif,image/webp"
                   multiple class="mm-file-input-hidden">
            <label for="gallery_image" class="mm-upload-zone" id="galleryDropZone">
                <span class="mm-upload-icon" aria-hidden="true"><svg width="52" height="52" viewBox="0 0 52 52" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="52" height="52" rx="13" fill="#dbeafe"/><path d="M26 36V22M18 29l8-9 8 9" stroke="#2563eb" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16 39h20" stroke="#2563eb" stroke-width="2" stroke-linecap="round" opacity="0.5"/></svg></span>
                <span class="mm-upload-primary"><?= __('admin.gallery_images.upload_click') ?></span>
                <span class="mm-upload-secondary"><?= __('admin.gallery_images.upload_drag') ?></span>
                <span class="mm-upload-hint"><?= __('admin.gallery_images.upload_formats') ?></span>
            </label>
            <div class="mm-upload-feedback" id="galleryUploadFeedback" aria-live="polite"></div>
        </div>

        <!-- Metadata fields -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
            <div class="form-group" style="margin:0;">
                <label for="upload_title"><?= __('admin.gallery_images.image_title') ?></label>
                <input type="text" id="upload_title" name="title" placeholder="<?= __('admin.gallery_images.image_title_placeholder') ?>">
            </div>
            <div class="form-group" style="margin:0;">
                <label for="alt_text"><?= __('admin.gallery_images.alt_text') ?></label>
                <input type="text" id="alt_text" name="alt_text"
                       placeholder="<?= __('admin.gallery_images.alt_text_placeholder') ?>">
            </div>
        </div>

        <div class="actions" style="justify-content:space-between;margin-top:1rem;">
            <button type="button" class="btn btn-secondary" id="galleryMediaPickerBtn"><?= __('admin.gallery_images.add_from_media') ?></button>
            <button type="submit" class="btn btn-primary" id="galleryUploadSubmit"><?= __('admin.common.upload') ?></button>
        </div>
    </form>
</div>

<script>
(function () {
    var fileInput = document.getElementById('gallery_image');
    var dropZone  = document.getElementById('galleryDropZone');
    var feedback  = document.getElementById('galleryUploadFeedback');
    var submitBtn = document.getElementById('galleryUploadSubmit');
    var form      = document.getElementById('galleryUploadForm');
    var pickerBtn = document.getElementById('galleryMediaPickerBtn');
    var albumId   = <?= (int) $album['id'] ?>;

    function hasFiles(e) {
        var types = e.dataTransfer && e.dataTransfer.types;
        if (!types) return false;
        for (var i = 0; i < types.length; i++) {
            if (types[i] === 'Files') return true;
        }
        return false;
    }

    // Phase 2.2: Multi-file support
    function updateFeedback() {
        if (!feedback || !fileInput) return;
        var count = fileInput.files ? fileInput.files.length : 0;
        if (count === 0) { feedback.textContent = ''; return; }
        if (count === 1) {
            feedback.textContent = fileInput.files[0].name;
        } else {
            feedback.textContent = count + ' <?= __('admin.gallery_images.files_selected') ?>';
        }
    }

    if (fileInput) {
        fileInput.addEventListener('change', updateFeedback);
    }

    // Phase 2.2: Multi-file AJAX upload – jede Datei einzeln senden.
    // Grund: PHP max_file_uploads kann auf 1 limitiert sein, was bei
    // multipart-Form-Submissions alle Dateien ausser der ersten verwirft.
    // Einzelne AJAX-Requests umgehen diese Beschränkung vollständig.
    if (form && submitBtn && fileInput) {
        form.addEventListener('submit', function (e) {
            var files = fileInput.files;

            // Einzelne Datei: normales Form-Submit (Rückwärtskompatibilität)
            if (!files || files.length <= 1) {
                submitBtn.disabled = true;
                // LRA: Spinner + i18n-Text statt leerem Button
                submitBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.uploading') ?>';
                return; // natürliches Submit
            }

            // Mehrere Dateien: AJAX-Upload, eine nach der anderen
            e.preventDefault();

            var total    = files.length;
            var done     = 0;
            var ok       = 0;
            var fail     = 0;
            var csrfToken = (form.querySelector('input[name="_csrf_token"]') || {}).value || '';
            var title     = (form.querySelector('[name="title"]')    || {}).value || '';
            var altText   = (form.querySelector('[name="alt_text"]') || {}).value || '';
            var uploadUrl = '/admin/gallery/album/' + albumId + '/upload';

            submitBtn.disabled = true;
            // LRA: Spinner + Zähler für Mehrfach-Upload
            submitBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span>0 / ' + total;
            if (feedback) feedback.textContent = '0 / ' + total + ' …';

            function uploadOne(file, idx) {
                var fd = new FormData();
                fd.append('_csrf_token', csrfToken);
                fd.append('title',       title);
                fd.append('alt_text',    altText);
                fd.append('image',       file, file.name);

                return fetch(uploadUrl, { method: 'POST', body: fd })
                    .then(function (res) {
                        done++;
                        // fetch folgt dem Redirect (302 → 200); res.ok = true bei Erfolg
                        if (res.ok) { ok++; } else { fail++; }
                        if (feedback) feedback.textContent = done + ' / ' + total + ' …';
                        // LRA: Button-Zähler mitführen
                        submitBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span>' + done + ' / ' + total;
                    })
                    .catch(function () {
                        done++;
                        fail++;
                        if (feedback) feedback.textContent = done + ' / ' + total + ' …';
                        submitBtn.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span>' + done + ' / ' + total;
                    });
            }

            // Sequenziell hochladen (verhindert sort_order-Race-Conditions)
            var chain = Promise.resolve();
            Array.from(files).forEach(function (file) {
                chain = chain.then(function () { return uploadOne(file); });
            });

            chain.then(function () {
                // LRA: Ergebnis im Button + Feedback-Zeile anzeigen
                if (fail === 0) {
                    submitBtn.innerHTML = '✓ ' + ok + ' <?= __('admin.gallery_images.upload_success_n') ?>';
                    submitBtn.style.background = '#16a34a';
                } else {
                    submitBtn.innerHTML = ok + ' <?= __('admin.gallery_images.upload_partial_ok') ?>, ' + fail + ' <?= __('admin.gallery_images.upload_partial_fail') ?>';
                    submitBtn.style.background = '#dc2626';
                }
                if (feedback) {
                    feedback.textContent = fail === 0
                        ? ok + ' <?= __('admin.gallery_images.upload_success_n') ?>'
                        : ok + ' <?= __('admin.gallery_images.upload_partial_ok') ?>, ' + fail + ' <?= __('admin.gallery_images.upload_partial_fail') ?>';
                    feedback.style.color = fail > 0 ? '#dc2626' : '#16a34a';
                }
                setTimeout(function () { location.reload(); }, 900);
            });
        });
    }

    // Drag & Drop into the zone (Phase 2.2: all files)
    if (dropZone && fileInput) {
        var zoneDragDepth = 0;

        dropZone.addEventListener('dragenter', function (e) {
            if (!hasFiles(e)) return;
            e.preventDefault(); e.stopPropagation();
            zoneDragDepth++;
            dropZone.classList.add('mm-zone-drag-over');
        });

        dropZone.addEventListener('dragover', function (e) {
            if (!hasFiles(e)) return;
            e.preventDefault(); e.stopPropagation();
            e.dataTransfer.dropEffect = 'copy';
        });

        dropZone.addEventListener('dragleave', function (e) {
            e.stopPropagation();
            zoneDragDepth--;
            if (zoneDragDepth <= 0) {
                zoneDragDepth = 0;
                dropZone.classList.remove('mm-zone-drag-over');
            }
        });

        dropZone.addEventListener('drop', function (e) {
            e.preventDefault(); e.stopPropagation();
            zoneDragDepth = 0;
            dropZone.classList.remove('mm-zone-drag-over');

            var files = e.dataTransfer && e.dataTransfer.files;
            if (!files || files.length === 0) return;

            if (typeof DataTransfer !== 'undefined') {
                try {
                    var dt = new DataTransfer();
                    // Phase 2.2: Add all files, not just first
                    for (var i = 0; i < files.length; i++) {
                        dt.items.add(files[i]);
                    }
                    fileInput.files = dt.files;
                    updateFeedback();
                } catch (err) {
                    // DataTransfer.items not supported – user must pick manually
                }
            }
        });
    }

    // Phase 2.2: Media picker button
    if (pickerBtn) {
        pickerBtn.addEventListener('click', function () {
            openGalleryMediaPicker(albumId);
        });
    }
}());

// Phase 2.2: Gallery media picker modal with folder navigation
function openGalleryMediaPicker(albumId) {
    var modal = document.createElement('div');
    modal.id = 'galleryMediaPickerModal';
    modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:10000;';

    var content = document.createElement('div');
    content.style.cssText = 'background:#fff;border-radius:8px;width:92%;max-width:760px;max-height:85vh;display:flex;flex-direction:column;';

    var header = document.createElement('div');
    header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;padding:1rem 1.5rem;border-bottom:1px solid #e5e7eb;flex-shrink:0;';
    header.innerHTML = '<h3 style="margin:0;font-size:1rem;"><?= __('admin.gallery_images.select_from_media') ?></h3>'
                     + '<button type="button" style="background:none;border:none;font-size:1.5rem;cursor:pointer;line-height:1;" onclick="document.getElementById(\'galleryMediaPickerModal\').remove();">&times;</button>';

    // Ordner-Leiste (wird nach API-Antwort befüllt)
    var folderBar = document.createElement('div');
    folderBar.id  = 'pickerFolderBar';
    folderBar.style.cssText = 'display:none;padding:0.6rem 1rem;border-bottom:1px solid #e5e7eb;flex-shrink:0;overflow-x:auto;white-space:nowrap;background:#f9fafb;';

    var body = document.createElement('div');
    body.id = 'pickerBody';
    body.style.cssText = 'flex:1;overflow-y:auto;padding:1rem 1.5rem;';
    body.innerHTML = '<p style="text-align:center;color:#888;"><?= __('admin.common.loading') ?></p>';

    var footer = document.createElement('div');
    footer.style.cssText = 'display:flex;justify-content:flex-end;gap:0.5rem;padding:1rem 1.5rem;border-top:1px solid #e5e7eb;flex-shrink:0;';
    footer.innerHTML = '<button type="button" class="btn btn-secondary" onclick="document.getElementById(\'galleryMediaPickerModal\').remove();"><?= __('admin.common.cancel') ?></button>'
                     + '<button type="button" class="btn btn-primary" id="addSelectedMediaBtn"><?= __('admin.common.add') ?></button>';

    content.appendChild(header);
    content.appendChild(folderBar);
    content.appendChild(body);
    content.appendChild(footer);
    modal.appendChild(content);
    document.body.appendChild(modal);

    var allFolders = [];
    var activeFolderId = null; // null = alle Bilder

    // Ordner-Buttons rendern
    function renderFolderBar(folders) {
        if (!folders || folders.length === 0) {
            folderBar.style.display = 'none';
            return;
        }
        allFolders = folders;
        folderBar.style.display = 'block';

        function buildBar(activeId) {
            var btnStyle = 'display:inline-block;margin-right:0.4rem;padding:0.25rem 0.7rem;border-radius:999px;border:1px solid #d1d5db;font-size:0.8rem;cursor:pointer;background:#fff;';
            var btnActiveStyle = btnStyle + 'background:#2563eb;color:#fff;border-color:#2563eb;';
            var html = '<button style="' + (activeId === null ? btnActiveStyle : btnStyle) + '" data-folder-id=""><?= __('admin.common.all') ?></button>';
            folders.forEach(function(f) {
                var active = activeId === f.id;
                html += '<button style="' + (active ? btnActiveStyle : btnStyle) + '" data-folder-id="' + f.id + '">📁 ' + escapeHtml(f.name) + '</button>';
            });
            folderBar.innerHTML = html;

            // Click-Handler
            Array.from(folderBar.querySelectorAll('button')).forEach(function(btn) {
                btn.addEventListener('click', function() {
                    var fid = btn.getAttribute('data-folder-id');
                    activeFolderId = fid === '' ? null : parseInt(fid, 10);
                    buildBar(activeFolderId);
                    loadImages(activeFolderId);
                });
            });
        }
        buildBar(activeFolderId);
    }

    // Bilder für Ordner laden und rendern
    function loadImages(folderId) {
        body.innerHTML = '<p style="text-align:center;color:#888;"><?= __('admin.common.loading') ?></p>';
        var url = '/admin/media/picker-data' + (folderId !== null ? '?folder=' + folderId : '');

        fetch(url)
            .then(function(res) { return res.json(); })
            .then(function(data) {
                var items = data.images || data.items || [];

                // Ordner-Bar beim ersten Laden aufbauen
                if (allFolders.length === 0 && data.folders && data.folders.length > 0) {
                    renderFolderBar(data.folders);
                }

                if (items.length === 0) {
                    body.innerHTML = '<p style="text-align:center;color:#999;"><?= __('admin.gallery_images.no_images_in_media') ?></p>';
                    return;
                }

                var html = '<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:0.75rem;">';
                items.forEach(function(item) {
                    var folderLabel = item.folder_name
                        ? '<span style="display:block;font-size:0.7rem;color:#6b7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;">📁 ' + escapeHtml(item.folder_name) + '</span>'
                        : '';
                    html += '<label style="cursor:pointer;display:flex;flex-direction:column;align-items:center;">'
                          + '<input type="checkbox" data-media-id="' + item.id + '" style="margin-bottom:0.3rem;">'
                          + '<img src="' + escapeHtml(item.thumb_url) + '" style="width:100%;aspect-ratio:1;object-fit:cover;border-radius:4px;border:2px solid transparent;" alt="' + escapeHtml(item.name || '') + '" '
                          +   'onchange="" '
                          + '>'
                          + folderLabel
                          + '</label>';
                });
                html += '</div>';
                body.innerHTML = html;

                // Checkbox → Bild-Rahmen hervorheben
                Array.from(body.querySelectorAll('input[type="checkbox"]')).forEach(function(cb) {
                    cb.addEventListener('change', function() {
                        var img = cb.closest('label').querySelector('img');
                        if (img) img.style.borderColor = cb.checked ? '#2563eb' : 'transparent';
                    });
                });
            })
            .catch(function() {
                body.innerHTML = '<p style="color:#dc2626;"><?= __('admin.gallery_images.media_load_error') ?></p>';
            });
    }

    // Initial laden (alle Bilder + Ordner holen)
    loadImages(null);

    // "Hinzufügen"-Button
    document.getElementById('addSelectedMediaBtn').addEventListener('click', function() {
        var selected = Array.from(document.querySelectorAll('#galleryMediaPickerModal input[type="checkbox"]:checked')).map(function(cb) {
            return parseInt(cb.getAttribute('data-media-id'), 10);
        });

        if (selected.length === 0) {
            alert('<?= __('admin.gallery_images.select_media_warning') ?>');
            return;
        }

        var btn = document.getElementById('addSelectedMediaBtn');
        btn.disabled = true;

        fetch('/admin/gallery/album/' + albumId + '/add-from-media', {
            method:  'POST',
            headers: { 'Content-Type': 'application/json' },
            body:    JSON.stringify({ mediaIds: selected, _csrf_token: document.querySelector('input[name="_csrf_token"]').value })
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            document.getElementById('galleryMediaPickerModal').remove();
            if (data.ok) { location.reload(); }
        })
        .catch(function() { btn.disabled = false; });
    });
}

function escapeHtml(text) {
    var map = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'};
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
</script>

<!-- Images list -->
<?php if (empty($images)): ?>
<p class="text-muted"><?= __('admin.gallery_images.no_images') ?></p>
<?php else: ?>

<div class="content-header" style="margin-top:0;padding-top:0;">
    <h4 style="margin:0;"><?= __('admin.gallery_images.images_heading', [':count' => count($images)]) ?></h4>
    <small class="text-muted"><?= __('admin.gallery_images.drag_to_reorder') ?></small>
</div>

<div class="table-responsive">
<table class="data-table" id="imageTable">
    <thead>
        <tr>
            <th style="width:30px;" title="<?= e(__('admin.gallery_images.drag_to_reorder')) ?>">⠿</th>
            <th style="width:70px;"><?= __('admin.common.preview') ?></th>
            <th><?= __('admin.gallery_images.image_title') ?> / <?= __('admin.gallery_images.alt_text') ?></th>
            <th style="width:70px;"><?= __('admin.pages.order') ?></th>
            <th style="width:80px;"><?= __('admin.gallery.cover') ?></th>
            <th><?= __('admin.common.actions') ?></th>
        </tr>
    </thead>
    <tbody id="imageTableBody">
        <?php foreach ($images as $image): ?>
        <tr data-id="<?= (int) $image['id'] ?>" style="cursor:grab;">
            <td style="text-align:center;color:#aaa;">⠿</td>
            <td>
                <img src="<?= e(thumb_url(\App\Models\GalleryImage::effectiveFilePath($image))) ?>"
                     alt="<?= e($image['alt_text'] ?? $image['title'] ?? '') ?>"
                     style="width:60px;height:60px;object-fit:cover;border-radius:4px;display:block;">
            </td>
            <td>
                <!-- Inline edit form -->
                <div id="display-<?= (int) $image['id'] ?>">
                    <?php if (!empty($image['title'])): ?>
                    <strong><?= e($image['title']) ?></strong><br>
                    <?php endif; ?>
                    <?php if (!empty($image['alt_text'])): ?>
                    <span class="text-muted" style="font-size:0.85rem;"><?= e($image['alt_text']) ?></span>
                    <?php else: ?>
                    <span class="text-muted" style="font-size:0.85rem;font-style:italic;"><?= __('admin.gallery_images.no_alt_text') ?></span>
                    <?php endif; ?>
                    <br>
                    <button type="button" class="btn btn-sm btn-secondary" style="margin-top:0.3rem;"
                            onclick="toggleEdit(<?= (int) $image['id'] ?>)"><?= __('admin.gallery_images.edit_meta') ?></button>
                </div>
                <form id="edit-<?= (int) $image['id'] ?>"
                      method="POST"
                      action="/admin/gallery/images/update/<?= (int) $image['id'] ?>"
                      style="display:none;">
                    <?= $csrf->field() ?>
                    <div style="display:flex;flex-direction:column;gap:0.4rem;">
                        <input type="text" name="title" value="<?= e($image['title'] ?? '') ?>"
                               placeholder="Title" style="font-size:0.85rem;">
                        <input type="text" name="alt_text" value="<?= e($image['alt_text'] ?? '') ?>"
                               placeholder="Alt text" style="font-size:0.85rem;">
                        <input type="hidden" name="sort_order" value="<?= (int) $image['sort_order'] ?>">
                        <div style="display:flex;gap:0.4rem;">
                            <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.common.save') ?></button>
                            <button type="button" class="btn btn-sm btn-secondary"
                                    onclick="toggleEdit(<?= (int) $image['id'] ?>)"><?= __('admin.common.cancel') ?></button>
                        </div>
                    </div>
                </form>
            </td>
            <td style="text-align:center;"><?= (int) $image['sort_order'] ?></td>
            <td style="text-align:center;">
                <?php if ($album['cover_image'] === $image['file_path']): ?>
                <span class="badge badge-success" title="Current album cover"><?= __('admin.gallery.cover') ?></span>
                <?php else: ?>
                <form method="POST"
                      action="/admin/gallery/album/<?= (int) $album['id'] ?>/set-cover/<?= (int) $image['id'] ?>"
                      class="inline-form">
                    <?= $csrf->field() ?>
                    <button type="submit" class="btn btn-sm btn-secondary" title="Set as cover"><?= __('admin.gallery_images.set_cover') ?></button>
                </form>
                <?php endif; ?>
            </td>
            <td class="actions">
                <form method="POST"
                      action="/admin/gallery/images/delete/<?= (int) $image['id'] ?>"
                      class="inline-form"
                      onsubmit="return confirm('<?= e(__('admin.gallery_images.confirm_delete')) ?>')">
                    <?= $csrf->field() ?>
                    <button type="submit" class="btn btn-sm btn-danger"><?= __('admin.common.delete') ?></button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
</div>

<?php endif; ?>

<script>
// Toggle inline edit form
function toggleEdit(imageId) {
    var display = document.getElementById('display-' + imageId);
    var form    = document.getElementById('edit-' + imageId);
    var hidden  = display.style.display === 'none';
    display.style.display = hidden ? 'block' : 'none';
    form.style.display    = hidden ? 'none'  : 'block';
}

// Drag-and-drop reorder
(function () {
    var tbody = document.getElementById('imageTableBody');
    if (!tbody) return;

    var dragging = null;

    tbody.addEventListener('dragstart', function (e) {
        dragging = e.target.closest('tr');
        dragging.style.opacity = '0.5';
        e.dataTransfer.effectAllowed = 'move';
    });

    tbody.addEventListener('dragend', function () {
        if (dragging) {
            dragging.style.opacity = '';
            dragging = null;
        }
        saveOrder();
    });

    tbody.addEventListener('dragover', function (e) {
        e.preventDefault();
        var target = e.target.closest('tr');
        if (target && target !== dragging) {
            var rect = target.getBoundingClientRect();
            var next = (e.clientY - rect.top) > (rect.height / 2);
            tbody.insertBefore(dragging, next ? target.nextSibling : target);
        }
    });

    // Make rows draggable
    Array.from(tbody.querySelectorAll('tr')).forEach(function (row) {
        row.setAttribute('draggable', 'true');
    });

    function saveOrder() {
        var ids = Array.from(tbody.querySelectorAll('tr[data-id]')).map(function (row) {
            return parseInt(row.getAttribute('data-id'), 10);
        });

        // Collect CSRF token from the first form on the page
        var csrfInput = document.querySelector('input[name="_csrf_token"]');
        var csrfToken = csrfInput ? csrfInput.value : '';

        fetch('/admin/gallery/images/reorder', {
            method:  'POST',
            headers: { 'Content-Type': 'application/json' },
            body:    JSON.stringify({ ids: ids, _csrf_token: csrfToken })
        });
    }
})();
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
