<?php ob_start(); ?>

<div class="content-header">
    <div class="content-header-left">
        <div class="content-header-icon"><?= icon('folder-open', 20) ?></div>
        <div class="content-header-title-group">
            <h2><?= __('admin.media.title') ?></h2>
        </div>
    </div>
    <div class="header-actions">
        <form method="POST" action="/admin/media/sync" style="display:inline">
            <?= $csrf->field() ?>
            <button type="submit" class="btn btn-secondary btn-sm"><?= icon('refresh-cw', 14) ?> <?= __('admin.media.sync_btn') ?></button>
        </form>
        <a href="/admin/media/optimize" class="btn btn-secondary btn-sm"><?= __('admin.media.optimize') ?></a>
        <button type="button" class="btn btn-primary btn-sm" id="uploadBtn"><?= __('admin.media.upload_btn') ?></button>
    </div>
</div>

<!-- ── Upload Modal ──────────────────────────────────────────────────────── -->
<div id="uploadOverlay" class="mm-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.media.upload_title') ?>">
    <div class="mm-modal mm-modal--sm">
        <div class="mm-modal-header">
            <h3><?= __('admin.media.upload_title') ?></h3>
            <button type="button" class="mm-close" id="uploadClose">&times;</button>
        </div>
        <div class="mm-modal-body">
            <form method="POST" action="/admin/media/upload" enctype="multipart/form-data" id="uploadForm" class="admin-form">
                <?= $csrf->field() ?>
                <div class="form-group">
                    <!-- Visually hidden native file input – stays in form, triggers on label click -->
                    <input type="file" id="media_file" name="media_file[]" accept="image/*,.svg,.ico,video/mp4,video/webm,video/ogg,video/quicktime,.mp4,.webm,.ogv,.mov" required multiple class="mm-file-input-hidden">
                    <!-- Visual upload zone: click → native dialog, drop → populate input via JS -->
                    <label for="media_file" class="mm-upload-zone" id="uploadDropZone">
                        <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">Klicken, um Dateien zu wählen</span>
                        <span class="mm-upload-secondary">oder per Drag &amp; Drop hier ablegen</span>
                        <span class="mm-upload-hint">Bilder: JPG, PNG, GIF, WEBP, SVG, ICO &middot; max. 5 MB &nbsp;|&nbsp; Videos: MP4, WEBM, OGV, MOV &middot; max. 200 MB &middot; bis zu 10 Dateien</span>
                    </label>
                    <!-- Selection feedback: updated by JS on change / drop -->
                    <div class="mm-upload-feedback" id="uploadFeedback" aria-live="polite"></div>
                </div>
                <div class="form-group">
                    <label for="upload_folder"><?= __('admin.media.upload_folder') ?></label>
                    <select id="upload_folder" name="folder_id">
                        <option value=""><?= __('admin.media.unassigned') ?></option>
                        <?php foreach ($folders as $f): ?>
                        <option value="<?= (int)$f['id'] ?>" <?= ($folderId !== '' && (int)$folderId === (int)$f['id']) ? 'selected' : '' ?>><?= e($f['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="actions" style="justify-content:flex-end;margin-top:1.25rem;">
                    <button type="button" class="btn btn-secondary" id="uploadCancelBtn"><?= __('admin.common.cancel') ?></button>
                    <button type="submit" class="btn btn-primary" id="uploadSubmitBtn"><?= __('admin.common.upload') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── New Folder Modal ──────────────────────────────────────────────────── -->
<div id="newFolderOverlay" class="mm-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.media.new_folder') ?>">
    <div class="mm-modal mm-modal--sm">
        <div class="mm-modal-header">
            <h3><?= __('admin.media.new_folder') ?></h3>
            <button type="button" class="mm-close" id="newFolderClose">&times;</button>
        </div>
        <div class="mm-modal-body">
            <form method="POST" action="/admin/media/folders/create" id="newFolderForm" class="admin-form">
                <?= $csrf->field() ?>
                <div class="form-group">
                    <label for="folder_name"><?= __('admin.media.folder_name') ?> <span class="required">*</span></label>
                    <input type="text" id="folder_name" name="name" required placeholder="<?= __('admin.media.folder_name_placeholder') ?>" autofocus>
                </div>
                <div class="actions" style="justify-content:flex-end;margin-top:1.25rem;">
                    <button type="button" class="btn btn-secondary" id="newFolderCancelBtn"><?= __('admin.common.cancel') ?></button>
                    <button type="submit" class="btn btn-primary"><?= __('admin.media.create_folder') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Rename Folder Modal ───────────────────────────────────────────────── -->
<div id="renameFolderOverlay" class="mm-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.media.rename_folder') ?>">
    <div class="mm-modal mm-modal--sm">
        <div class="mm-modal-header">
            <h3><?= __('admin.media.rename_folder') ?></h3>
            <button type="button" class="mm-close" id="renameFolderClose">&times;</button>
        </div>
        <div class="mm-modal-body">
            <form method="POST" action="" id="renameFolderForm" class="admin-form">
                <?= $csrf->field() ?>
                <div class="form-group">
                    <label for="rename_folder_name"><?= __('admin.media.new_name') ?> <span class="required">*</span></label>
                    <input type="text" id="rename_folder_name" name="name" required placeholder="<?= __('admin.media.folder_name') ?>">
                </div>
                <div class="actions" style="justify-content:flex-end;margin-top:1.25rem;">
                    <button type="button" class="btn btn-secondary" id="renameFolderCancelBtn"><?= __('admin.common.cancel') ?></button>
                    <button type="submit" class="btn btn-primary"><?= __('admin.media.rename') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ── Layout ────────────────────────────────────────────────────────────── -->
<div class="mm-layout">

    <!-- Sidebar: Folders -->
    <aside class="mm-sidebar">
        <div class="mm-sidebar-header">
            <span><?= __('admin.media.folders') ?></span>
            <button type="button" class="mm-new-folder-btn" id="newFolderBtn" title="<?= __('admin.media.new_folder') ?>">+</button>
        </div>
        <nav class="mm-folder-list">
            <a href="/admin/media" class="mm-folder-item <?= $folderId === '' ? 'active' : '' ?>">
                <span class="mm-folder-icon">☰</span>
                <span class="mm-folder-name"><?= __('admin.media.all_media') ?></span>
                <span class="mm-folder-count"><?= $total ?></span>
            </a>
            <a href="/admin/media?folder=0" class="mm-folder-item <?= $folderId === '0' ? 'active' : '' ?>">
                <span class="mm-folder-icon">◫</span>
                <span class="mm-folder-name"><?= __('admin.media.unassigned') ?></span>
                <span class="mm-folder-count"><?= $unassignedCount ?></span>
            </a>
            <?php foreach ($folders as $folder): ?>
            <div class="mm-folder-row">
                <a href="/admin/media?folder=<?= (int)$folder['id'] ?>" class="mm-folder-item <?= (string)$folderId === (string)$folder['id'] ? 'active' : '' ?>">
                    <span class="mm-folder-icon">▣</span>
                    <span class="mm-folder-name"><?= e($folder['name']) ?></span>
                    <span class="mm-folder-count"><?= (int)($folder['media_count'] ?? 0) ?></span>
                </a>
                <button type="button" class="mm-folder-rename" title="Rename folder"
                        data-folder-id="<?= (int)$folder['id'] ?>"
                        data-folder-name="<?= e($folder['name']) ?>">✎</button>
                <form method="POST" action="/admin/media/folders/delete/<?= (int)$folder['id'] ?>" class="inline-form" onsubmit="return confirm('Delete folder &quot;<?= e(addslashes($folder['name'])) ?>&quot;? Media items will become unassigned.')">
                    <?= $csrf->field() ?>
                    <button type="submit" class="mm-folder-delete" title="Delete folder">&times;</button>
                </form>
            </div>
            <?php endforeach; ?>
        </nav>
    </aside>

    <!-- Main area (also serves as drag-and-drop target) -->
    <div class="mm-main" id="mmDropZone">

        <!-- Drag & Drop hint overlay (shown while dragging files over the zone) -->
        <div class="mm-drop-hint" id="mmDropHint" aria-hidden="true">
            <span class="mm-drop-icon">↓</span>
            <span>Drop files here to upload</span>
        </div>

        <!-- Filter bar -->
        <form method="GET" action="/admin/media" class="mm-filterbar" id="filterForm">
            <?php if ($folderId !== ''): ?>
            <input type="hidden" name="folder" value="<?= e($folderId) ?>">
            <?php endif; ?>
            <input type="text" name="q" value="<?= e($q) ?>" placeholder="<?= __('admin.media.search_placeholder') ?>" class="mm-search" id="mmSearch">
            <select name="type" class="mm-type-select" onchange="this.form.submit()">
                <option value="" <?= $type === '' ? 'selected' : '' ?>><?= __('admin.media.all_types') ?></option>
                <option value="image" <?= $type === 'image' ? 'selected' : '' ?>><?= __('admin.media.images_only') ?></option>
                <option value="video" <?= $type === 'video' ? 'selected' : '' ?>>Videos</option>
            </select>
            <button type="submit" class="btn btn-secondary btn-sm"><?= __('admin.common.search') ?></button>
            <?php if ($q !== '' || $type !== ''): ?>
            <a href="/admin/media<?= $folderId !== '' ? '?folder=' . e($folderId) : '' ?>" class="btn btn-secondary btn-sm"><?= __('admin.common.clear') ?></a>
            <?php endif; ?>
            <span class="mm-total"><?= __('admin.media.file_count', ['count' => $total]) ?></span>
        </form>

        <!-- Media Grid -->
        <?php if (empty($items)): ?>
        <div class="mm-empty">
            <div class="mm-empty-icon">◫</div>
            <p><?= ($q !== '' || $type !== '') ? __('admin.media.no_search_results') : __('admin.media.no_files') ?></p>
            <?php if ($q === '' && $type === ''): ?>
            <button type="button" class="btn btn-primary" id="uploadBtnEmpty"><?= __('admin.media.upload_a_file') ?></button>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="mm-grid" id="mmGrid">
            <?php foreach ($items as $item): ?>
            <?php
                $fileMime    = $item['file_type'] ?? '';
                $fileExtI    = strtolower(pathinfo($item['file_path'] ?? '', PATHINFO_EXTENSION));
                $isVideo     = str_starts_with($fileMime, 'video/') || in_array($fileExtI, ['mp4', 'webm', 'ogv', 'mov'], true);
                $isImage     = !$isVideo && (str_starts_with($fileMime, 'image/') || in_array($fileExtI, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'avif'], true));
                $thumbUrl    = $isImage ? thumb_url($item['file_path']) : null;
                $posterUrl   = ($isVideo && !empty($item['video_poster'])) ? '/uploads/' . ltrim($item['video_poster'], '/') : null;
                $fileUrl     = '/uploads/' . ltrim($item['file_path'], '/');
                $displayName = $item['title'] ?: pathinfo($item['original_name'], PATHINFO_FILENAME);
                $sizeBytes   = (int) $item['file_size'];
                $size        = $sizeBytes > 0 ? ($sizeBytes >= 1048576 ? round($sizeBytes / 1048576, 1) . ' MB' : round($sizeBytes / 1024, 1) . ' KB') : '–';
                // Check for companion formats
                $hasWebp     = $isImage && webp_url($item['file_path']) !== null;
                $hasAvif     = $isImage && function_exists('avif_url') && avif_url($item['file_path']) !== null;
                // Best URL for copy: prefer AVIF > WebP > original
                $bestUrl     = $fileUrl;
                if ($hasAvif) { $bestUrl = avif_url($item['file_path']); }
                elseif ($hasWebp) { $bestUrl = webp_url($item['file_path']); }
            ?>
            <div class="mm-card<?= $isVideo ? ' mm-card--video' : '' ?>" data-id="<?= (int)$item['id'] ?>" data-url="<?= e($fileUrl) ?>">
                <a href="/admin/media/edit/<?= (int)$item['id'] ?>" class="mm-card-preview">
                    <?php if ($isVideo): ?>
                    <?php if ($posterUrl): ?>
                    <img src="<?= e($posterUrl) ?>" alt="<?= e($displayName) ?>" loading="lazy" class="mm-video-poster">
                    <?php else: ?>
                    <div class="mm-card-icon mm-card-icon--video">
                        <svg width="40" height="40" viewBox="0 0 40 40" fill="none"><rect width="40" height="40" rx="10" fill="#e0f2fe"/><path d="M15 13l16 7-16 7V13z" fill="#0284c7"/></svg>
                    </div>
                    <?php endif; ?>
                    <span class="mm-video-badge" aria-label="Video">▶</span>
                    <?php elseif ($isImage && $thumbUrl): ?>
                    <img src="<?= e($thumbUrl) ?>" alt="<?= e($item['alt_text'] ?? '') ?>" loading="lazy">
                    <?php elseif ($isImage): ?>
                    <img src="<?= e($fileUrl) ?>" alt="<?= e($item['alt_text'] ?? '') ?>" loading="lazy">
                    <?php else: ?>
                    <div class="mm-card-icon"><svg width="40" height="40" viewBox="0 0 40 40" fill="none"><rect width="40" height="40" rx="10" fill="#f1f5f9"/><path d="M14 10h8l6 6v14a2 2 0 01-2 2H14a2 2 0 01-2-2V12a2 2 0 012-2z" stroke="#94a3b8" stroke-width="1.5" fill="none"/><path d="M22 10v6h6" stroke="#94a3b8" stroke-width="1.5" fill="none"/></svg></div>
                    <?php endif; ?>
                </a>
                <div class="mm-card-info">
                    <a href="/admin/media/edit/<?= (int)$item['id'] ?>" class="mm-card-name" title="<?= e($item['original_name']) ?>"><?= e($displayName) ?></a>
                    <div class="mm-card-meta">
                        <span class="badge badge-draft"><?= e(strtoupper(pathinfo($item['filename'], PATHINFO_EXTENSION))) ?></span>
                        <span><?= e($size) ?></span>
                        <?php if ($hasWebp): ?><span class="badge badge-format" title="WebP-Companion vorhanden">WebP</span><?php endif; ?>
                        <?php if ($hasAvif): ?><span class="badge badge-format" title="AVIF-Companion vorhanden">AVIF</span><?php endif; ?>
                    </div>
                    <?php if ($item['folder_name']): ?>
                    <div class="mm-card-folder">▣ <?= e($item['folder_name']) ?></div>
                    <?php endif; ?>
                </div>
                <div class="mm-card-actions">
                    <a href="<?= e($fileUrl) ?>" target="_blank" class="mm-action-btn" title="<?= __('admin.media.open_original') ?>">↗</a>
                    <button type="button" class="mm-action-btn mm-copy-url-btn" title="<?= __('admin.media.copy_url') ?><?= $bestUrl !== $fileUrl ? ' (' . strtoupper(pathinfo($bestUrl, PATHINFO_EXTENSION)) . ')' : '' ?>" data-url="<?= e($bestUrl) ?>" data-url-original="<?= e($fileUrl) ?>">⎘</button>
                    <a href="/admin/media/edit/<?= (int)$item['id'] ?>" class="mm-action-btn" title="<?= __('admin.common.edit') ?>">✎</a>
                    <form method="POST" action="/admin/media/delete/<?= (int)$item['id'] ?>" class="inline-form" onsubmit="return confirm('<?= __('admin.media.confirm_delete') ?>')">
                        <?= $csrf->field() ?>
                        <input type="hidden" name="ref" value="/admin/media<?= $folderId !== '' ? '?folder=' . e($folderId) : '' ?>">
                        <button type="submit" class="mm-action-btn mm-action-btn--danger" title="<?= __('admin.common.delete') ?>">✕</button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <?php if ($pages > 1): ?>
        <div class="mm-pagination">
            <?php for ($p = 1; $p <= $pages; $p++): ?>
            <?php
                $pUrl = '/admin/media?' . http_build_query(array_filter([
                    'folder' => $folderId !== '' ? $folderId : null,
                    'q'      => $q ?: null,
                    'type'   => $type ?: null,
                    'page'   => $p > 1 ? $p : null,
                ]));
            ?>
            <a href="<?= e($pUrl) ?>" class="mm-page-btn <?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div><!-- /mm-main -->
</div><!-- /mm-layout -->

<script>
(function () {

    // ── Focus trap helper ─────────────────────────────────────────────────
    // Keeps keyboard focus inside a modal dialog when Tab is pressed.
    function getFocusable(el) {
        return Array.prototype.slice.call(
            el.querySelectorAll('button,input,select,textarea,a[href],[tabindex]:not([tabindex="-1"])')
        ).filter(function (n) { return !n.disabled && n.offsetParent !== null; });
    }
    function makeTrapHandler(modal) {
        return function (e) {
            if (e.key !== 'Tab') return;
            var focusable = getFocusable(modal);
            if (!focusable.length) return;
            var first = focusable[0], last = focusable[focusable.length - 1];
            if (e.shiftKey) {
                if (document.activeElement === first) { e.preventDefault(); last.focus(); }
            } else {
                if (document.activeElement === last)  { e.preventDefault(); first.focus(); }
            }
        };
    }

    // ── Shared: file input + helpers ──────────────────────────────────────
    var fileInput = document.getElementById('media_file');

    // Check whether a drag event carries actual files (not links / text)
    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;
    }

    // Update the selection-feedback line below the upload zone
    function updateFeedback() {
        var feedback = document.getElementById('uploadFeedback');
        if (!feedback || !fileInput) return;
        var count = fileInput.files ? fileInput.files.length : 0;
        feedback.textContent = count === 0 ? '' :
            count === 1 ? '1 Datei ausgewählt' : count + ' Dateien ausgewählt';
    }

    // ── Upload modal ──────────────────────────────────────────────────────
    var uploadOverlay  = document.getElementById('uploadOverlay');
    var uploadBtn      = document.getElementById('uploadBtn');
    var uploadBtnEmpty = document.getElementById('uploadBtnEmpty');
    var uploadClose    = document.getElementById('uploadClose');
    var uploadCancel   = document.getElementById('uploadCancelBtn');
    var uploadSubmit   = document.getElementById('uploadSubmitBtn');
    var uploadForm     = document.getElementById('uploadForm');

    var uploadTrap = uploadOverlay ? makeTrapHandler(uploadOverlay) : null;

    function openUpload() {
        if (!uploadOverlay) return;
        uploadOverlay.style.display = 'flex';
        if (uploadTrap) uploadOverlay.addEventListener('keydown', uploadTrap);
        var first = getFocusable(uploadOverlay)[0];
        if (first) setTimeout(function () { first.focus(); }, 30);
    }
    function closeUpload() {
        if (!uploadOverlay) return;
        uploadOverlay.style.display = 'none';
        if (uploadTrap) uploadOverlay.removeEventListener('keydown', uploadTrap);
        // Reset file input and feedback when the modal is dismissed
        if (fileInput) { try { fileInput.value = ''; } catch (e) {} }
        updateFeedback();
    }

    if (uploadBtn)      uploadBtn.addEventListener('click', openUpload);
    if (uploadBtnEmpty) uploadBtnEmpty.addEventListener('click', openUpload);
    if (uploadClose)    uploadClose.addEventListener('click', closeUpload);
    if (uploadCancel)   uploadCancel.addEventListener('click', closeUpload);

    if (uploadOverlay) uploadOverlay.addEventListener('click', function (e) {
        if (e.target === uploadOverlay) closeUpload();
    });

    // Update feedback text whenever the native file dialog confirms a selection
    if (fileInput) {
        fileInput.addEventListener('change', updateFeedback);
    }

    // Disable the submit button while uploading to prevent double-submit
    // LRA: Spinner + i18n-Text statt hartkodiertem String
    if (uploadForm && uploadSubmit) {
        uploadForm.addEventListener('submit', function () {
            uploadSubmit.disabled = true;
            uploadSubmit.innerHTML = '<span class="lra-btn-spinner" aria-hidden="true"></span><?= __('admin.common.uploading') ?>';
        });
    }

    // ── Upload zone: D&D inside the modal ─────────────────────────────────
    // Files dropped here populate the file input and show a count;
    // the user then confirms by clicking "Upload" (no auto-submit here).
    var uploadDropZone = document.getElementById('uploadDropZone');
    if (uploadDropZone && fileInput) {
        var zoneDragDepth = 0;

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

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

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

        uploadDropZone.addEventListener('drop', function (e) {
            e.preventDefault(); e.stopPropagation();
            zoneDragDepth = 0;
            uploadDropZone.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();
                    var limit = Math.min(files.length, 10);
                    for (var i = 0; i < limit; i++) { dt.items.add(files[i]); }
                    fileInput.files = dt.files;
                    updateFeedback();
                    return;
                } catch (err) {
                    // DataTransfer.items not supported – fall through (user still sees the modal)
                }
            }
        });
    }

    // ── New folder modal ──────────────────────────────────────────────────
    var folderOverlay = document.getElementById('newFolderOverlay');
    var newFolderBtn  = document.getElementById('newFolderBtn');
    var folderClose   = document.getElementById('newFolderClose');
    var folderCancel  = document.getElementById('newFolderCancelBtn');
    var folderTrap    = folderOverlay ? makeTrapHandler(folderOverlay) : null;

    function openFolder() {
        if (!folderOverlay) return;
        folderOverlay.style.display = 'flex';
        if (folderTrap) folderOverlay.addEventListener('keydown', folderTrap);
        var n = document.getElementById('folder_name');
        if (n) { n.value = ''; setTimeout(function(){ n.focus(); }, 50); }
    }
    function closeFolder() {
        if (!folderOverlay) return;
        folderOverlay.style.display = 'none';
        if (folderTrap) folderOverlay.removeEventListener('keydown', folderTrap);
    }

    if (newFolderBtn) newFolderBtn.addEventListener('click', openFolder);
    if (folderClose)  folderClose.addEventListener('click', closeFolder);
    if (folderCancel) folderCancel.addEventListener('click', closeFolder);

    if (folderOverlay) folderOverlay.addEventListener('click', function (e) {
        if (e.target === folderOverlay) closeFolder();
    });

    // ── Rename Folder modal ────────────────────────────────────────────────
    var renameOverlay  = document.getElementById('renameFolderOverlay');
    var renameForm     = document.getElementById('renameFolderForm');
    var renameInput    = document.getElementById('rename_folder_name');
    var renameClose    = document.getElementById('renameFolderClose');
    var renameCancel   = document.getElementById('renameFolderCancelBtn');
    var renameTrap     = renameOverlay ? makeTrapHandler(renameOverlay) : null;

    function openRename(folderId, folderName) {
        if (!renameOverlay || !renameForm || !renameInput) return;
        renameForm.action = '/admin/media/folders/rename/' + folderId;
        renameInput.value = folderName;
        renameOverlay.style.display = 'flex';
        if (renameTrap) renameOverlay.addEventListener('keydown', renameTrap);
        setTimeout(function () { renameInput.focus(); renameInput.select(); }, 30);
    }
    function closeRename() {
        if (!renameOverlay) return;
        renameOverlay.style.display = 'none';
        if (renameTrap) renameOverlay.removeEventListener('keydown', renameTrap);
    }

    if (renameClose)  renameClose.addEventListener('click', closeRename);
    if (renameCancel) renameCancel.addEventListener('click', closeRename);
    if (renameOverlay) renameOverlay.addEventListener('click', function (e) {
        if (e.target === renameOverlay) closeRename();
    });

    // Wire up rename buttons in sidebar
    document.querySelectorAll('.mm-folder-rename').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openRename(this.dataset.folderId, this.dataset.folderName);
        });
    });

    // ── Search on Enter ───────────────────────────────────────────────────
    var searchInput = document.getElementById('mmSearch');
    if (searchInput) {
        searchInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') { e.preventDefault(); document.getElementById('filterForm').submit(); }
        });
    }

    // ── Escape closes any open modal ──────────────────────────────────────
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') { closeUpload(); closeFolder(); closeRename(); }
    });

    // ── Copy URL buttons in grid ───────────────────────────────────────────
    document.querySelectorAll('.mm-copy-url-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var url = this.dataset.url;
            var self = this;
            function onCopied() {
                self.classList.add('mm-copied');
                var prev = self.title;
                self.title = 'Copied!';
                setTimeout(function () {
                    self.classList.remove('mm-copied');
                    self.title = prev;
                }, 1500);
            }
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(url).then(onCopied);
            } else {
                var ta = document.createElement('textarea');
                ta.value = url;
                ta.style.cssText = 'position:fixed;opacity:0;';
                document.body.appendChild(ta);
                ta.select();
                try { document.execCommand('copy'); onCopied(); } catch (_) {}
                document.body.removeChild(ta);
            }
        });
    });

    // ── Main area Drag & Drop ─────────────────────────────────────────────
    // Files dragged onto the main media area populate the file input and
    // submit the upload form automatically (no extra endpoint needed).
    // Uses the existing CSRF token and the active folder selection from the form.
    var dropZone = document.getElementById('mmDropZone');

    if (dropZone && fileInput && uploadForm) {
        var dragDepth = 0;

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

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

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

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

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

            if (typeof DataTransfer !== 'undefined' && DataTransfer.prototype.hasOwnProperty !== undefined) {
                try {
                    var dt    = new DataTransfer();
                    var limit = Math.min(files.length, 10);
                    for (var i = 0; i < limit; i++) {
                        dt.items.add(files[i]);
                    }
                    fileInput.files = dt.files;
                    if (uploadSubmit) {
                        uploadSubmit.disabled    = true;
                        uploadSubmit.textContent = 'Uploading…';
                    }
                    uploadForm.submit();
                    return;
                } catch (err) {
                    // DataTransfer.items not supported – fall through
                }
            }

            // Fallback: open the upload modal so the user can pick files manually
            openUpload();
        });
    }

})();
</script>

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