<?php ob_start();
$isEdit  = !empty($event);
$action  = $isEdit
    ? admin_url('events/update/' . (int) $event['id'])
    : admin_url('events/store');
?>

<div class="content-header">
    <div class="content-header-left">
        <div class="content-header-icon"><?= icon('calendar', 20) ?></div>
        <h2><?= $isEdit ? __('admin.events.edit') : __('admin.events.create') ?></h2>
    </div>
    <div class="header-actions">
        <?php if ($isEdit && ($event['publish_status'] ?? '') === 'published' && !empty($event['slug'])): ?>
        <a href="/events/<?= e($event['slug']) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.events.view_event') ?></a>
        <?php endif; ?>
        <a href="<?= admin_url('events') ?>" class="btn btn-secondary"><?= __('admin.events.back') ?></a>
    </div>
</div>

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

    <div class="form-grid">

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

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

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

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

            <div class="form-group">
                <label for="content"><?= __('admin.events.content') ?></label>
                <textarea id="content" name="content" rows="14"
                          placeholder="<?= __('admin.events.content_placeholder') ?>"><?= e($event['content'] ?? '') ?></textarea>
            </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="publish_status"><?= __('admin.events.publish_status') ?></label>
                    <select id="publish_status" name="publish_status">
                        <option value="draft"     <?= ($event['publish_status'] ?? 'draft') === 'draft'     ? 'selected' : '' ?>><?= __('admin.common.draft') ?></option>
                        <option value="published" <?= ($event['publish_status'] ?? '')      === 'published' ? 'selected' : '' ?>><?= __('admin.common.published') ?></option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="event_status"><?= __('admin.events.event_status') ?></label>
                    <select id="event_status" name="event_status">
                        <option value="scheduled"  <?= ($event['event_status'] ?? 'scheduled') === 'scheduled'  ? 'selected' : '' ?>><?= __('admin.events.scheduled') ?></option>
                        <option value="postponed"  <?= ($event['event_status'] ?? '')           === 'postponed'  ? 'selected' : '' ?>><?= __('admin.events.postponed') ?></option>
                        <option value="cancelled"  <?= ($event['event_status'] ?? '')           === 'cancelled'  ? 'selected' : '' ?>><?= __('admin.events.cancelled') ?></option>
                    </select>
                    <small class="form-hint"><?= __('admin.events.postponed_hint') ?></small>
                </div>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="is_featured" value="1"
                               <?= !empty($event['is_featured']) ? 'checked' : '' ?>>
                        <?= __('admin.events.featured') ?>
                    </label>
                    <small class="form-hint"><?= __('admin.events.featured_hint') ?></small>
                </div>

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

            <!-- Date & Time -->
            <div class="form-card">
                <h4><?= __('admin.events.date_time') ?></h4>

                <div class="form-group">
                    <label for="start_date"><?= __('admin.events.start_date') ?> <span class="required">*</span></label>
                    <input type="date" id="start_date" name="start_date"
                           value="<?= e($event['start_date'] ?? '') ?>" required>
                </div>

                <div class="form-group">
                    <label for="start_time"><?= __('admin.events.start_time') ?></label>
                    <input type="time" id="start_time" name="start_time"
                           value="<?= e(!empty($event['start_time']) ? substr($event['start_time'], 0, 5) : '') ?>">
                </div>

                <div class="form-group">
                    <label for="end_date"><?= __('admin.events.end_date') ?></label>
                    <input type="date" id="end_date" name="end_date"
                           value="<?= e($event['end_date'] ?? '') ?>">
                    <small class="form-hint"><?= __('admin.events.end_date_hint') ?></small>
                </div>

                <div class="form-group">
                    <label for="end_time"><?= __('admin.events.end_time') ?></label>
                    <input type="time" id="end_time" name="end_time"
                           value="<?= e(!empty($event['end_time']) ? substr($event['end_time'], 0, 5) : '') ?>">
                </div>
            </div>

            <!-- Location & Category -->
            <div class="form-card">
                <h4><?= __('admin.events.location_category') ?></h4>

                <div class="form-group">
                    <label for="location"><?= __('admin.events.location') ?></label>
                    <input type="text" id="location" name="location"
                           value="<?= e($event['location'] ?? '') ?>"
                           placeholder="<?= __('admin.events.location_placeholder') ?>">
                </div>

                <div class="form-group">
                    <label for="category_id"><?= __('admin.event_categories.title') ?></label>
                    <select id="category_id" name="category_id">
                        <option value=""><?= __('admin.events.no_category') ?></option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= (int) $cat['id'] ?>"
                                <?= (int) ($event['category_id'] ?? 0) === (int) $cat['id'] ? 'selected' : '' ?>>
                            <?= e($cat['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="form-hint">
                        <a href="<?= admin_url('events/categories') ?>" target="_blank"><?= __('admin.events.manage_categories') ?></a>
                    </small>
                </div>
            </div>

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

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

                <!-- Preview of currently selected / uploaded image -->
                <div id="eventImagePreview" style="margin-bottom:0.75rem;<?= empty($event['media_path']) ? 'display:none;' : '' ?>">
                    <?php if (!empty($event['media_path'])): ?>
                    <img id="eventImagePreviewImg"
                         src="<?= e(thumb_url($event['media_path'])) ?>"
                         alt="<?= e($event['media_alt'] ?? '') ?>"
                         style="max-width:100%;border-radius:4px;">
                    <?php else: ?>
                    <img id="eventImagePreviewImg" 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="eventPickerBtn">
                        📷 <?= empty($event['media_path']) ? __('admin.events.select_image_title') : __('admin.events.change_image') ?>
                    </button>
                    <button type="button" class="btn btn-sm" id="eventImageRemoveBtn"
                            style="color:#c0392b;<?= empty($event['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.events.upload_new') ?></small>
                    <input type="file" id="eventImageUploadInput"
                           accept="image/jpeg,image/png,image/gif,image/webp"
                           style="display:none;">
                    <button type="button" class="btn btn-secondary btn-sm" id="eventImageUploadBtn">
                        ⬆ <?= __('admin.events.upload_image') ?>
                    </button>
                    <span id="eventUploadFeedback"
                          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.events.upload_hint') ?>
                    <a href="<?= admin_url('media') ?>" target="_blank">Media Manager</a>.
                </small>
            </div>

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

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

<!-- ── Event Media Picker Modal ───────────────────────────────────────── -->
<div id="eventPickerOverlay" class="media-picker-overlay" style="display:none;" role="dialog" aria-modal="true" aria-label="<?= __('admin.events.select_image_title') ?>">
    <div class="media-picker-modal">
        <div class="media-picker-header">
            <h3><?= __('admin.events.select_image_title') ?></h3>
            <button type="button" class="media-picker-close" id="eventPickerClose" aria-label="Close">&times;</button>
        </div>
        <div id="eventPickerBody">
            <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.events.select_image_help') ?></small>
        </div>
    </div>
</div>

<script>
(function () {
    // ── 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, '');
    }

    // ── Event Image Picker ────────────────────────────────────────────────
    var pickerBtn     = document.getElementById('eventPickerBtn');
    var removeBtn     = document.getElementById('eventImageRemoveBtn');
    var overlay       = document.getElementById('eventPickerOverlay');
    var closeBtn      = document.getElementById('eventPickerClose');
    var mediaIdInput  = document.getElementById('media_id');
    var previewBox    = document.getElementById('eventImagePreview');
    var previewImg    = document.getElementById('eventImagePreviewImg');
    var pickerBody    = document.getElementById('eventPickerBody');
    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();
    });

    // Remove image
    if (removeBtn) {
        removeBtn.addEventListener('click', function () {
            mediaIdInput.value = '';
            previewBox.style.display = 'none';
            previewImg.src = '';
            removeBtn.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="evtPickerSearch" placeholder="Search images…" autocomplete="off">' +
                '<span class="media-picker-toolbar-label">Folder:</span>' +
                '<select class="media-picker-folder" id="evtPickerFolder">' +
                    '<option value="">All media</option>' +
                    '<option value="0">Unassigned</option>' +
                '</select>' +
            '</div>' +
            '<div class="media-picker-body" id="evtPickerGrid">' +
                '<p style="text-align:center;color:var(--gray-400);padding-top:3rem;">Loading…</p>' +
            '</div>';

        var searchInput  = pickerBody.querySelector('#evtPickerSearch');
        var folderSelect = pickerBody.querySelector('#evtPickerFolder');
        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('evtPickerGrid');
        if (!grid) return;
        grid.innerHTML = '<p style="text-align:center;color:var(--gray-400);padding-top:2rem;">Loading…</p>';

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

        fetch(url, { credentials: 'same-origin' })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                // Populate folder options once
                var folderSelect = document.getElementById('evtPickerFolder');
                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 event-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('.event-picker-item').forEach(function (item) {
                    item.addEventListener('click', function () {
                        var id   = item.dataset.id;
                        var url  = item.dataset.full;
                        var thumb = item.dataset.url;

                        mediaIdInput.value = id;
                        previewImg.src = thumb || url;
                        previewBox.style.display = 'block';
                        if (removeBtn) removeBtn.style.display = '';
                        pickerBtn.textContent = '📷 Change Image';
                        closePicker();
                    });
                });
            })
            .catch(function () {
                var g = document.getElementById('evtPickerGrid');
                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;');
    }

    // ── Direct image upload ───────────────────────────────────────────────
    var uploadBtn      = document.getElementById('eventImageUploadBtn');
    var uploadInput    = document.getElementById('eventImageUploadInput');
    var uploadFeedback = document.getElementById('eventUploadFeedback');

    // Trigger native file picker via hidden input
    if (uploadBtn && uploadInput) {
        uploadBtn.addEventListener('click', function () {
            uploadInput.click();
        });

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

            // Grab CSRF token from the main event form
            var csrfInput = document.querySelector('#eventForm input[name="_csrf_token"]');
            var csrfToken = csrfInput ? csrfInput.value : '';

            uploadFeedback.style.color = '#888';
            uploadFeedback.textContent = 'Uploading…';
            uploadBtn.disabled = true;

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

            fetch('<?= admin_url('events/upload-image') ?>', {
                method: 'POST',
                credentials: 'same-origin',
                body: fd,
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                uploadBtn.disabled = false;
                uploadInput.value  = '';

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

                // Set media_id and update preview
                mediaIdInput.value = data.media_id;
                previewImg.src     = data.thumb_url || data.url;
                previewBox.style.display = 'block';
                if (removeBtn) removeBtn.style.display = '';
                pickerBtn.textContent = '📷 Change Image';

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

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