<?php ob_start(); ?>

<?php
$themeActions = [];
if ($zipOk) {
    $themeActions[] = ['url' => '/admin/themes/upload', 'label' => __('admin.themes.install'), 'class' => 'btn-primary'];
} else {
    $themeActions[] = ['url' => '', 'label' => __('admin.themes.install'), 'class' => 'btn-secondary btn-disabled', 'attrs' => 'title="' . e(__('admin.themes.zip_not_available')) . '"'];
}
admin_content_header(__('admin.nav.themes'), 'palette', $themeActions);
?>

<div class="theme-grid">
    <?php foreach ($themes as $slug => $theme): ?>
    <?php $isActive    = ($slug === $activeTheme); ?>
    <?php $isProtected = in_array($slug, $permanentlyProtected, true); ?>
    <?php $colors      = $theme['colors'] ?? []; ?>
    <div class="theme-card <?= $isActive ? 'theme-card--active' : '' ?>">

        <?php if ($isActive): ?>
        <div class="theme-card__badge"><?= __('admin.themes.active_badge') ?></div>
        <?php endif; ?>

        <!-- Preview area: thumbnail image → color gradient fallback → placeholder -->
        <div class="theme-card__preview"<?php if (!empty($theme['thumbnailUrl'])): ?> role="button" tabindex="0" aria-label="<?= e($theme['name']) ?> – Vorschau vergrößern" data-lightbox-src="<?= e($theme['thumbnailUrl']) ?>" data-lightbox-title="<?= e($theme['name']) ?> v<?= e($theme['version']) ?>"<?php endif; ?>>
            <?php if (!empty($theme['thumbnailUrl'])): ?>
            <img class="theme-card__thumbnail"
                 src="<?= e($theme['thumbnailUrl']) ?>"
                 alt="<?= e($theme['name']) ?> preview"
                 loading="lazy">
            <span class="theme-card__zoom-hint" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35"/><path d="M11 8v6M8 11h6"/></svg></span>
            <?php elseif (!empty($colors)): ?>
            <?php
                // Generate a rich color preview from theme colors
                $colorValues = array_values($colors);
                $primary   = $colorValues[0] ?? '#666';
                $secondary = $colorValues[1] ?? $primary;
                $bg        = $colors['background'] ?? '#f8f9fa';
                $text      = $colors['text'] ?? '#333';
            ?>
            <div class="theme-color-preview" style="background: <?= e($bg) ?>;">
                <div class="theme-color-preview__header" style="background: linear-gradient(135deg, <?= e($primary) ?>, <?= e($secondary) ?>);"></div>
                <div class="theme-color-preview__body">
                    <div class="theme-color-preview__line theme-color-preview__line--title" style="background: <?= e($text) ?>;"></div>
                    <div class="theme-color-preview__line" style="background: <?= e($text) ?>; opacity:.3;"></div>
                    <div class="theme-color-preview__line" style="background: <?= e($text) ?>; opacity:.2; width:70%;"></div>
                </div>
                <div class="theme-color-swatches">
                    <?php foreach ($colors as $colorName => $colorValue): ?>
                    <span class="theme-color-swatch"
                          style="background:<?= e($colorValue) ?>;"
                          title="<?= e($colorName) ?>: <?= e($colorValue) ?>"></span>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php else: ?>
            <div class="theme-color-bar theme-color-bar--empty"><?= __('admin.themes.no_preview') ?></div>
            <?php endif; ?>

            <!-- Theme name overlay -->
            <div class="theme-card__name-overlay">
                <strong><?= e($theme['name']) ?></strong>
                <span class="theme-card__version">v<?= e($theme['version']) ?></span>
            </div>
        </div>

        <!-- Meta -->
        <div class="theme-card__body">
            <p class="theme-card__description">
                <?= !empty($theme['description']) ? e($theme['description']) : '<em class="text-muted">' . __('admin.themes.no_description') . '</em>' ?>
            </p>
            <div class="theme-card__meta text-muted">
                <span><?= __('admin.themes.by_author', [':author' => e($theme['author'] ?: 'Unknown')]) ?></span>
                &nbsp;·&nbsp;
                <span><?= __('admin.themes.slug_label', [':slug' => e($slug)]) ?></span>
            </div>
        </div>

        <!-- Actions -->
        <div class="theme-card__footer">
            <?php if ($isActive): ?>
            <span class="btn btn-success btn-sm" style="cursor:default;">✓ <?= __('admin.themes.currently_active') ?></span>
            <?php else: ?>
            <form method="POST" action="/admin/themes/activate"
                  onsubmit="return confirm('<?= __('admin.themes.confirm_activate', [':name' => e(addslashes($theme['name']))]) ?>')">
                <?= $csrf->field() ?>
                <input type="hidden" name="theme" value="<?= e($slug) ?>">
                <button type="submit" class="btn btn-primary btn-sm"><?= __('admin.themes.activate') ?></button>
            </form>
            <?php endif; ?>

            <a href="/" target="_blank" class="btn btn-secondary btn-sm" title="<?= __('admin.themes.view_site') ?>"><?= __('admin.themes.view_site') ?></a>

            <?php if (!$isActive && !$isProtected): ?>
            <form method="POST" action="/admin/themes/uninstall"
                  onsubmit="return confirm('<?= __('admin.themes.confirm_uninstall', [':name' => e(addslashes($theme['name']))]) ?>')">
                <?= $csrf->field() ?>
                <input type="hidden" name="theme" value="<?= e($slug) ?>">
                <button type="submit" class="btn btn-danger btn-sm"><?= __('admin.themes.uninstall') ?></button>
            </form>
            <?php elseif ($isProtected && !$isActive): ?>
            <span class="btn btn-secondary btn-sm theme-protected-hint"
                  title="<?= __('admin.themes.protected_hint') ?>"><?= __('admin.themes.protected') ?></span>
            <?php endif; ?>
        </div>

    </div>
    <?php endforeach; ?>

    <?php if (empty($themes)): ?>
    <p class="text-muted"><?= __('admin.themes.no_themes') ?></p>
    <?php endif; ?>
</div>

<style>
.theme-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1.5rem;
    margin-top: 1rem;
}

.theme-card {
    position: relative;
    border: 2px solid var(--border-color, #e0e0e0);
    border-radius: 10px;
    overflow: hidden;
    background: #fff;
    transition: box-shadow .2s, border-color .2s, transform .2s;
    display: flex;
    flex-direction: column;
}
.theme-card:hover {
    box-shadow: 0 6px 24px rgba(0,0,0,.1);
    transform: translateY(-2px);
}
.theme-card--active {
    border-color: var(--primary, #2563eb);
    box-shadow: 0 0 0 1px var(--primary, #2563eb);
}

.theme-card__badge {
    position: absolute;
    top: .6rem; right: .6rem;
    background: var(--primary, #2563eb);
    color: #fff;
    font-size: .7rem;
    font-weight: 700;
    padding: .25em .7em;
    border-radius: 12px;
    text-transform: uppercase;
    letter-spacing: .05em;
    z-index: 2;
    box-shadow: 0 2px 6px rgba(0,0,0,.15);
}

.theme-card__preview {
    position: relative;
    height: 180px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

/* Thumbnail image preview */
.theme-card__thumbnail {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

/* Color preview (fallback when no thumbnail) */
.theme-color-preview {
    position: absolute;
    inset: 0;
    display: flex;
    flex-direction: column;
}
.theme-color-preview__header {
    height: 50%;
    position: relative;
}
.theme-color-preview__body {
    flex: 1;
    padding: 12px 16px;
    display: flex;
    flex-direction: column;
    gap: 6px;
    justify-content: center;
}
.theme-color-preview__line {
    height: 6px;
    border-radius: 3px;
    width: 90%;
}
.theme-color-preview__line--title {
    height: 10px;
    border-radius: 5px;
    width: 60%;
    margin-bottom: 4px;
}
.theme-color-swatches {
    position: absolute;
    bottom: 8px;
    right: 10px;
    display: flex;
    gap: 4px;
}
.theme-color-swatch {
    display: block;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 2px solid rgba(255,255,255,.7);
    box-shadow: 0 1px 4px rgba(0,0,0,.15);
}

/* Legacy dots fallback */
.theme-color-bar {
    display: flex;
    gap: 8px;
    align-items: center;
}
.theme-color-bar--empty { font-size: .8rem; color: #aaa; }

.theme-card__name-overlay {
    position: absolute;
    bottom: 0; left: 0; right: 0;
    background: linear-gradient(transparent, rgba(0,0,0,.6));
    color: #fff;
    padding: .5rem .85rem;
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    font-size: .9rem;
    z-index: 1;
}
.theme-card__version {
    font-size: .75rem;
    opacity: .8;
    background: rgba(255,255,255,.15);
    padding: .1em .45em;
    border-radius: 4px;
}

.theme-card__body {
    padding: .85rem 1rem .6rem;
    flex: 1;
}
.theme-card__description {
    font-size: .85rem;
    margin: 0 0 .5rem;
    min-height: 2.5em;
    line-height: 1.45;
    color: #4a5568;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
.theme-card__meta {
    font-size: .78rem;
}
.theme-card__meta code {
    font-size: .85em;
    background: #f0f0f0;
    padding: .1em .35em;
    border-radius: 3px;
}

.theme-card__footer {
    padding: .65rem 1rem;
    border-top: 1px solid var(--border-color, #e0e0e0);
    display: flex;
    gap: .4rem;
    align-items: center;
    flex-wrap: wrap;
    background: #fafbfc;
}

.theme-protected-hint {
    opacity: .55;
    cursor: default;
    font-size: .75rem;
}

/* Thumbnail: object-position top to show hero area */
.theme-card__thumbnail {
    object-position: top center;
}

/* Zoom hint icon on hover */
.theme-card__preview[data-lightbox-src] {
    cursor: zoom-in;
}
.theme-card__zoom-hint {
    position: absolute;
    top: .5rem;
    left: .5rem;
    background: rgba(0,0,0,.5);
    color: #fff;
    border-radius: 6px;
    padding: .3rem;
    line-height: 0;
    opacity: 0;
    transition: opacity .2s;
    z-index: 2;
}
.theme-card__preview:hover .theme-card__zoom-hint {
    opacity: 1;
}

/* Lightbox overlay */
.theme-lightbox {
    position: fixed;
    inset: 0;
    z-index: 9999;
    background: rgba(0,0,0,.88);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    opacity: 0;
    pointer-events: none;
    transition: opacity .25s ease;
    backdrop-filter: blur(4px);
}
.theme-lightbox.is-open {
    opacity: 1;
    pointer-events: auto;
}
.theme-lightbox__img {
    max-width: 90vw;
    max-height: 82vh;
    border-radius: 8px;
    box-shadow: 0 12px 48px rgba(0,0,0,.5);
    object-fit: contain;
    transform: scale(.95);
    transition: transform .3s ease;
}
.theme-lightbox.is-open .theme-lightbox__img {
    transform: scale(1);
}
.theme-lightbox__title {
    color: #fff;
    font-size: .9rem;
    font-weight: 600;
    margin-top: .75rem;
    opacity: .8;
    letter-spacing: .03em;
}
.theme-lightbox__close {
    position: absolute;
    top: 1rem;
    right: 1.5rem;
    background: rgba(255,255,255,.15);
    border: none;
    color: #fff;
    font-size: 1.5rem;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background .2s;
    line-height: 0;
}
.theme-lightbox__close:hover {
    background: rgba(255,255,255,.25);
}

@media (max-width: 640px) {
    .theme-grid {
        grid-template-columns: 1fr;
    }
    .theme-lightbox__img {
        max-width: 96vw;
        max-height: 75vh;
        border-radius: 4px;
    }
}
</style>

<!-- Theme Screenshot Lightbox -->
<div class="theme-lightbox" id="themeLightbox">
    <button class="theme-lightbox__close" id="themeLightboxClose" aria-label="Schließen">&times;</button>
    <img class="theme-lightbox__img" id="themeLightboxImg" src="" alt="">
    <div class="theme-lightbox__title" id="themeLightboxTitle"></div>
</div>

<script>
(function () {
    var overlay = document.getElementById('themeLightbox');
    var img     = document.getElementById('themeLightboxImg');
    var title   = document.getElementById('themeLightboxTitle');
    var closeBtn = document.getElementById('themeLightboxClose');
    if (!overlay) return;

    // Open lightbox on preview click
    document.querySelectorAll('.theme-card__preview[data-lightbox-src]').forEach(function (el) {
        el.addEventListener('click', function (e) {
            e.preventDefault();
            img.src = el.getAttribute('data-lightbox-src');
            img.alt = el.getAttribute('data-lightbox-title') || '';
            title.textContent = el.getAttribute('data-lightbox-title') || '';
            overlay.classList.add('is-open');
            document.body.style.overflow = 'hidden';
        });
        el.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); el.click(); }
        });
    });

    function closeLightbox() {
        overlay.classList.remove('is-open');
        document.body.style.overflow = '';
    }

    closeBtn.addEventListener('click', closeLightbox);
    overlay.addEventListener('click', function (e) {
        if (e.target === overlay) closeLightbox();
    });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && overlay.classList.contains('is-open')) closeLightbox();
    });
})();
</script>

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