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

<article class="download-detail">
    <div class="container">

        <header class="download-detail-header">
            <?php if (!empty($dl['category_name'])): ?>
            <span class="download-category">
                <a href="/download/category/<?= e($dl['category_slug']) ?>"><?= e($dl['category_name']) ?></a>
            </span>
            <?php endif; ?>

            <h1><?= e($dl['title']) ?></h1>

            <?php if (!empty($dl['version'])): ?>
            <span class="download-version">Version: <?= e($dl['version']) ?></span>
            <?php endif; ?>
        </header>

        <?php if (!empty($dl['media_path'])): ?>
        <div class="download-detail-image">
            <?= picture_tag($dl['media_path'], $dl['media_alt'] ?? $dl['title'], 'download-hero-image') ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($dl['excerpt'])): ?>
        <div class="download-detail-excerpt">
            <p><?= e($dl['excerpt']) ?></p>
        </div>
        <?php endif; ?>

        <?php if (!empty($dl['content'])): ?>
        <div class="download-detail-content prose">
            <?= $dl['content'] ?>
        </div>
        <?php endif; ?>

        <?php if ($hasFile): ?>
        <div class="download-cta">
            <div class="download-file-card">
                <div class="download-file-icon">
                    <span class="download-ext-badge download-ext-badge--lg"><?= e($fileExt) ?></span>
                </div>
                <div class="download-file-info">
                    <span class="download-file-name"><?= e($displayName) ?></span>
                    <?php if ($fileSizeHR !== ''): ?>
                    <span class="download-file-size"><?= e($fileSizeHR) ?></span>
                    <?php endif; ?>
                </div>
                <a href="<?= e($fileUrl) ?>" class="btn btn-download" download="<?= e($displayName) ?>">
                    ↓ Download
                </a>
            </div>
        </div>
        <?php endif; ?>

        <div class="download-detail-footer">
            <a href="/download" class="btn-back">← Back to Downloads</a>
        </div>

    </div>
</article>

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