<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));

$error = '';
$success = '';

// 处理下载安装请求 — 使用 PRG 模式防止刷新页面时重复提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'install') {
    require_csrf();
    $installCode = isset($_POST['code']) ? trim((string)$_POST['code']) : '';
    $installType = isset($_POST['pack_type']) ? trim((string)$_POST['pack_type']) : '';
    try {
        $result = install_template_from_cloud($installCode, $installType);
        $_SESSION['market_flash'] = '模板「' . $result['name'] . '」下载安装成功，共 ' . $result['files_count'] . ' 个文件，已归入' . ($result['pack_type'] === 'standard' ? '常规' : '变体') . '模板。';
        $_SESSION['market_flash_type'] = 'success';
    } catch (Exception $e) {
        $_SESSION['market_flash'] = $e->getMessage();
        $_SESSION['market_flash_type'] = 'error';
    }
    header('Location: /admin/template-pack/market.php');
    exit;
}

// 读取 flash 消息
if (isset($_SESSION['market_flash'])) {
    if (isset($_SESSION['market_flash_type']) && $_SESSION['market_flash_type'] === 'error') {
        $error = $_SESSION['market_flash'];
    } else {
        $success = $_SESSION['market_flash'];
    }
    unset($_SESSION['market_flash'], $_SESSION['market_flash_type']);
}

// 获取云端模板列表
$cloudTemplates = array();
$cloudError = '';
try {
    $cloudTemplates = fetch_cloud_template_list();
} catch (Exception $e) {
    $cloudError = $e->getMessage();
}

// 获取本地已安装列表用于对比（code+pack_type 组合键）
$localPacks = list_template_packs();
$localInstalled = array();
foreach ($localPacks as $lp) {
    $c = isset($lp['code']) ? $lp['code'] : '';
    $t = isset($lp['pack_type']) ? $lp['pack_type'] : 'variation';
    if ($c !== '') {
        $key = $c . ':' . $t;
        $localInstalled[$key] = isset($lp['version']) ? $lp['version'] : '0.0.0';
    }
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - 模板市场</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
    <style>
    .market-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px 20px;
        margin-top: 20px;
    }
    .market-card {
        display: flex;
        gap: 16px;
        padding: 20px;
        background: #fff;
        border: 1px solid #dcdcde;
        border-radius: 8px;
        transition: box-shadow 0.15s, border-color 0.15s;
    }
    .market-card:hover {
        border-color: #b4b9be;
        box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    }
    .market-card-thumb {
        flex-shrink: 0;
        width: 80px;
        height: 80px;
        border-radius: 8px;
        background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        cursor: pointer;
    }
    .market-card-thumb img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 8px;
    }
    .market-card-thumb .no-img {
        font-size: 32px;
        opacity: 0.35;
    }
    .market-card-content {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
    }
    .market-card-top {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 8px;
        margin-bottom: 6px;
    }
    .market-card-title {
        font-size: 14px;
        font-weight: 600;
        color: #2271b1;
        margin: 0;
        line-height: 1.4;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .market-card-title:hover {
        color: #135e96;
    }
    .market-card-badge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        font-size: 10px;
        font-weight: 600;
        border-radius: 4px;
        line-height: 1.4;
        white-space: nowrap;
        flex-shrink: 0;
    }
    .market-card-badge.update {
        background: #fef3c7;
        color: #92400e;
    }
    .market-card-badge.new {
        background: #dcfce7;
        color: #166534;
    }
    .market-card-desc {
        font-size: 12px;
        color: #50575e;
        line-height: 1.6;
        margin: 0 0 auto;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        padding-bottom: 10px;
    }
    .market-card-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
        padding-top: 8px;
        border-top: 1px solid #f1f5f9;
    }
    .market-card-meta {
        font-size: 11px;
        color: #787c82;
        display: flex;
        flex-wrap: wrap;
        gap: 4px 12px;
    }
    .market-card-meta .type-badge {
        font-size: 10px;
        font-weight: 500;
        padding: 1px 6px;
        border-radius: 3px;
        white-space: nowrap;
    }
    .type-badge.variation {
        background: #eef2ff;
        color: #4f46e5;
    }
    .type-badge.standard {
        background: #f1f5f9;
        color: #64748b;
    }
    .btn-install {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 12px;
        font-size: 11px;
        font-weight: 500;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.15s;
        text-decoration: none;
        white-space: nowrap;
        flex-shrink: 0;
    }
    .btn-install.available {
        background: #2271b1;
        color: #fff;
    }
    .btn-install.available:hover {
        background: #135e96;
    }
    .btn-install.installed {
        background: #f0fdf4;
        color: #15803d;
        cursor: default;
        border: 1px solid #bbf7d0;
    }
    .btn-install.updatable {
        background: #fef3c7;
        color: #92400e;
        border: 1px solid #fcd34d;
    }
    .btn-install.updatable:hover {
        background: #fde68a;
    }
    .market-empty {
        text-align: center;
        padding: 60px 20px;
        color: #94a3b8;
        grid-column: 1 / -1;
    }
    .market-empty .icon {
        font-size: 48px;
        margin-bottom: 12px;
    }
    .market-filter {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }
    .market-filter .filter-btn {
        padding: 6px 14px;
        font-size: 12px;
        border: 1px solid #dcdcde;
        border-radius: 4px;
        background: #fff;
        color: #50575e;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.15s;
    }
    .market-filter .filter-btn.active,
    .market-filter .filter-btn:hover {
        background: #2271b1;
        color: #fff;
        border-color: #2271b1;
    }
    @media (max-width: 1400px) {
        .market-grid { grid-template-columns: repeat(2, 1fr); }
    }
    @media (max-width: 900px) {
        .market-grid { grid-template-columns: 1fr; }
    }
    /* Update changelog modal */
    .update-modal-overlay {
        display:none; position:fixed; inset:0; z-index:9000;
        background:rgba(15,23,42,0.5); justify-content:center; align-items:center;
        backdrop-filter:blur(2px);
    }
    .update-modal-overlay.is-open { display:flex; }
    .update-modal {
        background:#fff; border-radius:16px; box-shadow:0 12px 40px rgba(0,0,0,0.2);
        width:100%; max-width:480px; max-height:80vh; overflow-y:auto;
        animation:updateModalIn .2s ease;
    }
    @keyframes updateModalIn { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }
    .update-modal-head {
        display:flex; align-items:center; justify-content:space-between;
        padding:20px 24px 0;
    }
    .update-modal-head h3 { margin:0; font-size:16px; color:#0f172a; }
    .update-modal-close {
        background:none; border:none; cursor:pointer; font-size:22px;
        color:#94a3b8; line-height:1; padding:4px;
    }
    .update-modal-close:hover { color:#334155; }
    .update-modal-body { padding:16px 24px 24px; }
    .update-modal-versions {
        display:flex; align-items:center; gap:10px; margin-bottom:16px;
        font-size:13px; color:#64748b;
    }
    .update-modal-versions .ver-old { color:#dc2626; background:#fef2f2; padding:3px 10px; border-radius:6px; font-weight:600; font-size:12px; }
    .update-modal-versions .ver-new { color:#15803d; background:#f0fdf4; padding:3px 10px; border-radius:6px; font-weight:600; font-size:12px; }
    .update-modal-versions .ver-arrow { color:#94a3b8; font-size:16px; }
    .changelog-list {
        background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px;
        padding:14px 18px; margin-bottom:18px; max-height:240px; overflow-y:auto;
    }
    .changelog-list p {
        font-size:13px; color:#334155; margin:0 0 6px; line-height:1.6;
        padding-left:16px; position:relative;
    }
    .changelog-list p::before {
        content:'\2022'; position:absolute; left:0; color:#6366f1; font-weight:700;
    }
    .changelog-list p:last-child { margin-bottom:0; }
    .changelog-empty { font-size:13px; color:#94a3b8; font-style:italic; margin-bottom:18px; }
    .update-modal-actions { display:flex; gap:10px; }
    .update-modal-actions .btn-confirm {
        flex:1; padding:10px; border:none; border-radius:10px;
        background:#4f46e5; color:#fff; font-size:14px; font-weight:600;
        cursor:pointer; transition:all .15s;
    }
    .update-modal-actions .btn-confirm:hover { background:#4338ca; }
    .update-modal-actions .btn-confirm:disabled { opacity:0.6; cursor:not-allowed; }
    .update-modal-actions .btn-cancel-modal {
        padding:10px 20px; border:1px solid #e2e8f0; border-radius:10px;
        background:#fff; color:#64748b; font-size:14px; font-weight:500;
        cursor:pointer; transition:all .15s;
    }
    .update-modal-actions .btn-cancel-modal:hover { background:#f1f5f9; }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('market', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div>
                    <h1>模板市场</h1>
                    <p>从云端浏览和下载模板套件到本地，支持变体模板和常规模板。</p>
                </div>
                <div class="topbar-actions">
                    <a class="btn-ghost" href="/admin/template-pack/list.php">本地模板管理</a>
                </div>
            </header>

            <?php if ($success !== ''): ?>
                <div class="page-card" style="border-left:4px solid #16a34a; margin-bottom:18px;">
                    <div class="card-head"><div><h2 style="color:#16a34a;">下载成功</h2><p><?php echo e($success); ?></p></div></div>
                </div>
            <?php endif; ?>

            <?php if ($error !== ''): ?>
                <div class="page-card" style="border-left:4px solid #dc2626; margin-bottom:18px;">
                    <div class="card-head"><div><h2 style="color:#dc2626;">操作失败</h2><p><?php echo e($error); ?></p></div></div>
                </div>
            <?php endif; ?>

            <section class="page-card">
                <div class="card-head">
                    <div>
                        <h2>云端模板</h2>
                        <p>共 <?php echo count($cloudTemplates); ?> 个可用模板</p>
                    </div>
                    <div class="market-filter">
                        <a class="filter-btn active" href="#" onclick="filterMarket('all');return false;">全部</a>
                        <a class="filter-btn" href="#" onclick="filterMarket('variation');return false;">变体</a>
                        <a class="filter-btn" href="#" onclick="filterMarket('standard');return false;">常规</a>
                        <a class="filter-btn" href="#" onclick="filterMarket('not-installed');return false;">未安装</a>
                        <a class="filter-btn" href="#" onclick="filterMarket('has-update');return false;">🔄 有更新</a>
                    </div>
                </div>

                <?php if ($cloudError !== ''): ?>
                    <div class="market-empty">
                        <div class="icon">⚠️</div>
                        <p style="color:#dc2626;"><?php echo e($cloudError); ?></p>
                        <p style="font-size:12px;">请确认 cloud.beeai.chat 可正常访问，或稍后重试。</p>
                    </div>
                <?php elseif (empty($cloudTemplates)): ?>
                    <div class="market-empty">
                        <div class="icon">📦</div>
                        <p>云端暂无可用模板</p>
                    </div>
                <?php else: ?>
                    <div class="market-grid" id="marketGrid">
                        <?php foreach ($cloudTemplates as $ct):
                            $ctCode = isset($ct['code']) ? $ct['code'] : '';
                            $ctName = isset($ct['name']) ? $ct['name'] : $ctCode;
                            $ctType = isset($ct['pack_type']) ? $ct['pack_type'] : 'variation';
                            $ctDesc = isset($ct['description']) ? $ct['description'] : '';
                            $ctVersion = isset($ct['version']) ? $ct['version'] : '1.0.0';
                            $ctAuthor = isset($ct['author']) ? $ct['author'] : '';
                            $ctScreenshot = isset($ct['screenshot']) ? $ct['screenshot'] : '';
                            $ctSize = isset($ct['file_size']) ? $ct['file_size'] : 0;
                            $ctKey = $ctCode . ':' . $ctType;
                            $isInstalled = isset($localInstalled[$ctKey]);
                            $localVer = $isInstalled ? $localInstalled[$ctKey] : '';
                            $isUpdatable = $isInstalled && version_compare($ctVersion, $localVer, '>');
                        ?>
                        <div class="market-card" data-type="<?php echo e($ctType); ?>" data-installed="<?php echo $isInstalled ? '1' : '0'; ?>" data-updatable="<?php echo $isUpdatable ? '1' : '0'; ?>">
                            <div class="market-card-thumb" <?php if ($ctScreenshot !== ''): ?>onclick="previewImg(this.querySelector('img'))"<?php endif; ?>>
                                <?php if ($ctScreenshot !== ''): ?>
                                    <img src="<?php echo e($ctScreenshot); ?>" alt="<?php echo e($ctName); ?>" onerror="this.outerHTML='<div class=no-img>📄</div>';">
                                <?php else: ?>
                                    <div class="no-img">📄</div>
                                <?php endif; ?>
                            </div>
                            <div class="market-card-content">
                                <div class="market-card-top">
                                    <h3 class="market-card-title"><?php echo e($ctName); ?></h3>
                                    <?php if ($isUpdatable):
                                        $ctChangelog = isset($ct['changelog']) ? trim((string)$ct['changelog']) : '';
                                    ?>
                                        <button type="button" class="btn-install updatable" onclick="showUpdateModal('<?php echo e($ctCode); ?>','<?php echo e($ctType); ?>','<?php echo e($ctName); ?>','<?php echo e($localVer); ?>','<?php echo e($ctVersion); ?>',<?php echo e(json_encode($ctChangelog)); ?>)">更新</button>
                                    <?php elseif ($isInstalled): ?>
                                        <span class="btn-install installed">已安装</span>
                                    <?php else: ?>
                                        <form method="post" style="margin:0;" onsubmit="this.querySelector('button').disabled=true;this.querySelector('button').textContent='…';">
                                            <?php echo csrf_field(); ?>
                                            <input type="hidden" name="action" value="install">
                                            <input type="hidden" name="code" value="<?php echo e($ctCode); ?>">
                                            <input type="hidden" name="pack_type" value="<?php echo e($ctType); ?>">
                                            <button type="submit" class="btn-install available">安装</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                                <p class="market-card-desc"><?php echo e($ctDesc); ?></p>
                                <div class="market-card-footer">
                                    <div class="market-card-meta">
                                        <span class="type-badge <?php echo e($ctType); ?>"><?php echo $ctType === 'standard' ? '常规' : '变体'; ?></span>
                                        <?php if ($ctAuthor !== ''): ?><span>作者: <?php echo e($ctAuthor); ?></span><?php endif; ?>
                                        <span>v<?php echo e($isInstalled && $localVer !== '' ? $localVer : $ctVersion); ?></span>
                                        <?php $ctDate = isset($ct['updated_at']) ? trim((string)$ct['updated_at']) : ''; if ($ctDate !== ''): ?><span>更新: <?php echo e($ctDate); ?></span><?php endif; ?>
                                        <?php if ($ctSize > 0): ?><span><?php echo round($ctSize / 1024, 0); ?>KB</span><?php endif; ?>
                                    </div>
                                    <?php if ($isUpdatable): ?>
                                        <span class="market-card-badge update">有新版</span>
                                    <?php elseif (!$isInstalled && isset($ct['updated_at']) && $ct['updated_at'] !== '' && strtotime($ct['updated_at']) >= strtotime('-7 days')): ?>
                                        <span class="market-card-badge new">新上架</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
function previewImg(img) {
    var overlay = document.getElementById('imgOverlay');
    var full = document.getElementById('imgFull');
    var caption = document.getElementById('imgCaption');
    full.src = img.src;
    caption.textContent = img.alt || '';
    overlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}
function closePreview() {
    document.getElementById('imgOverlay').style.display = 'none';
    document.body.style.overflow = '';
}
function filterMarket(type) {
    var cards = document.querySelectorAll('.market-card');
    var btns = document.querySelectorAll('.market-filter .filter-btn');
    btns.forEach(function(b) { b.classList.remove('active'); });
    event.target.classList.add('active');
    cards.forEach(function(card) {
        var cardType = card.getAttribute('data-type');
        var cardInstalled = card.getAttribute('data-installed');
        var show = true;
        if (type === 'variation') show = cardType === 'variation';
        else if (type === 'standard') show = cardType === 'standard';
        else if (type === 'not-installed') show = cardInstalled === '0';
        else if (type === 'has-update') show = card.getAttribute('data-updatable') === '1';
        card.style.display = show ? '' : 'none';
    });
}
</script>
<!-- Update Changelog Modal -->
<div class="update-modal-overlay" id="updateModal">
    <div class="update-modal">
        <div class="update-modal-head">
            <h3 id="umTitle">更新模板</h3>
            <button type="button" class="update-modal-close" onclick="closeUpdateModal()">&times;</button>
        </div>
        <div class="update-modal-body">
            <div class="update-modal-versions">
                <span class="ver-old" id="umOldVer">v1.0.0</span>
                <span class="ver-arrow">→</span>
                <span class="ver-new" id="umNewVer">v1.0.1</span>
            </div>
            <div id="umChangelogWrap"></div>
            <form method="post" id="umForm" style="margin:0;">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="install">
                <input type="hidden" name="code" id="umCode" value="">
                <input type="hidden" name="pack_type" id="umType" value="">
                <div class="update-modal-actions">
                    <button type="button" class="btn-cancel-modal" onclick="closeUpdateModal()">取消</button>
                    <button type="submit" class="btn-confirm" id="umConfirmBtn">确认更新</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script>
function showUpdateModal(code, type, name, oldVer, newVer, changelog) {
    document.getElementById('umTitle').textContent = '更新「' + name + '」';
    document.getElementById('umOldVer').textContent = 'v' + oldVer;
    document.getElementById('umNewVer').textContent = 'v' + newVer;
    document.getElementById('umCode').value = code;
    document.getElementById('umType').value = type;
    var wrap = document.getElementById('umChangelogWrap');
    if (changelog && changelog.trim() !== '') {
        var lines = changelog.trim().split('\n');
        var html = '<div class="changelog-list">';
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].trim();
            if (line !== '') {
                html += '<p>' + line.replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</p>';
            }
        }
        html += '</div>';
        wrap.innerHTML = html;
    } else {
        wrap.innerHTML = '<div class="changelog-empty">暂无更新记录</div>';
    }
    document.getElementById('umConfirmBtn').disabled = false;
    document.getElementById('umConfirmBtn').textContent = '确认更新';
    document.getElementById('updateModal').classList.add('is-open');
}
function closeUpdateModal() {
    document.getElementById('updateModal').classList.remove('is-open');
}
document.getElementById('updateModal').addEventListener('click', function(e) {
    if (e.target === this) closeUpdateModal();
});
document.getElementById('umForm').addEventListener('submit', function() {
    var btn = document.getElementById('umConfirmBtn');
    btn.disabled = true;
    btn.textContent = '更新中…';
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && document.getElementById('updateModal').classList.contains('is-open')) {
        closeUpdateModal();
    }
});
</script>
<div id="imgOverlay" onclick="closePreview()" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.85);justify-content:center;align-items:center;flex-direction:column;cursor:zoom-out;">
    <img id="imgFull" src="" alt="" style="max-width:92vw;max-height:85vh;border-radius:8px;box-shadow:0 8px 40px rgba(0,0,0,.5);object-fit:contain;" onclick="event.stopPropagation();">
    <p id="imgCaption" style="color:#fff;margin-top:12px;font-size:14px;text-align:center;"></p>
    <span style="position:absolute;top:18px;right:24px;color:#fff;font-size:32px;cursor:pointer;line-height:1;" onclick="closePreview()">&times;</span>
</div>
</body>
</html>
