<?php ob_start();
$isEdit = !empty($download);
$action = $isEdit
    ? '/admin/downloads/update/' . (int) $download['id']
    : '/admin/downloads/store';
?>
<link rel="stylesheet" href="/admin/assets/editor/jodit.min.css">

<div class="content-header">
    <h2><?= $isEdit ? __('admin.downloads.edit') : __('admin.downloads.create') ?></h2>
    <div style="display:flex;gap:0.5rem;align-items:center;">
        <?php if ($isEdit && ($download['status'] ?? '') === 'published' && !empty($download['slug'])): ?>
        <a href="/download/<?= e($download['slug']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.downloads.view_download') ?></a>
        <?php endif; ?>
        <a href="/admin/downloads" class="btn btn-secondary"><?= __('admin.downloads.back') ?></a>
    </div>
</div>

<form method="POST" action="<?= $action ?>" class="admin-form" id="downloadForm">
    <?= $csrf->field() ?>

    <!-- Hidden file fields (populated by AJAX upload) -->
    <input type="hidden" id="file_path" name="file_path" value="<?= e($download['file_path'] ?? '') ?>">
    <input type="hidden" id="file_name" name="file_name" value="<?= e($download['file_name'] ?? '') ?>">
    <input type="hidden" id="file_size" name="file_size" value="<?= (int) ($download['file_size'] ?? 0) ?: '' ?>">
    <input type="hidden" id="file_type" name="file_type" value="<?= e($download['file_type'] ?? '') ?>">

    <div class="form-grid">

        <!-- Main column -->
        <div class="form-main">

            <div class="form-group">
                <label for="title"><?= __('admin.downloads.download_title') ?> <span class="required">*</span></label>
                <input type="text" id="title" name="title"
                       value="<?= e($download['title'] ?? '') ?>"
                       required placeholder="<?= __('admin.downloads.download_title_placeholder') ?>">
            </div>

            <div class="form-group">
                <label for="slug"><?= __('admin.common.slug') ?></label>
                <div class="slug-preview-wrap">
                    <span class="slug-prefix"><?= __('admin.downloads.slug_prefix') ?></span>
                    <input type="text" id="slug" name="slug"
                           value="<?= e($download['slug'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.slug_placeholder') ?>">
                </div>
                <small class="form-hint"><?= __('admin.downloads.slug_help') ?></small>
            </div>

            <div class="form-group">
                <label for="excerpt"><?= __('admin.downloads.excerpt') ?></label>
                <textarea id="excerpt" name="excerpt" rows="3"
                          placeholder="<?= __('admin.downloads.excerpt_placeholder') ?>"><?= e($download['excerpt'] ?? '') ?></textarea>
            </div>

            <div class="form-group">
                <label for="content"><?= __('admin.downloads.content') ?></label>
                <textarea id="content" name="content" rows="14"
                          placeholder="<?= __('admin.downloads.content_placeholder') ?>"><?= e($download['content'] ?? '') ?></textarea>
                <div class="editor-footer-row">
                    <small class="form-hint editor-hint"><?= __('admin.downloads.content_help') ?></small>
                    <button type="button" class="btn btn-secondary btn-sm" id="dlContentPickerBtn" data-media-picker data-editor-target="content">📷 <?= __('admin.downloads.insert_image_title') ?></button>
                </div>
            </div>

            <!-- SEO -->
            <div class="form-card" style="margin-top:1.5rem;">
                <h4>SEO</h4>
                <div class="form-group">
                    <label for="seo_title"><?= __('admin.pages.seo_title') ?></label>
                    <input type="text" id="seo_title" name="seo_title"
                           value="<?= e($download['seo_title'] ?? '') ?>"
                           placeholder="<?= __('admin.pages.seo_title_default') ?>">
                </div>
                <div class="form-group">
                    <label for="seo_description"><?= __('admin.pages.seo_description') ?></label>
                    <textarea id="seo_description" name="seo_description" rows="2"
                              placeholder="<?= __('admin.pages.seo_description_default') ?>"><?= e($download['seo_description'] ?? '') ?></textarea>
                </div>
            </div>

        </div><!-- /form-main -->

        <!-- Sidebar -->
        <div class="form-sidebar">

            <!-- Publishing -->
            <div class="form-card">
                <h4><?= __('admin.events.publishing') ?></h4>

                <div class="form-group">
                    <label for="status"><?= __('admin.common.status') ?></label>
                    <select id="status" name="status">
                        <option value="draft"     <?= ($download['status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>><?= __('admin.common.draft') ?></option>
                        <option value="published" <?= ($download['status'] ?? '')      === 'published' ? 'selected' : '' ?>><?= __('admin.common.published') ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="sort_order"><?= __('admin.common.sort_order') ?></label>
                    <input type="number" id="sort_order" name="sort_order"
                           value="<?= (int) ($download['sort_order'] ?? 0) ?>"
                           min="0" style="width:80px;">
                    <small class="form-hint"><?= __('admin.downloads.sort_help') ?></small>
                </div>

                <button type="submit" class="btn btn-primary btn-full" style="margin-top:0.25rem;">
                    <?= $isEdit ? __('admin.downloads.update_download') : __('admin.downloads.create_download') ?>
                </button>
            </div>

            <!-- Details: Category + Version -->
            <div class="form-card">
                <h4><?= __('admin.downloads.details') ?></h4>
                <div class="form-group">
                    <label for="category_id"><?= __('admin.event_categories.title') ?></label>
                    <select id="category_id" name="category_id">
                        <option value=""><?= __('admin.downloads.no_category') ?></option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= (int) $cat['id'] ?>"
                                <?= (int) ($download['category_id'] ?? 0) === (int) $cat['id'] ? 'selected' : '' ?>>
                            <?= e($cat['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="form-hint">
                        <a href="/admin/downloads/categories" target="_blank"><?= __('admin.downloads.manage_categories') ?></a>
                    </small>
                </div>

                <div class="form-group">
                    <label for="version"><?= __('admin.downloads.version') ?></label>
                    <input type="text" id="version" name="version"
                           value="<?= e($download['version'] ?? '') ?>"
                           placeholder="<?= __('admin.downloads.version_placeholder') ?>"
                           style="max-width:180px;">
                    <small class="form-hint"><?= __('admin.downloads.version_hint') ?></small>
                </div>
            </div>

            <!-- Download File -->
            <div class="form-card">
                <h4><?= __('admin.downloads.download_file') ?></h4>

                <?php
                $hasFile      = !empty($download['file_path']);
                $fileExt      = $hasFile ? strtoupper(pathinfo($download['file_path'], PATHINFO_EXTENSION)) : '';
                $fileDisplay  = $hasFile && !empty($download['file_name']) ? $download['file_name'] : ($hasFile ? basename($download['file_path']) : '');
                $fileSizeHR   = '';
                if ($hasFile && !empty($download['file_size'])) {
                    $bytes = (int) $download['file_size'];
                    $fileSizeHR = $bytes >= 1048576
                        ? round($bytes / 1048576, 1) . ' MB'
                        : ($bytes >= 1024 ? round($bytes / 1024, 1) . ' KB' : $bytes . ' B');
                }
                ?>

                <!-- Current file info -->
                <div id="fileInfo" style="margin-bottom:0.75rem;<?= $hasFile ? '' : 'display:none;' ?>">
                    <div style="display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0.75rem;background:#f0f9ff;border:1px solid #bde0f9;border-radius:4px;">
                        <span style="font-weight:600;font-size:0.8rem;background:#1a6fa8;color:#fff;padding:0.1rem 0.4rem;border-radius:3px;"><?= e($fileExt) ?></span>
                        <span id="fileInfoName" style="font-size:0.875rem;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= e($fileDisplay) ?></span>
                        <?php if ($fileSizeHR !== ''): ?>
                        <span id="fileInfoSize" style="font-size:0.8rem;color:var(--gray-500);"><?= e($fileSizeHR) ?></span>
                        <?php else: ?>
                        <span id="fileInfoSize" style="font-size:0.8rem;color:var(--gray-500);"></span>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Upload row -->
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;align-items:center;margin-bottom:0.5rem;">
                    <input type="file" id="fileUploadInput"
                           style="display:none;"
                           accept=".pdf,.zip,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.odp,.txt,.csv,.json,.xml,.rar,.7z,.jpg,.jpeg,.png,.gif,.webp,.svg">
                    <button type="button" class="btn btn-secondary btn-sm" id="fileUploadBtn">
                        ⬆ <?= $hasFile ? __('admin.downloads.replace_file') : __('admin.downloads.upload_file') ?>
                    </button>
                    <?php if ($hasFile): ?>
                    <button type="button" class="btn btn-sm" id="fileRemoveBtn"
                            style="color:#c0392b;"><?= __('admin.common.remove') ?></button>
                    <?php else: ?>
                    <button type="button" class="btn btn-sm" id="fileRemoveBtn"
                            style="color:#c0392b;display:none;"><?= __('admin.common.remove') ?></button>
                    <?php endif; ?>
                </div>
                <input type="hidden" name="remove_file" id="removeFileInput" value="0">

                <span id="fileUploadFeedback"
                      style="font-size:0.8125rem;display:block;margin-top:0.25rem;"></span>

                <small class="form-hint" style="margin-top:0.5rem;display:block;">
                    <?= __('admin.downloads.file_hint') ?>
                </small>
            </div>

            <!-- Featured Image (via Media Manager or direct upload) -->
            <div class="form-card">
                <h4><?= __('admin.blog.featured_image') ?></h4>

                <!-- Hidden field holding the selected media ID -->
                <input type="hidden" id="media_id" name="media_id"
                       value="<?= (int) ($download['media_id'] ?? 0) ?: '' ?>">

                <!-- Preview of currently selected image -->
                <div id="dlImagePreview" style="margin-bottom:0.75rem;<?= empty($download['media_path']) ? 'display:none;' : '' ?>">
                    <?php if (!empty($download['media_path'])): ?>
                    <img id="dlImagePreviewImg"
                         src="<?= e(thumb_url($download['media_path'])) ?>"
                         alt="<?= e($download['media_alt'] ?? '') ?>"
                         style="max-width:100%;border-radius:4px;">
                    <?php else: ?>
                    <img id="dlImagePreviewImg" src="" alt="" style="max-width:100%;border-radius:4px;">
                    <?php endif; ?>
                </div>

                <!-- Library picker row -->
                <div style="display:flex;gap:0.5rem;flex-wrap:wrap;margin-bottom:0.6rem;">
                    <button type="button" class="btn btn-secondary btn-sm" id="dlPickerBtn">
                        📷 <?= empty($download['media_path']) ? __('admin.blog.select_from_library') : __('admin.blog.change_image') ?>
                    </button>
                    <button type="button" class="btn btn-sm" id="dlImageRemoveBtn"
                            style="color:#c0392b;<?= empty($download['media_path']) ? 'display:none;' : '' ?>">
                        <?= __('admin.common.remove') ?>
                    </button>
                </div>

                <!-- Direct upload row -->
                <div style="border-top:1px solid #e9ecef;padding-top:0.6rem;">
                    <small style="display:block;color:#888;margin-bottom:0.4rem;"><?= __('admin.downloads.upload_new') ?></small>
                    <input type="file" id="dlImageUploadInput"
                           accept="image/jpeg,image/png,image/gif,image/webp"
                           style="display:none;">
                    <button type="button" class="btn btn-secondary btn-sm" id="dlImageUploadBtn">
                        ⬆ <?= __('admin.downloads.upload_image') ?>
                    </button>
                    <span id="dlUploadFeedback"
                          style="font-size:0.8125rem;margin-left:0.5rem;vertical-align:middle;"></span>
                </div>

                <small class="form-hint" style="margin-top:0.5rem;display:block;">
                    <?= __('admin.downloads.upload_image_hint') ?>
                    <a href="/admin/media" target="_blank">Media Manager</a>.
                </small>
            </div>

        </div><!-- /form-sidebar -->

    </div><!-- /form-grid -->
</form>

<!-- ── Media Picker Modal (for content editor) ──────────────────────── -->
<div id="mediaPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.downloads.insert_image_title') ?>">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.downloads.insert_image_title') ?></h3>
            <button type="button" class="media-picker-close" id="mediaPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="mediaPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.pages.insert_image_help') ?> <a href="/admin/media" target="_blank">Media Manager</a>.</small>
        </div>
    </div>
</div>

<!-- ── Media Picker Modal (for featured image) ──────────────────────── -->
<div id="dlPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.downloads.select_image_title') ?>">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.downloads.select_image_title') ?></h3>
            <button type="button" class="media-picker-close" id="dlPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="dlPickerBody">
            <p class="text-muted" style="text-align:center; padding:2rem;"><?= __('admin.common.loading') ?></p>
        </div>
        <div class="media-picker-footer">
            <small class="form-hint"><?= __('admin.downloads.select_image_help') ?></small>
        </div>
    </div>
</div>

<script src="/admin/assets/editor/jodit.min.js"></script>
<script>
(function () {
    // ── Jodit WYSIWYG Editor ──────────────────────────────────────────────
    var contentTextarea = document.getElementById('content');
    var joditEditor     = null;
    if (contentTextarea && typeof Jodit !== 'undefined') {
        joditEditor = Jodit.make(contentTextarea, {
            height: 480,
            language: 'en',
            toolbarSticky: true,
            toolbarStickyOffset: 56,
            buttons: [
                'bold', 'italic', 'underline', 'strikethrough', 'eraser',
                '|',
                'paragraph', 'fontsize',
                '|',
                'ul', 'ol', 'indent', 'outdent',
                '|',
                'superscript', 'subscript',
                '|',
                'link', 'image',
                '|',
                'table', 'hr',
                '|',
                'align',
                '|',
                'undo', 'redo',
                '\n',
                'find',
                '|',
                'source',
            ],
            cleanHTML: {
                fillEmptyParagraph: false,
            },
            enter: 'P',
            defaultMode: Jodit.MODE_WYSIWYG,
        });
        // Attach editor instance so admin.js media-picker can insert images
        contentTextarea._joditEditor = joditEditor;
    }

    // ── Slug Auto-Generation ─────────────────────────────────────────────
    var titleInput = document.getElementById('title');
    var slugInput  = document.getElementById('slug');

    <?php if (!$isEdit): ?>
    if (titleInput && slugInput) {
        titleInput.addEventListener('input', function () {
            if (!slugInput._userEdited) {
                slugInput.value = slugifyTitle(this.value);
            }
        });
        slugInput.addEventListener('input', function () {
            this._userEdited = (this.value.trim() !== '');
        });
    }
    <?php endif; ?>

    function slugifyTitle(str) {
        var map = {
            'ä':'ae','ö':'oe','ü':'ue','Ä':'ae','Ö':'oe','Ü':'ue','ß':'ss',
            'à':'a','á':'a','â':'a','ã':'a','å':'a','æ':'ae',
            'ç':'c','è':'e','é':'e','ê':'e','ë':'e',
            'ì':'i','í':'i','î':'i','ï':'i',
            'ñ':'n','ò':'o','ó':'o','ô':'o','õ':'o','ø':'o',
            'ù':'u','ú':'u','û':'u','ý':'y','þ':'th','ÿ':'y'
        };
        return str
            .replace(/[äöüÄÖÜßàáâãåæçèéêëìíîïñòóôõøùúûýþÿ]/g, function (c) { return map[c] || c; })
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    // ── Download File Upload ─────────────────────────────────────────────
    var fileUploadBtn      = document.getElementById('fileUploadBtn');
    var fileUploadInput    = document.getElementById('fileUploadInput');
    var fileRemoveBtn      = document.getElementById('fileRemoveBtn');
    var removeFileInput    = document.getElementById('removeFileInput');
    var fileUploadFeedback = document.getElementById('fileUploadFeedback');
    var fileInfo           = document.getElementById('fileInfo');
    var fileInfoName       = document.getElementById('fileInfoName');
    var fileInfoSize       = document.getElementById('fileInfoSize');
    var filePathInput      = document.getElementById('file_path');
    var fileNameInput      = document.getElementById('file_name');
    var fileSizeInput      = document.getElementById('file_size');
    var fileTypeInput      = document.getElementById('file_type');

    function formatBytes(bytes) {
        bytes = parseInt(bytes) || 0;
        if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
        if (bytes >= 1024)    return (bytes / 1024).toFixed(1) + ' KB';
        return bytes + ' B';
    }

    if (fileUploadBtn && fileUploadInput) {
        fileUploadBtn.addEventListener('click', function () {
            fileUploadInput.click();
        });

        fileUploadInput.addEventListener('change', function () {
            var file = fileUploadInput.files[0];
            if (!file) return;

            var csrfInput = document.querySelector('#downloadForm input[name="_csrf_token"]');
            var csrfToken = csrfInput ? csrfInput.value : '';

            fileUploadFeedback.style.color = '#888';
            fileUploadFeedback.textContent = 'Uploading…';
            fileUploadBtn.disabled = true;

            var fd = new FormData();
            fd.append('download_file', file);
            fd.append('_csrf_token', csrfToken);

            fetch('/admin/downloads/upload-file', {
                method: 'POST',
                credentials: 'same-origin',
                body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                fileUploadBtn.disabled = false;
                fileUploadInput.value  = '';

                if (!data.ok) {
                    fileUploadFeedback.style.color = 'var(--admin-danger, #c0392b)';
                    fileUploadFeedback.textContent = data.error || 'Upload failed.';
                    return;
                }

                filePathInput.value = data.file_path;
                fileNameInput.value = data.file_name;
                fileSizeInput.value = data.file_size;
                fileTypeInput.value = data.file_type;
                removeFileInput.value = '0';

                if (fileInfoName) fileInfoName.textContent = data.file_name;
                if (fileInfoSize) fileInfoSize.textContent = formatBytes(data.file_size);
                if (fileInfo) fileInfo.style.display = '';
                if (fileRemoveBtn) fileRemoveBtn.style.display = '';
                fileUploadBtn.textContent = '⬆ Replace File';

                fileUploadFeedback.style.color = '#27ae60';
                fileUploadFeedback.textContent = '✓ Uploaded';
                setTimeout(function () { fileUploadFeedback.textContent = ''; }, 3000);
            })
            .catch(function () {
                fileUploadBtn.disabled = false;
                fileUploadInput.value  = '';
                fileUploadFeedback.style.color = 'var(--admin-danger, #c0392b)';
                fileUploadFeedback.textContent = 'Upload failed. Please try again.';
            });
        });
    }

    if (fileRemoveBtn) {
        fileRemoveBtn.addEventListener('click', function () {
            filePathInput.value = '';
            fileNameInput.value = '';
            fileSizeInput.value = '';
            fileTypeInput.value = '';
            removeFileInput.value = '1';
            if (fileInfo) fileInfo.style.display = 'none';
            fileRemoveBtn.style.display = 'none';
            fileUploadBtn.textContent = '⬆ Upload File';
            fileUploadFeedback.textContent = '';
        });
    }

    // ── Featured Image Picker ────────────────────────────────────────────
    var pickerBtn    = document.getElementById('dlPickerBtn');
    var imgRemoveBtn = document.getElementById('dlImageRemoveBtn');
    var overlay      = document.getElementById('dlPickerOverlay');
    var closeBtn     = document.getElementById('dlPickerClose');
    var mediaIdInput = document.getElementById('media_id');
    var previewBox   = document.getElementById('dlImagePreview');
    var previewImg   = document.getElementById('dlImagePreviewImg');
    var pickerBody   = document.getElementById('dlPickerBody');
    var pickerLoaded = false;

    function openPicker() {
        overlay.style.display = 'flex';
        if (!pickerLoaded) {
            renderPickerShell();
            loadPickerImages('', '');
            pickerLoaded = true;
        }
    }

    function closePicker() { overlay.style.display = 'none'; }

    if (pickerBtn)  pickerBtn.addEventListener('click', openPicker);
    if (closeBtn)   closeBtn.addEventListener('click', closePicker);
    if (overlay)    overlay.addEventListener('click', function (e) { if (e.target === overlay) closePicker(); });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && overlay && overlay.style.display !== 'none') closePicker();
    });

    if (imgRemoveBtn) {
        imgRemoveBtn.addEventListener('click', function () {
            mediaIdInput.value = '';
            previewBox.style.display = 'none';
            previewImg.src = '';
            imgRemoveBtn.style.display = 'none';
            pickerBtn.textContent = '📷 Select from Library';
        });
    }

    function renderPickerShell() {
        pickerBody.innerHTML =
            '<div class="media-picker-toolbar">' +
                '<input type="text" class="media-picker-search" id="dlPickerSearch" placeholder="Search images…" autocomplete="off">' +
                '<span class="media-picker-toolbar-label">Folder:</span>' +
                '<select class="media-picker-folder" id="dlPickerFolder">' +
                    '<option value="">All media</option>' +
                    '<option value="0">Unassigned</option>' +
                '</select>' +
            '</div>' +
            '<div class="media-picker-body" id="dlPickerGrid">' +
                '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">Loading…</p>' +
            '</div>';

        var searchInput  = pickerBody.querySelector('#dlPickerSearch');
        var folderSelect = pickerBody.querySelector('#dlPickerFolder');
        var searchTimer;

        searchInput.addEventListener('input', function () {
            clearTimeout(searchTimer);
            var q = searchInput.value, folder = folderSelect.value;
            searchTimer = setTimeout(function () { loadPickerImages(q, folder); }, 350);
        });
        folderSelect.addEventListener('change', function () {
            loadPickerImages(searchInput.value, folderSelect.value);
        });
    }

    function loadPickerImages(q, folder) {
        var grid = document.getElementById('dlPickerGrid');
        if (!grid) return;
        grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:2rem;">Loading…</p>';

        var url = '/admin/media/picker-images?q=' + encodeURIComponent(q) +
                  '&folder=' + encodeURIComponent(folder);

        fetch(url, { credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                var folderSelect = document.getElementById('dlPickerFolder');
                if (folderSelect && folderSelect.options.length <= 2 && data.folders && data.folders.length) {
                    data.folders.forEach(function (f) {
                        var opt = document.createElement('option');
                        opt.value = f.id; opt.textContent = f.name;
                        folderSelect.appendChild(opt);
                    });
                }

                if (!data.images || data.images.length === 0) {
                    grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">No images found.</p>';
                    return;
                }

                var html = '<div class="media-picker-grid">';
                data.images.forEach(function (img) {
                    html += '<div class="media-picker-item dl-picker-item"' +
                            ' data-id="' + escH(img.id)        + '"' +
                            ' data-url="' + escH(img.thumb_url || img.url) + '"' +
                            ' data-full="' + escH(img.url)     + '"' +
                            ' title="' + escH(img.name)        + '">' +
                            '<img src="' + escH(img.thumb_url || img.url) + '" alt="' + escH(img.name) + '" loading="lazy">' +
                            '<div class="media-picker-item-name">' + escH(img.name) + '</div>' +
                            '</div>';
                });
                html += '</div>';
                grid.innerHTML = html;

                grid.querySelectorAll('.dl-picker-item').forEach(function (item) {
                    item.addEventListener('click', function () {
                        var id    = item.dataset.id;
                        var thumb = item.dataset.url;
                        var full  = item.dataset.full;

                        mediaIdInput.value = id;
                        previewImg.src = thumb || full;
                        previewBox.style.display = 'block';
                        if (imgRemoveBtn) imgRemoveBtn.style.display = '';
                        pickerBtn.textContent = '📷 Change Image';
                        closePicker();
                    });
                });
            })
            .catch(function () {
                var g = document.getElementById('dlPickerGrid');
                if (g) g.innerHTML = '<p style="text-align:center;color:var(--admin-danger);padding-top:3rem;">Failed to load images.</p>';
            });
    }

    function escH(str) {
        return String(str)
            .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    // ── Media Picker for content editor ─────────────────────────────────
    // Wired up by admin.js via [data-media-picker] / [data-editor-target] on
    // #dlContentPickerBtn and the #mediaPickerOverlay modal above.

    // ── Direct image upload for featured image ───────────────────────────
    var imgUploadBtn      = document.getElementById('dlImageUploadBtn');
    var imgUploadInput    = document.getElementById('dlImageUploadInput');
    var imgUploadFeedback = document.getElementById('dlUploadFeedback');

    if (imgUploadBtn && imgUploadInput) {
        imgUploadBtn.addEventListener('click', function () {
            imgUploadInput.click();
        });

        imgUploadInput.addEventListener('change', function () {
            var file = imgUploadInput.files[0];
            if (!file) return;

            var csrfInput = document.querySelector('#downloadForm input[name="_csrf_token"]');
            var csrfToken = csrfInput ? csrfInput.value : '';

            imgUploadFeedback.style.color = '#888';
            imgUploadFeedback.textContent = 'Uploading…';
            imgUploadBtn.disabled = true;

            var fd = new FormData();
            fd.append('image_file', file);
            fd.append('_csrf_token', csrfToken);

            fetch('/admin/downloads/upload-image', {
                method: 'POST',
                credentials: 'same-origin',
                body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                imgUploadBtn.disabled = false;
                imgUploadInput.value  = '';

                if (!data.ok) {
                    imgUploadFeedback.style.color = 'var(--admin-danger, #c0392b)';
                    imgUploadFeedback.textContent = data.error || 'Upload failed.';
                    return;
                }

                mediaIdInput.value = data.media_id;
                previewImg.src     = data.thumb_url || data.url;
                previewBox.style.display = 'block';
                if (imgRemoveBtn) imgRemoveBtn.style.display = '';
                pickerBtn.textContent = '📷 Change Image';

                imgUploadFeedback.style.color = '#27ae60';
                imgUploadFeedback.textContent = '✓ Uploaded';
                setTimeout(function () { imgUploadFeedback.textContent = ''; }, 3000);
            })
            .catch(function () {
                imgUploadBtn.disabled = false;
                imgUploadInput.value  = '';
                imgUploadFeedback.style.color = 'var(--admin-danger, #c0392b)';
                imgUploadFeedback.textContent = 'Upload failed. Please try again.';
            });
        });
    }
})();
</script>

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