<?php ob_start();
$fileMime  = $media['file_type'] ?? '';
$fileExtE  = strtolower(pathinfo($media['file_path'] ?? '', PATHINFO_EXTENSION));
$isVideoE  = $isVideo ?? (str_starts_with($fileMime, 'video/') || in_array($fileExtE, ['mp4', 'webm', 'ogv', 'mov'], true));
$isImageE  = $isImage ?? (!$isVideoE && (str_starts_with($fileMime, 'image/') || in_array($fileExtE, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'avif'], true)));
$fileUrl   = '/uploads/' . ltrim($media['file_path'], '/');
$thumbUrl  = $isImageE ? thumb_url($media['file_path']) : null;
$posterUrl = ($isVideoE && !empty($media['video_poster'])) ? '/uploads/' . ltrim($media['video_poster'], '/') : null;
$sizeBytes = (int) $media['file_size'];
$size      = $sizeBytes > 0 ? ($sizeBytes >= 1048576 ? round($sizeBytes / 1048576, 1) . ' MB' : round($sizeBytes / 1024, 1) . ' KB') : '–';
?>

<div class="content-header">
    <div class="content-header-left">
        <div class="content-header-icon"><?= icon('folder-open', 20) ?></div>
        <h2><?= __('admin.media_edit.title') ?></h2>
    </div>
    <div class="header-actions">
        <a href="<?= admin_url('media') ?><?= $media['folder_id'] ? '?folder=' . (int)$media['folder_id'] : '' ?>" class="btn btn-secondary"><?= __('admin.media_edit.back') ?></a>
    </div>
</div>

<div class="form-grid" style="grid-template-columns:1fr 300px;">

    <!-- Left: Preview + Metadata form -->
    <div>
        <!-- Preview -->
        <div class="form-card" style="text-align:center;padding:1.5rem;">
            <?php if ($isVideoE): ?>
            <div class="mm-edit-video-wrap">
                <video controls preload="metadata"
                       <?php if ($posterUrl): ?>poster="<?= e($posterUrl) ?>"<?php endif; ?>
                       style="max-width:100%;max-height:320px;border-radius:6px;background:#000;">
                    <source src="<?= e($fileUrl) ?>" type="<?= e($fileMime ?: 'video/mp4') ?>">
                    <?= __('admin.media_edit_extra.video_unsupported') ?>
                </video>
            </div>
            <?php elseif ($isImageE): ?>
            <?php if ($thumbUrl): ?>
            <img src="<?= e($thumbUrl) ?>" alt="<?= e($media['alt_text'] ?? '') ?>"
                 style="max-width:100%;max-height:260px;object-fit:contain;border-radius:4px;">
            <?php else: ?>
            <img src="<?= e($fileUrl) ?>" alt="<?= e($media['alt_text'] ?? '') ?>"
                 style="max-width:100%;max-height:260px;object-fit:contain;border-radius:4px;">
            <?php endif; ?>
            <?php else: ?>
            <div style="opacity:0.5;"><svg width="56" height="56" 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>
            <p style="font-size:0.875rem;color:var(--gray-500);"><?= e($media['file_type'] ?? 'file') ?></p>
            <?php endif; ?>
            <div style="margin-top:1rem;">
                <a href="<?= e($fileUrl) ?>" target="_blank" class="btn btn-secondary btn-sm"><?= __('admin.media_edit.open_original') ?></a>
            </div>
        </div>

        <!-- Metadata form -->
        <div class="form-card">
            <h4><?= __('admin.media_edit.metadata') ?></h4>
            <form method="POST" action="<?= admin_url('media/update/' . (int)$media['id']) ?>" class="admin-form">
                <?= $csrf->field() ?>

                <div class="form-group">
                    <label for="title"><?= __('admin.media_edit.display_title') ?></label>
                    <input type="text" id="title" name="title"
                           value="<?= e($media['title'] ?? '') ?>"
                           placeholder="<?= __('admin.media_edit.display_title_help') ?>">
                </div>

                <?php if (!$isVideoE): ?>
                <div class="form-group">
                    <label for="alt_text"><?= __('admin.media_edit.alt_text') ?></label>
                    <input type="text" id="alt_text" name="alt_text"
                           value="<?= e($media['alt_text'] ?? '') ?>"
                           placeholder="<?= __('admin.media_edit.alt_text_help') ?>">
                    <small class="form-hint"><?= __('admin.media_edit.alt_text_hint') ?></small>
                </div>
                <?php endif; ?>

                <div class="form-group">
                    <label for="description"><?= __('admin.media_edit.description') ?></label>
                    <textarea id="description" name="description" rows="3"
                              placeholder="<?= __('admin.media_edit.description_help') ?>"><?= e($media['description'] ?? '') ?></textarea>
                </div>

                <?php if ($isVideoE): ?>
                <!-- Video Poster / Vorschaubild -->
                <div class="form-group">
                    <label><?= __('admin.media_edit_extra.poster_label') ?> <small style="font-weight:normal;color:#aaa;"><?= __('admin.media_edit_extra.poster_hint') ?></small></label>
                    <div class="iw-media-picker-field" data-type="image">
                        <div class="iw-mpf-preview" id="posterPreviewWrap">
                            <?php if ($posterUrl): ?>
                            <img src="<?= e($posterUrl) ?>" alt="Poster" id="posterPreviewImg" style="max-height:80px;border-radius:4px;">
                            <?php else: ?>
                            <span class="iw-mpf-placeholder" id="posterPreviewImg"><?= __('admin.media_edit_extra.no_poster_selected') ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="iw-mpf-actions">
                            <input type="hidden" id="video_poster" name="video_poster" value="<?= e($media['video_poster'] ?? '') ?>">
                            <button type="button" class="btn btn-secondary btn-sm iw-mpf-pick-btn"
                                    data-input="video_poster"
                                    data-preview="posterPreviewWrap"
                                    data-picker-type="image">
                                <svg width="14" height="14" viewBox="0 0 20 20" fill="none" style="vertical-align:-2px;margin-right:4px;"><path d="M2 6a2 2 0 012-2h4l2 2h6a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" stroke="currentColor" stroke-width="1.5" fill="none"/></svg> <?= __('admin.media_edit_extra.select_from_media') ?>
                            </button>
                            <?php if (!empty($media['video_poster'])): ?>
                            <button type="button" class="btn btn-secondary btn-sm iw-mpf-clear-btn"
                                    data-input="video_poster"
                                    data-preview="posterPreviewWrap">
                                ✕ <?= __('admin.media_edit_extra.remove') ?>
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="form-group">
                    <label for="folder_id"><?= __('admin.media_edit.folder') ?></label>
                    <select id="folder_id" name="folder_id">
                        <option value=""><?= __('admin.media.unassigned') ?></option>
                        <?php foreach ($folders as $f): ?>
                        <option value="<?= (int)$f['id'] ?>" <?= (string)($media['folder_id'] ?? '') === (string)$f['id'] ? 'selected' : '' ?>><?= e($f['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <button type="submit" class="btn btn-primary"><?= __('admin.media_edit.save') ?></button>
            </form>
        </div>
    </div>

    <!-- Right: File details + actions -->
    <div>
        <div class="form-card">
            <h4><?= __('admin.media_edit.file_details') ?></h4>
            <table style="width:100%;font-size:0.8125rem;border-collapse:collapse;">
                <tbody>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);width:40%;"><?= __('admin.media_edit.filename') ?></td>
                    <td style="padding:0.35rem 0;word-break:break-all;"><code style="font-size:0.8125rem;"><?= e($media['filename']) ?></code></td>
                </tr>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.original_name') ?></td>
                    <td style="padding:0.35rem 0;word-break:break-all;"><?= e($media['original_name']) ?></td>
                </tr>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.type') ?></td>
                    <td style="padding:0.35rem 0;">
                        <?= e($media['file_type'] ?? '–') ?>
                        <?php if ($isVideoE): ?>
                        <span style="display:inline-block;margin-left:0.35rem;padding:0.1rem 0.45rem;background:#e0f2fe;color:#0284c7;border-radius:4px;font-size:0.75rem;font-weight:600;">Video</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.size') ?></td>
                    <td style="padding:0.35rem 0;"><?= e($size) ?></td>
                </tr>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.path') ?></td>
                    <td style="padding:0.35rem 0;word-break:break-all;"><code style="font-size:0.75rem;">/uploads/<?= e($media['file_path']) ?></code></td>
                </tr>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.uploaded') ?></td>
                    <td style="padding:0.35rem 0;"><?= e(date('d.m.Y H:i', strtotime($media['created_at']))) ?></td>
                </tr>
                <?php if ($dimensions): ?>
                <tr>
                    <td style="padding:0.35rem 0;color:var(--gray-500);"><?= __('admin.media_edit.dimensions') ?></td>
                    <td style="padding:0.35rem 0;"><?= e($dimensions) ?></td>
                </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- URL for copy-paste -->
        <div class="form-card">
            <h4><?= __('admin.media_edit.file_url') ?></h4>
            <div style="display:flex;gap:0.5rem;align-items:center;">
                <input type="text" id="fileUrlField" value="<?= e($fileUrl) ?>" readonly
                       style="flex:1;padding:0.4rem 0.6rem;border:1px solid var(--gray-300);border-radius:var(--radius-sm);font-size:0.8125rem;font-family:var(--font-mono);background:var(--gray-50);">
                <button type="button" class="btn btn-secondary btn-sm" id="copyUrlBtn" title="<?= __('admin.media_edit.copy') ?>"><?= __('admin.media_edit.copy') ?></button>
            </div>
            <small class="form-hint" style="margin-top:0.5rem;display:block;"><?= __('admin.media_edit.url_hint') ?></small>
        </div>

        <!-- Danger zone: Delete -->
        <div class="form-card" style="border-color:var(--admin-danger);">
            <h4 style="color:var(--admin-danger);"><?= __('admin.media_edit.delete_title') ?></h4>
            <p style="font-size:0.8125rem;color:var(--gray-600);margin-bottom:0.75rem;"><?= __('admin.media_edit.delete_text') ?></p>
            <form method="POST" action="<?= admin_url('media/delete/' . (int)$media['id']) ?>"
                  onsubmit="return confirm('<?= __('admin.media_edit.delete_text') ?>')">
                <?= $csrf->field() ?>
                <input type="hidden" name="ref" value="<?= admin_url('media') ?>">
                <button type="submit" class="btn btn-danger btn-sm"><?= __('admin.media_edit.delete_btn') ?></button>
            </form>
        </div>
    </div>

</div>

<script>
(function () {
    // Copy URL – only page-specific logic here; picker buttons are handled by wireMpfButtons in admin.js
    var copyBtn  = document.getElementById('copyUrlBtn');
    var urlField = document.getElementById('fileUrlField');
    if (copyBtn && urlField) {
        copyBtn.addEventListener('click', function () {
            var url = urlField.value;
            function onCopied() {
                copyBtn.textContent = '<?= __('admin.media_edit.copied') ?>';
                setTimeout(function () { copyBtn.textContent = '<?= __('admin.media_edit.copy') ?>'; }, 2000);
            }
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(url).then(onCopied);
            } else {
                urlField.select();
                try { document.execCommand('copy'); } catch (_) {}
                onCopied();
            }
        });
    }
})();
</script>

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