<?php ob_start(); ?>

<?php
admin_content_header($package['name'] ?? 'Package', 'store', [
    ['url' => admin_url('marketplace'), 'label' => __('admin.marketplace.back_to_marketplace'), 'class' => 'btn-secondary'],
]);
?>

<div class="mp-detail">
    <div class="mp-detail__main">
        <!-- Gallery / Thumbnail -->
        <?php
            use App\Support\MarketplacePlaceholder;
            $pkgType       = $package['type'] ?? 'plugin';
            $pkgName       = $package['name'] ?? '';
            $pkgCategory   = $package['category'] ?? 'content';
            $pkgThumbnail  = $package['thumbnail'] ?? '';
            $pkgScreenshots = ($pkgType === 'theme') ? ($package['screenshots'] ?? []) : [];
            $hasScreenshots = count($pkgScreenshots) >= 1;
            $showThumbstrip = ($pkgType === 'theme');
        ?>
        <div class="mp-detail__gallery">
            <!-- Hero -->
            <div class="mp-detail__hero">
                <?php if ($hasScreenshots): ?>
                    <?php foreach ($pkgScreenshots as $i => $ssUrl): ?>
                    <div class="mp-detail__slide<?= $i === 0 ? ' active' : '' ?>">
                        <img src="<?= e($ssUrl) ?>" alt="<?= e($pkgName) ?> – Screenshot <?= $i + 1 ?>">
                    </div>
                    <?php endforeach; ?>
                <?php elseif ($pkgThumbnail !== ''): ?>
                    <div class="mp-detail__slide active">
                        <img src="<?= e($pkgThumbnail) ?>" alt="<?= e($pkgName) ?>">
                    </div>
                <?php else: ?>
                    <div class="mp-detail__slide active mp-placeholder--named">
                        <?= MarketplacePlaceholder::render($pkgCategory, '#2563eb', '#8b5cf6', $pkgName) ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Thumbstrip (Themes only, only when screenshots present) -->
            <?php if ($showThumbstrip && $hasScreenshots): ?>
            <div class="mp-detail__thumbstrip">
                <?php foreach ($pkgScreenshots as $i => $ssUrl): ?>
                <div class="mp-detail__thumb<?= $i === 0 ? ' active' : '' ?>" data-slide="<?= $i ?>">
                    <img src="<?= e($ssUrl) ?>" alt="Screenshot <?= $i + 1 ?>">
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Description -->
        <?php if (!empty($package['description'])): ?>
        <div class="card" style="margin-top:1.5rem;">
            <div class="card-body">
                <h3 style="margin-top:0;"><?= __('admin.marketplace.description') ?></h3>
                <p style="line-height:1.6;"><?= e($package['description']) ?></p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="mp-detail__sidebar">
        <!-- Info card -->
        <div class="card">
            <div class="card-body">
                <div class="mp-detail__badges" style="margin-bottom:1rem;">
                    <?php $type = $package['type'] ?? 'plugin'; ?>
                    <span class="mp-badge mp-badge--<?= e($type) ?>"><?= $type === 'theme' ? __('admin.marketplace.type_theme') : __('admin.marketplace.type_plugin') ?></span>
                    <?php if (!empty($package['is_premium'])): ?>
                    <span class="mp-badge mp-badge--premium"><?= __('admin.marketplace.premium') ?></span>
                    <?php else: ?>
                    <span class="mp-badge mp-badge--free"><?= __('admin.marketplace.free') ?></span>
                    <?php endif; ?>
                </div>

                <table class="mp-detail__info">
                    <tr>
                        <th><?= __('admin.marketplace.version') ?></th>
                        <td><?= e($package['version'] ?? '') ?></td>
                    </tr>
                    <tr>
                        <th><?= __('admin.marketplace.author') ?></th>
                        <td><?= e($package['author'] ?? '') ?></td>
                    </tr>
                    <?php if (!empty($package['min_cms_version'])): ?>
                    <tr>
                        <th><?= __('admin.marketplace.min_cms') ?></th>
                        <td>
                            <?= e($package['min_cms_version']) ?>
                            <?php if (empty($package['_cms_compatible'])): ?>
                            <span class="text-danger" style="font-size:.8rem;">(<?= __('admin.marketplace.incompatible') ?>)</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endif; ?>
                    <?php if (!empty($package['price'])): ?>
                    <tr>
                        <th>Preis</th>
                        <td><?= e($package['price']) ?> &euro;</td>
                    </tr>
                    <?php endif; ?>
                    <?php if (!empty($package['categories'])): ?>
                    <tr>
                        <th>Kategorien</th>
                        <td><?= e(is_array($package['categories']) ? implode(', ', $package['categories']) : $package['categories']) ?></td>
                    </tr>
                    <?php endif; ?>
                </table>

                <!-- Signature / Integrity badges -->
                <?php
                    $hasSig    = !empty($package['signature_b64']);
                    $hasSha    = !empty($package['sha256_hash']);
                    $keyId     = $package['key_id'] ?? '';
                ?>
                <div class="mp-sig-badges" style="margin-top:1rem; display:flex; flex-wrap:wrap; gap:.4rem;">
                    <?php if ($hasSig): ?>
                    <span class="mp-sig-badge mp-sig-badge--ok" title="Ed25519 · <?= e($keyId) ?>">
                        <?= icon('shield-check', 13) ?> Ed25519
                    </span>
                    <?php else: ?>
                    <span class="mp-sig-badge mp-sig-badge--warn" title="<?= __('admin.marketplace.sig_missing') ?>">
                        <?= icon('shield-off', 13) ?> <?= __('admin.marketplace.sig_missing') ?>
                    </span>
                    <?php endif; ?>

                    <?php if ($hasSha): ?>
                    <span class="mp-sig-badge mp-sig-badge--ok" title="SHA-256: <?= e($package['sha256_hash'] ?? '') ?>">
                        <?= icon('fingerprint', 13) ?> SHA-256
                    </span>
                    <?php else: ?>
                    <span class="mp-sig-badge mp-sig-badge--warn" title="<?= __('admin.marketplace.hash_missing') ?>">
                        <?= icon('fingerprint', 13) ?> <?= __('admin.marketplace.hash_missing') ?>
                    </span>
                    <?php endif; ?>

                    <?php if ($keyId !== ''): ?>
                    <span class="mp-sig-badge mp-sig-badge--neutral" title="<?= __('admin.marketplace.key_id') ?>: <?= e($keyId) ?>">
                        <?= icon('key', 13) ?> <?= e(mb_strimwidth($keyId, 0, 16, '…')) ?>
                    </span>
                    <?php endif; ?>
                </div>

                <!-- Status -->
                <?php if ($package['_installed'] ?? false): ?>
                <div class="mp-detail__status" style="margin-top:1rem; padding:.75rem; border-radius:8px; background:var(--color-success-bg, #dcfce7);">
                    <?= icon('check-circle', 16) ?>
                    <strong><?= __('admin.marketplace.installed') ?></strong> (v<?= e($package['_installed_version'] ?? '') ?>)
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Action card -->
        <div class="card" style="margin-top:1rem;">
            <div class="card-body">
                <?php
                    $isInstalled   = $package['_installed'] ?? false;
                    $hasUpdate     = $package['_has_update'] ?? false;
                    $cmsCompatible = $package['_cms_compatible'] ?? true;
                    $isPremium     = !empty($package['is_premium']);
                    $hasLicense    = !empty($package['_license_key']);
                ?>

                <?php if (!$cmsCompatible): ?>
                <p class="text-danger"><?= __('admin.marketplace.cms_too_old', [':version' => e($package['min_cms_version'] ?? '')]) ?></p>

                <?php elseif ($isInstalled && $hasUpdate): ?>
                <!-- Update form -->
                <form method="POST" action="<?= admin_url('marketplace/update') ?>"
                      onsubmit="return confirm('<?= e(__('admin.marketplace.confirm_update', [':name' => $package['name'] ?? '', ':version' => $package['version'] ?? ''])) ?>')">
                    <?= $csrf->field() ?>
                    <input type="hidden" name="slug" value="<?= e($package['slug'] ?? '') ?>">
                    <input type="hidden" name="version" value="<?= e($package['version'] ?? '') ?>">
                    <button type="submit" class="btn btn-warning" style="width:100%;">
                        <?= icon('download', 16) ?> <?= __('admin.marketplace.update') ?> (v<?= e($package['version'] ?? '') ?>)
                    </button>
                </form>

                <?php elseif ($isInstalled): ?>
                <p class="text-success" style="text-align:center; margin:0;">
                    <?= icon('check-circle', 18) ?> <?= __('admin.marketplace.up_to_date') ?>
                </p>

                <?php else: ?>
                <!-- Install form -->
                <form method="POST" action="<?= admin_url('marketplace/install') ?>"
                      onsubmit="return confirm('<?= e(__('admin.marketplace.confirm_install', [':name' => $package['name'] ?? ''])) ?>')">
                    <?= $csrf->field() ?>
                    <input type="hidden" name="slug" value="<?= e($package['slug'] ?? '') ?>">
                    <input type="hidden" name="version" value="<?= e($package['version'] ?? '') ?>">

                    <?php if ($isPremium): ?>
                    <div class="form-group" style="margin-bottom:1rem;">
                        <label for="license_key"><?= __('admin.marketplace.license_key') ?></label>
                        <input type="text" id="license_key" name="license_key" class="form-control"
                               value="<?= e($package['_license_key'] ?? '') ?>"
                               placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
                               <?= $isPremium && !$hasLicense ? 'required' : '' ?>>
                        <small class="text-muted"><?= __('admin.marketplace.requires_license') ?></small>
                    </div>
                    <?php endif; ?>

                    <button type="submit" class="btn btn-primary" style="width:100%;">
                        <?= icon('download', 16) ?> <?= __('admin.marketplace.install') ?>
                    </button>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
/* ── Layout ─────────────────────────────────────────────────── */
.mp-detail {
    display: grid;
    grid-template-columns: 1fr 340px;
    gap: 1.5rem;
    align-items: start;
}
@media (max-width: 900px) {
    .mp-detail { grid-template-columns: 1fr; }
}

/* ── Gallery ─────────────────────────────────────────────────── */
.mp-detail__gallery {
    border-radius: var(--radius-lg, 12px);
    overflow: hidden;
    background: var(--color-muted-bg, #f1f5f9);
    border: 1px solid var(--color-border, #e2e8f0);
}
.mp-detail__hero {
    aspect-ratio: 16 / 10;
    position: relative;
    overflow: hidden;
}
.mp-detail__slide {
    position: absolute;
    inset: 0;
    opacity: 0;
    transition: opacity .25s ease;
    pointer-events: none;
}
.mp-detail__slide.active {
    opacity: 1;
    pointer-events: auto;
}
.mp-detail__slide img {
    width: 100%; height: 100%;
    object-fit: cover;
    display: block;
}

/* Placeholder inside hero */
.mp-placeholder {
    position: absolute; inset: 0;
    display: flex; align-items: center; justify-content: center;
    background:
        radial-gradient(circle at 30% 30%, var(--ph-accent-soft, rgba(37,99,235,.08)) 0%, transparent 60%),
        radial-gradient(circle at 70% 80%, var(--ph-primary-soft, rgba(139,92,246,.06)) 0%, transparent 55%);
}
.mp-placeholder svg {
    width: 44%; height: auto;
    color: var(--ph-stroke, var(--color-primary, #2563eb));
    opacity: .82;
    filter: drop-shadow(0 2px 8px rgba(37,99,235,.18));
}
.mp-placeholder__label {
    position: absolute;
    bottom: 12px; left: 14px;
    font-size: 11px;
    letter-spacing: .08em;
    text-transform: uppercase;
    color: var(--color-muted, #64748b);
    font-weight: 600;
}
.mp-placeholder--named .mp-placeholder__name {
    position: absolute;
    bottom: 44px; left: 0; right: 0;
    text-align: center;
    font-size: 18px;
    font-weight: 700;
    letter-spacing: -.01em;
    color: var(--color-text, #0f172a);
    opacity: .5;
    pointer-events: none;
}

/* ── Thumbstrip ──────────────────────────────────────────────── */
.mp-detail__thumbstrip {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    padding: 10px;
    background: var(--color-surface-alt, #f8fafc);
    border-top: 1px solid var(--color-border, #e2e8f0);
}
.mp-detail__thumb {
    aspect-ratio: 16 / 10;
    border-radius: var(--radius-sm, 6px);
    overflow: hidden;
    cursor: pointer;
    border: 2px solid transparent;
    background: var(--color-muted-bg, #f1f5f9);
    transition: border-color .18s, transform .18s;
}
.mp-detail__thumb:hover { transform: translateY(-1px); border-color: var(--color-border, #e2e8f0); }
.mp-detail__thumb.active { border-color: var(--color-primary, #2563eb); }
.mp-detail__thumb img { width: 100%; height: 100%; object-fit: cover; display: block; pointer-events: none; }

/* ── Info table ──────────────────────────────────────────────── */
.mp-detail__info {
    width: 100%;
    font-size: .9rem;
}
.mp-detail__info th {
    text-align: left;
    padding: .35rem 1rem .35rem 0;
    color: var(--color-muted, #64748b);
    font-weight: 500;
    white-space: nowrap;
}
.mp-detail__info td { padding: .35rem 0; }

/* ── Signature badges ────────────────────────────────────────── */
.mp-sig-badge {
    display: inline-flex;
    align-items: center;
    gap: .25rem;
    padding: .2rem .55rem;
    border-radius: 99px;
    font-size: .78rem;
    font-weight: 500;
    line-height: 1;
}
.mp-sig-badge--ok      { background: var(--color-success-bg, #dcfce7); color: var(--color-success, #16a34a); }
.mp-sig-badge--warn    { background: var(--color-warning-bg, #fef9c3); color: var(--color-warning, #ca8a04); }
.mp-sig-badge--neutral { background: var(--color-surface-alt, #f1f5f9); color: var(--color-muted, #64748b); }
</style>

<script>
(function () {
    var gallery = document.querySelector('.mp-detail__gallery');
    if (!gallery) return;
    var slides = gallery.querySelectorAll('.mp-detail__slide');
    var thumbs = gallery.querySelectorAll('.mp-detail__thumb');
    if (!slides.length || !thumbs.length) return;

    function activate(idx) {
        slides.forEach(function (s, i) { s.classList.toggle('active', i === idx); });
        thumbs.forEach(function (t, i) { t.classList.toggle('active', i === idx); });
    }
    thumbs.forEach(function (thumb) {
        thumb.addEventListener('click', function () {
            activate(parseInt(thumb.dataset.slide, 10) || 0);
        });
    });
}());
</script>

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