<?php
$isConnected = !empty($marketplaceConfigured);
$rate = (float)($creditRate ?? 0.01);
?>

<?php include __DIR__ . '/_mp_modal.php'; ?>


<div class="mb-4">
    <div class="relative">
        <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
        <input type="text" id="themeSearch" placeholder="Search themes..." class="w-full sm:w-64 pl-10 pr-4 py-1.5 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-500 bg-white outline-none" autocomplete="off">
    </div>
</div>

<?php if (!empty($marketplaceError)): ?>
    <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-4 text-sm text-red-700">
        <?= htmlspecialchars($marketplaceError) ?>
    </div>
<?php endif; ?>


<?php if (!empty($themes)): ?>
<div id="themesInstalled" class="mb-6">
    <h2 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-2">Installed</h2>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="overflow-x-auto">
            <table class="w-full" id="themesInstalledTable">
                <thead>
                    <tr class="bg-gray-50">
                        <th class="px-4 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Theme</th>
                        <th class="px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hide-mobile">Version</th>
                        <th class="px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hide-mobile">Author</th>
                        <th class="px-3 py-2 text-center text-[11px] font-semibold uppercase tracking-wider text-gray-500">Status</th>
                        <th class="px-3 py-2 text-right text-[11px] font-semibold uppercase tracking-wider text-gray-500">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($themes as $theme): ?>
                        <?php
                        $slug = htmlspecialchars($theme['slug'] ?? '');
                        $shotExt = file_exists(APP_ROOT . '/themes/' . $theme['slug'] . '/screenshot.webp') ? 'webp' : (file_exists(APP_ROOT . '/themes/' . $theme['slug'] . '/screenshot.png') ? 'png' : '');
                        $hasScreenshot = $shotExt !== '';
                        $screenshotUrl = $hasScreenshot ? '/themes/' . $slug . '/screenshot.' . $shotExt : '';
                        $isActive = !empty($theme['is_active']);
                        ?>
                        <tr class="theme-row hover:bg-gray-50 transition-colors"
                            data-name="<?= htmlspecialchars(strtolower($theme['name'])) ?>"
                            data-desc="<?= htmlspecialchars(strtolower($theme['description'] ?? '')) ?>">
                            <td class="px-4 py-2.5">
                                <div class="flex items-center gap-3 min-w-0">
                                    <?php if ($hasScreenshot): ?>
                                        <img src="<?= $screenshotUrl ?>" alt="<?= htmlspecialchars($theme['name']) ?>" class="w-16 h-9 rounded object-cover shrink-0 border border-gray-200">
                                    <?php else: ?>
                                        <div class="w-16 h-9 rounded bg-gray-100 flex items-center justify-center shrink-0 border border-gray-200">
                                            <svg class="w-4 h-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                                        </div>
                                    <?php endif; ?>
                                    <div class="min-w-0">
                                        <button type="button" onclick="document.getElementById('modal-<?= $slug ?>').classList.remove('hidden')" class="text-sm font-medium text-gray-900 hover:text-primary-600 truncate block text-left transition-colors">
                                            <?= htmlspecialchars($theme['name']) ?>
                                        </button>
                                        <p class="text-[11px] text-gray-400 truncate max-w-xs"><?= htmlspecialchars(mb_strimwidth($theme['description'] ?? 'No description.', 0, 80, '...')) ?></p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-3 py-2.5 text-xs text-gray-500 hide-mobile">
                                <?php if (!empty($theme['version'])): ?>v<?= htmlspecialchars($theme['version']) ?><?php endif; ?>
                                <?php if (!empty($theme['mp_has_update'])): ?>
                                    <span class="inline-flex items-center ml-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-orange-100 text-orange-700">
                                        &rarr; v<?= htmlspecialchars($theme['mp_latest_version']) ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-2.5 text-xs text-gray-400 hide-mobile"><?= htmlspecialchars($theme['author'] ?? '') ?></td>
                            <td class="px-3 py-2.5 text-center">
                                <?php if ($isActive): ?>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-800">Active</span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium bg-gray-100 text-gray-600">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-3 py-2.5 text-right">
                                <div class="flex items-center justify-end gap-1">
                                    <button type="button" onclick="document.getElementById('modal-<?= $slug ?>').classList.remove('hidden')"
                                            class="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-medium text-indigo-700 bg-indigo-50 hover:bg-indigo-100 border border-indigo-200 rounded-lg transition-colors">
                                        <svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                        Details
                                    </button>
                                    <?php if ($isActive): ?>
                                        <a href="/admin/appearance" class="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-medium text-primary-700 bg-primary-50 hover:bg-primary-100 border border-primary-200 rounded-lg transition-colors no-underline" title="Customize">
                                            <svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"/></svg>
                                            Customize
                                        </a>
                                    <?php else: ?>
                                        <form method="POST" action="/admin/themes/<?= $slug ?>/activate" class="inline">
                                            <?= Router::csrfField() ?>
                                            <button type="submit" class="inline-flex items-center gap-1 px-2.5 py-1 text-[11px] font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors">Activate</button>
                                        </form>
                                        <form method="POST" action="/admin/themes/<?= $slug ?>/uninstall" onsubmit="return confirm('Uninstall this theme? All theme files will be deleted.')" class="inline">
                                            <?= Router::csrfField() ?>
                                            <button type="submit" class="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors" title="Uninstall">
                                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    <form method="POST" action="/admin/themes/<?= $slug ?>/reset" onsubmit="return confirm('Reset all settings, translations and customizations for this theme?\n\nThis action cannot be undone.')" class="inline">
                                        <?= Router::csrfField() ?>
                                        <button type="submit" class="p-1.5 text-gray-400 hover:text-orange-600 hover:bg-orange-50 rounded transition-colors" title="Reset theme data">
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>


<?php foreach ($themes as $theme): ?>
    <?php
    $slug = htmlspecialchars($theme['slug'] ?? '');
    $_author = $theme['mp_author'] ?? $theme['author'] ?? '';
    $_longDesc = $theme['mp_long_description'] ?? $theme['long_description'] ?? '';
    $_shortDesc = $theme['mp_description'] ?? $theme['description'] ?? 'No description.';
    $_features = $theme['mp_features'] ?? $theme['features'] ?? [];
    if (is_string($_features)) $_features = json_decode($_features, true) ?: [];
    $_downloads = (int)($theme['mp_download_count'] ?? 0);
    $_requires = $theme['mp_requires_cms'] ?? $theme['requires'] ?? '';
    $_screenshot = $theme['mp_screenshot_url'] ?? '';
    if ($_screenshot === '') {
        foreach (['webp', 'png'] as $_ext) {
            if (file_exists(APP_ROOT . '/themes/' . $theme['slug'] . '/screenshot.' . $_ext)) { $_screenshot = '/themes/' . $slug . '/screenshot.' . $_ext; break; }
        }
    }
    $isActive = !empty($theme['is_active']);
    ?>
    <div id="modal-<?= $slug ?>" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)this.classList.add('hidden')">
        <div class="fixed inset-0 bg-black/50"></div>
        <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[80vh] sm:max-h-[85vh] flex flex-col overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
                <div class="flex items-center gap-3">
                    <h2 class="text-lg font-semibold text-gray-900"><?= htmlspecialchars($theme['name']) ?></h2>
                    <?php if (!empty($theme['version'])): ?>
                        <span class="text-xs text-gray-400">v<?= htmlspecialchars($theme['version']) ?></span>
                    <?php endif; ?>
                    <?php if ($isActive): ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">Active</span>
                    <?php else: ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">Inactive</span>
                    <?php endif; ?>
                </div>
                <button type="button" onclick="this.closest('[id^=modal-]').classList.add('hidden')"
                        class="text-gray-400 hover:text-gray-600 transition-colors">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div class="px-6 py-5 overflow-y-auto flex-1">
                <p class="text-xs text-gray-400 mb-4">
                    <?php if ($_author !== ''): ?>By <?= htmlspecialchars($_author) ?><?php endif; ?>
                    <?php if ($_downloads > 0): ?> &middot; <?= number_format($_downloads) ?> downloads<?php endif; ?>
                    <?php if ($_requires !== ''): ?> &middot; Requires TubePress <?= htmlspecialchars($_requires) ?>+<?php endif; ?>
                </p>
                <?php if ($_screenshot !== ''): ?>
                    <img src="<?= htmlspecialchars($_screenshot) ?>" alt="<?= htmlspecialchars($theme['name']) ?>" class="w-full rounded-lg border border-gray-200 mb-5">
                <?php endif; ?>
                <?php if ($_longDesc !== ''): ?>
                    <div class="prose prose-sm text-gray-700 mb-6">
                        <?php foreach (preg_split('/\R{2,}/', $_longDesc) as $para): ?>
                            <p class="mb-3 last:mb-0"><?= htmlspecialchars(trim($para)) ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="text-sm text-gray-600 mb-6"><?= htmlspecialchars($_shortDesc) ?></p>
                <?php endif; ?>
                <?php if (!empty($_features)): ?>
                    <h3 class="text-sm font-semibold text-gray-900 mb-3 uppercase tracking-wide">Features</h3>
                    <div class="space-y-3">
                        <?php foreach ($_features as $feature): ?>
                            <div class="bg-gray-50 rounded-lg p-4 flex gap-3.5 items-start">
                                <div class="flex-shrink-0 w-8 h-8 rounded-lg bg-primary-100 text-primary-600 flex items-center justify-center mt-0.5">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                                </div>
                                <div class="min-w-0">
                                    <h4 class="text-sm font-medium text-gray-900 mb-1"><?= htmlspecialchars($feature['title'] ?? '') ?></h4>
                                    <p class="text-sm text-gray-600"><?= htmlspecialchars($feature['description'] ?? '') ?></p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end items-center gap-2 flex-shrink-0 bg-gray-50">
                <button type="button" onclick="this.closest('[id^=modal-]').classList.add('hidden')"
                        class="px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Close</button>
            </div>
        </div>
    </div>
<?php endforeach; ?>
<?php endif; ?>


<?php if (!empty($available)): ?>
<div id="themesAvailable">
    <h2 class="text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-3">Marketplace</h2>
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" id="themesAvailableGrid">
        <?php foreach ($available as $mp): ?>
            <?php
            $mpSlug = htmlspecialchars($mp['slug'] ?? '');
            $isFree = !empty($mp['is_free']);
            $isOwned = !empty($mp['owned']);
            $price = (float)($mp['price_credits'] ?? 0);
            $priceUsd = $price * $rate;
            $mpFeaturesList = $mp['features'] ?? [];
            if (is_string($mpFeaturesList)) $mpFeaturesList = json_decode($mpFeaturesList, true) ?: [];
            $featureCount = count($mpFeaturesList);
            ?>
            <div class="theme-row bg-white rounded-xl border border-gray-200 shadow-sm hover:shadow-md hover:border-gray-300 transition-all duration-200 flex flex-col overflow-hidden"
                 data-name="<?= htmlspecialchars(strtolower($mp['name'] ?? '')) ?>"
                 data-desc="<?= htmlspecialchars(strtolower($mp['description'] ?? '')) ?>">
                
                <button type="button" onclick="document.getElementById('mp-modal-<?= $mpSlug ?>').classList.remove('hidden')" class="block w-full aspect-video bg-gray-100 relative group">
                    <?php if (!empty($mp['screenshot_url'])): ?>
                        <img src="<?= htmlspecialchars($mp['screenshot_url']) ?>" alt="<?= htmlspecialchars($mp['name'] ?? '') ?>" class="w-full h-full object-cover">
                    <?php else: ?>
                        <div class="w-full h-full flex items-center justify-center">
                            <svg class="w-8 h-8 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                        </div>
                    <?php endif; ?>
                    <div class="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors flex items-center justify-center">
                        <span class="text-white text-xs font-medium bg-black/60 px-3 py-1.5 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity">Preview</span>
                    </div>
                    
                    <div class="absolute top-2.5 right-2.5">
                        <?php if ($isFree): ?>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-[11px] font-bold bg-green-50/95 text-green-700 border border-green-200 shadow-sm backdrop-blur-sm">Free</span>
                        <?php elseif ($isOwned): ?>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-[11px] font-bold bg-blue-50/95 text-blue-700 border border-blue-200 shadow-sm backdrop-blur-sm">Owned</span>
                        <?php else: ?>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-lg text-[11px] font-bold bg-amber-50/95 text-amber-700 border border-amber-200 shadow-sm backdrop-blur-sm">$<?= number_format($priceUsd, 2) ?></span>
                        <?php endif; ?>
                    </div>
                </button>
                
                <div class="p-4 flex-1">
                    <div class="flex items-center gap-2 mb-1.5">
                        <button type="button" onclick="document.getElementById('mp-modal-<?= $mpSlug ?>').classList.remove('hidden')"
                                class="text-sm font-semibold text-gray-900 hover:text-primary-600 transition-colors truncate text-left">
                            <?= htmlspecialchars($mp['name'] ?? '') ?>
                        </button>
                    </div>
                    <p class="text-[11px] text-gray-400 mb-2.5">
                        By <?= htmlspecialchars($mp['author'] ?? 'Unknown') ?>
                        <?php if (!empty($mp['latest_version'])): ?>&middot; v<?= htmlspecialchars($mp['latest_version']) ?><?php endif; ?>
                    </p>
                    <p class="text-[13px] text-gray-600 leading-relaxed line-clamp-3"><?= htmlspecialchars($mp['description'] ?? 'No description.') ?></p>
                    <?php if ($featureCount > 0): ?>
                        <p class="mt-2.5 text-[11px] text-gray-400 flex items-center gap-1">
                            <svg class="w-3.5 h-3.5 text-green-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                            <?= $featureCount ?> feature<?= $featureCount > 1 ? 's' : '' ?> included
                        </p>
                    <?php endif; ?>
                </div>
                
                <div class="px-4 py-3 border-t border-gray-100 flex items-center justify-between gap-2 bg-gray-50/50 rounded-b-xl">
                    <button type="button" onclick="document.getElementById('mp-modal-<?= $mpSlug ?>').classList.remove('hidden')"
                            class="text-[12px] font-medium text-gray-500 hover:text-primary-600 transition-colors">
                        View details &rarr;
                    </button>
                    <?php if ($isFree || $isOwned): ?>
                        <form method="POST" action="/admin/themes/<?= $mpSlug ?>/install" class="inline">
                            <?= Router::csrfField() ?>
                            <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 text-[12px] font-semibold text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors shadow-sm">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                                Install
                            </button>
                        </form>
                    <?php elseif ($isConnected): ?>
                        <button type="button" onclick="MP.openPurchaseModal('<?= $mpSlug ?>', 'theme', '<?= htmlspecialchars($mp['name'] ?? '', ENT_QUOTES) ?>')"
                                class="inline-flex items-center gap-1.5 px-4 py-2 text-[12px] font-semibold text-white bg-amber-500 hover:bg-amber-600 rounded-lg transition-colors shadow-sm">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 100 4 2 2 0 000-4z"/></svg>
                            Get
                        </button>
                    <?php else: ?>
                        <button type="button" onclick="MP.autoConnect()"
                                class="inline-flex items-center gap-1.5 px-4 py-2 text-[12px] font-semibold text-white bg-amber-500 hover:bg-amber-600 rounded-lg transition-colors shadow-sm"
                                title="Connect your account to purchase this theme">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                            Connect &amp; Get
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>


<?php foreach ($available as $mp): ?>
    <?php
    $mpSlug = htmlspecialchars($mp['slug'] ?? '');
    $isFree = !empty($mp['is_free']);
    $isOwned = !empty($mp['owned']);
    $mpPrice = (float)($mp['price_credits'] ?? 0);
    $mpPriceUsd = $mpPrice * $rate;
    $mpFeatures = $mp['features'] ?? [];
    if (is_string($mpFeatures)) $mpFeatures = json_decode($mpFeatures, true) ?: [];
    $mpLongDesc = $mp['long_description'] ?? '';
    $mpShortDesc = $mp['description'] ?? 'No description.';
    ?>
    <div id="mp-modal-<?= $mpSlug ?>" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" onclick="if(event.target===this)this.classList.add('hidden')">
        <div class="fixed inset-0 bg-black/50"></div>
        <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[80vh] sm:max-h-[85vh] flex flex-col overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between flex-shrink-0">
                <div class="flex items-center gap-3">
                    <h2 class="text-lg font-semibold text-gray-900"><?= htmlspecialchars($mp['name'] ?? '') ?></h2>
                    <?php if (!empty($mp['latest_version'])): ?>
                        <span class="text-xs text-gray-400">v<?= htmlspecialchars($mp['latest_version']) ?></span>
                    <?php endif; ?>
                    <?php if ($isFree): ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-700">Free</span>
                    <?php elseif ($isOwned): ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium bg-blue-100 text-blue-700">Owned</span>
                    <?php else: ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium bg-amber-100 text-amber-700">$<?= number_format($mpPriceUsd, 2) ?></span>
                    <?php endif; ?>
                </div>
                <button type="button" onclick="this.closest('[id^=mp-modal-]').classList.add('hidden')"
                        class="text-gray-400 hover:text-gray-600 transition-colors">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div class="px-6 py-5 overflow-y-auto flex-1">
                <p class="text-xs text-gray-400 mb-4">
                    <?php if (!empty($mp['author'])): ?>By <?= htmlspecialchars($mp['author']) ?><?php endif; ?>
                    <?php if (!empty($mp['download_count'])): ?> &middot; <?= number_format((int)$mp['download_count']) ?> downloads<?php endif; ?>
                    <?php if (!empty($mp['requires_cms'])): ?> &middot; Requires TubePress <?= htmlspecialchars($mp['requires_cms']) ?>+<?php endif; ?>
                </p>
                <?php if (!empty($mp['screenshot_url'])): ?>
                    <img src="<?= htmlspecialchars($mp['screenshot_url']) ?>" alt="<?= htmlspecialchars($mp['name'] ?? '') ?>" class="w-full rounded-lg border border-gray-200 mb-5">
                <?php endif; ?>
                <?php if ($mpLongDesc !== ''): ?>
                    <div class="prose prose-sm text-gray-700 mb-6">
                        <?php foreach (preg_split('/\R{2,}/', $mpLongDesc) as $para): ?>
                            <p class="mb-3 last:mb-0"><?= htmlspecialchars(trim($para)) ?></p>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <p class="text-sm text-gray-600 mb-6"><?= htmlspecialchars($mpShortDesc) ?></p>
                <?php endif; ?>
                <?php if (!empty($mpFeatures)): ?>
                    <h3 class="text-sm font-semibold text-gray-900 mb-3 uppercase tracking-wide">Features</h3>
                    <div class="space-y-3">
                        <?php foreach ($mpFeatures as $feature): ?>
                            <div class="bg-gray-50 rounded-lg p-4 flex gap-3.5 items-start">
                                <div class="flex-shrink-0 w-8 h-8 rounded-lg bg-primary-100 text-primary-600 flex items-center justify-center mt-0.5">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg>
                                </div>
                                <div class="min-w-0">
                                    <h4 class="text-sm font-medium text-gray-900 mb-1"><?= htmlspecialchars($feature['title'] ?? '') ?></h4>
                                    <p class="text-sm text-gray-600"><?= htmlspecialchars($feature['description'] ?? '') ?></p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-between items-center flex-shrink-0 bg-gray-50">
                <div>
                    <?php if (!$isFree && !$isOwned): ?>
                        <span class="text-sm font-semibold text-gray-900">$<?= number_format($mpPriceUsd, 2) ?></span>
                    <?php endif; ?>
                </div>
                <div class="flex items-center gap-2">
                    <button type="button" onclick="this.closest('[id^=mp-modal-]').classList.add('hidden')"
                            class="px-4 py-2 bg-white text-gray-700 text-sm font-medium rounded-lg border border-gray-300 hover:bg-gray-50">Close</button>
                    <?php if ($isFree || $isOwned): ?>
                        <form method="POST" action="/admin/themes/<?= $mpSlug ?>/install" class="inline">
                            <?= Router::csrfField() ?>
                            <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
                                Install
                            </button>
                        </form>
                    <?php elseif ($isConnected): ?>
                        <button type="button" onclick="this.closest('[id^=mp-modal-]').classList.add('hidden'); MP.openPurchaseModal('<?= $mpSlug ?>', 'theme', '<?= htmlspecialchars($mp['name'] ?? '', ENT_QUOTES) ?>')"
                                class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-amber-500 hover:bg-amber-600 rounded-lg transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 100 4 2 2 0 000-4z"/></svg>
                            Get
                        </button>
                    <?php else: ?>
                        <button type="button" onclick="this.closest('[id^=mp-modal-]').classList.add('hidden'); MP.autoConnect()"
                                class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-amber-500 hover:bg-amber-600 rounded-lg transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                            Connect &amp; Get
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<?php elseif (!$isConnected): ?>
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
    <p class="text-gray-500 text-sm mb-3">Connect to the marketplace to browse more themes.</p>
    <button type="button" onclick="MP.autoConnect()" class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-semibold text-white bg-primary-600 hover:bg-primary-700 rounded-lg transition-colors">Connect</button>
</div>
<?php endif; ?>

<?php if (empty($themes) && empty($available)): ?>
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
    <p class="text-gray-500 text-sm">No themes available.</p>
</div>
<?php endif; ?>


<div id="themesNoResults" class="hidden bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
    <p class="text-gray-500 text-sm">No themes match your search.</p>
</div>

<script>
document.getElementById('themeSearch').addEventListener('input', function() {
    var q = this.value.toLowerCase().trim();
    var rows = document.querySelectorAll('.theme-row');
    var visibleInstalled = 0, visibleAvailable = 0;

    rows.forEach(function(row) {
        var name = row.dataset.name || '';
        var desc = row.dataset.desc || '';
        var match = !q || name.includes(q) || desc.includes(q);
        row.style.display = match ? '' : 'none';
        if (match) {
            if (row.closest('#themesInstalled')) visibleInstalled++;
            else if (row.closest('#themesAvailable')) visibleAvailable++;
        }
    });

    var installedSection = document.getElementById('themesInstalled');
    var availableSection = document.getElementById('themesAvailable');
    if (installedSection) installedSection.style.display = visibleInstalled > 0 ? '' : 'none';
    if (availableSection) availableSection.style.display = visibleAvailable > 0 ? '' : 'none';

    document.getElementById('themesNoResults').classList.toggle('hidden', visibleInstalled + visibleAvailable > 0);
});
</script>
