<?php
/**
 * CloudForge Theme - 模板中心（带分类筛选）
 */
$pageDescription = '模板中心 - 选择适合您行业的网站模板';
$breadcrumbItems = [['title' => '模板中心']];

$themeColors = [
    'default' => '#6366F1', 'tech-blue' => '#3B82F6', 'minimal-white' => '#94A3B8',
    'vibrant-orange' => '#F97316', 'deep-purple' => '#8B5CF6', 'nature-green' => '#10B981',
    'dark-mode' => '#1E293B', 'gradient-modern' => '#EC4899', 'corporate-elegant' => '#1E40AF',
    'creative-portfolio' => '#F43F5E', 'cloud-forge' => '#22D3EE',
];
$layoutLabels = ['grid' => '网格', 'list' => '列表', 'masonry' => '瀑布流', 'sidebar' => '侧边栏', 'fullwidth' => '全宽'];

// 收集所有模板
$allTemplates = [];

// 1. 精选主题
$featured = db_query("SELECT * FROM `themes` WHERE `id` <= 10 ORDER BY `is_active` DESC, `id` ASC");
foreach ($featured as $t) {
    $color = $themeColors[$t['slug']] ?? '#6366F1';
    $allTemplates[] = [
        'slug' => $t['slug'], 'name' => $t['name'], 'desc' => $t['description'],
        'color' => $color, 'category' => '精选', 'layout' => 'grid',
        'is_active' => $t['is_active'], 'group' => 'featured',
    ];
}
// 加上 cloud-forge 自身
$allTemplates[] = [
    'slug' => 'cloud-forge', 'name' => 'CloudForge', 'desc' => '暗夜精密工业风主题',
    'color' => '#22D3EE', 'category' => '科技', 'layout' => 'fullwidth',
    'is_active' => true, 'group' => 'featured',
];

// 2. 行业模板（扫描目录）
$templatesDir = __DIR__ . '/../../templates/';
if (is_dir($templatesDir)) {
    $knownSlugs = array_column($allTemplates, 'slug');
    $dirs = glob($templatesDir . '*', GLOB_ONLYDIR);
    foreach ($dirs as $dir) {
        $slug = basename($dir);
        if (in_array($slug, $knownSlugs)) continue;
        $infoFile = $dir . '/theme.json';
        if (file_exists($infoFile)) {
            $info = json_decode(file_get_contents($infoFile), true);
            if ($info && isset($info['industry'])) {
                $color = $info['colors']['primary'] ?? '#6366F1';
                $allTemplates[] = [
                    'slug' => $slug, 'name' => $info['name'] ?? $slug,
                    'desc' => $info['description'] ?? '',
                    'color' => $color, 'category' => $info['industry'],
                    'layout' => $info['layout'] ?? 'grid',
                    'is_active' => false, 'group' => 'industry',
                ];
            }
        }
    }
}

// 提取分类列表
$categories = [];
foreach ($allTemplates as $tmpl) {
    $cat = $tmpl['category'];
    if (!isset($categories[$cat])) $categories[$cat] = 0;
    $categories[$cat]++;
}
// 排序：精选优先，其他按数量降序
$categoryOrder = ['精选', '企业', '科技', '餐饮', '教育', '医疗', '电商', '酒店',
    '设计', '金融', '建筑', '汽车', '旅游', '宠物', '婚庆', '美容', '摄影'];
uksort($categories, function($a, $b) use ($categoryOrder) {
    $ia = array_search($a, $categoryOrder); if ($ia === false) $ia = 999;
    $ib = array_search($b, $categoryOrder); if ($ib === false) $ib = 999;
    return $ia - $ib;
});
?>
<?php echo breadcrumb($breadcrumbItems); ?>

<div class="main-content">
    <div class="container">

        <div class="section-header section-header--center">
            <span class="section-label">// TEMPLATES</span>
            <h2 class="section-title">模板中心</h2>
            <p class="section-subtitle">共 <?php echo count($allTemplates); ?> 套模板 · 按行业分类筛选</p>
        </div>

        <!-- 分类筛选标签 -->
        <div id="filterBar" style="display:flex;flex-wrap:wrap;gap:var(--sp-2);justify-content:center;margin-bottom:var(--sp-8);padding:var(--sp-4);background:var(--bg-surface-2);border:1px solid var(--border-subtle);border-radius:var(--r-lg);">
            <button class="filter-btn is-active" data-cat="全部" onclick="filterTemplates('全部', this)"
                    style="padding:var(--sp-2) var(--sp-4);border:1px solid var(--border-default);border-radius:var(--r-full);background:transparent;font-family:var(--font-mono);font-size:var(--fs-xs);color:var(--text-secondary);cursor:pointer;transition:all var(--dur-fast);">
                全部 <span style="color:var(--text-muted);"><?php echo count($allTemplates); ?></span>
            </button>
            <?php foreach ($categories as $cat => $count): ?>
            <button class="filter-btn" data-cat="<?php echo $cat; ?>" onclick="filterTemplates('<?php echo $cat; ?>', this)"
                    style="padding:var(--sp-2) var(--sp-4);border:1px solid var(--border-default);border-radius:var(--r-full);background:transparent;font-family:var(--font-mono);font-size:var(--fs-xs);color:var(--text-secondary);cursor:pointer;transition:all var(--dur-fast);">
                <?php echo $cat; ?> <span style="color:var(--text-muted);"><?php echo $count; ?></span>
            </button>
            <?php endforeach; ?>
        </div>

        <!-- 模板网格 -->
        <div id="templateGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:var(--sp-5);">
            <?php foreach ($allTemplates as $idx => $t):
                $accentColor = $t['color'];
                $cat = $t['category'];
            ?>
            <div class="template-card" data-category="<?php echo $cat; ?>"
                 style="background:var(--bg-surface-1);border:1px solid var(--border-default);border-radius:var(--r-md);overflow:hidden;transition:all var(--dur-normal) var(--ease-out-quart);opacity:1;">
                <!-- 缩略图区 -->
                <a href="/?preview_theme=<?php echo $t['slug']; ?>" target="_blank">
                    <div style="height:170px;background:linear-gradient(145deg,<?php echo $accentColor; ?>11,<?php echo $accentColor; ?>33,<?php echo $accentColor; ?>55);display:flex;align-items:center;justify-content:center;border-bottom:1px solid var(--border-subtle);position:relative;overflow:hidden;">
                        <!-- 装饰 SVG -->
                        <svg width="100%" height="100%" viewBox="0 0 280 170" style="position:absolute;opacity:0.08;" preserveAspectRatio="none">
                            <rect x="24" y="24" width="232" height="122" rx="6" fill="none" stroke="<?php echo $accentColor; ?>" stroke-width="1"/>
                            <rect x="36" y="38" width="70" height="10" rx="3" fill="<?php echo $accentColor; ?>"/>
                            <rect x="36" y="56" width="150" height="5" rx="2" fill="<?php echo $accentColor; ?>" opacity="0.5"/>
                            <rect x="36" y="67" width="130" height="5" rx="2" fill="<?php echo $accentColor; ?>" opacity="0.3"/>
                            <rect x="36" y="82" width="44" height="26" rx="3" fill="<?php echo $accentColor; ?>" opacity="0.12"/>
                            <rect x="86" y="82" width="44" height="26" rx="3" fill="<?php echo $accentColor; ?>" opacity="0.08"/>
                            <rect x="136" y="82" width="44" height="26" rx="3" fill="<?php echo $accentColor; ?>" opacity="0.12"/>
                            <rect x="36" y="118" width="200" height="4" rx="2" fill="<?php echo $accentColor; ?>" opacity="0.2"/>
                            <rect x="36" y="127" width="160" height="4" rx="2" fill="<?php echo $accentColor; ?>" opacity="0.1"/>
                        </svg>
                        <!-- 标签 -->
                        <div style="position:relative;z-index:1;display:flex;flex-direction:column;align-items:center;gap:var(--sp-2);">
                            <?php if ($t['is_active']): ?>
                            <span style="padding:var(--sp-1) var(--sp-3);background:<?php echo $accentColor; ?>;color:var(--bg-base);border-radius:var(--r-full);font-family:var(--font-mono);font-size:10px;font-weight:600;">LIVE</span>
                            <?php endif; ?>
                            <span style="font-family:var(--font-mono);font-size:var(--fs-xs);color:<?php echo $accentColor; ?>;opacity:0.7;">// <?php echo $t['slug']; ?></span>
                        </div>
                    </div>
                </a>
                <!-- 信息区 -->
                <div style="padding:var(--sp-4) var(--sp-5);">
                    <div style="display:flex;align-items:center;gap:var(--sp-2);margin-bottom:var(--sp-2);">
                        <div style="width:10px;height:10px;border-radius:50%;background:<?php echo $accentColor; ?>;flex-shrink:0;box-shadow:0 0 6px <?php echo $accentColor; ?>66;"></div>
                        <h3 style="font-family:var(--font-display);font-weight:600;font-size:var(--fs-base);color:var(--text-primary);"><?php echo xss_clean($t['name']); ?></h3>
                    </div>
                    <p style="font-size:var(--fs-xs);color:var(--text-secondary);line-height:var(--lh-normal);margin-bottom:var(--sp-3);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                        <?php echo xss_clean($t['desc'] ?: '暂无描述'); ?>
                    </p>
                    <div style="display:flex;gap:var(--sp-2);flex-wrap:wrap;align-items:center;">
                        <span style="font-family:var(--font-mono);font-size:10px;padding:2px var(--sp-2);background:var(--bg-surface-3);border-radius:var(--r-full);color:var(--text-muted);">
                            <?php echo $layoutLabels[$t['layout']] ?? $t['layout']; ?>
                        </span>
                        <span style="font-family:var(--font-mono);font-size:10px;padding:2px var(--sp-2);background:var(--accent-subtle);border-radius:var(--r-full);color:var(--accent);">
                            <?php echo $cat; ?>
                        </span>
                        <div style="margin-left:auto;">
                            <a href="/?preview_theme=<?php echo $t['slug']; ?>" target="_blank" class="btn btn--ghost btn--sm" style="font-size:10px;padding:var(--sp-1) var(--sp-3);">预览</a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- 无结果 -->
        <div id="noResults" style="display:none;text-align:center;padding:var(--sp-16);color:var(--text-muted);">
            <svg width="40" height="40" viewBox="0 0 40 40" fill="none" style="margin-bottom:var(--sp-4);opacity:0.3;"><circle cx="20" cy="20" r="12" stroke="currentColor" stroke-width="1.5"/><path d="M29 29l6 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
            <p style="font-size:var(--fs-base);">该分类暂无模板</p>
        </div>

    </div>
</div>

<script>
function filterTemplates(category, btn) {
    // 更新按钮状态
    document.querySelectorAll('.filter-btn').forEach(function(b) {
        b.style.background = 'transparent';
        b.style.color = 'var(--text-secondary)';
        b.style.borderColor = 'var(--border-default)';
    });
    btn.style.background = 'var(--accent)';
    btn.style.color = 'var(--bg-base)';
    btn.style.borderColor = 'var(--accent)';

    // 筛选模板
    var cards = document.querySelectorAll('.template-card');
    var visible = 0;
    cards.forEach(function(card) {
        if (category === '全部' || card.getAttribute('data-category') === category) {
            card.style.display = '';
            visible++;
            // Animate in
            card.style.opacity = '0';
            card.style.transform = 'translateY(10px)';
            setTimeout(function() {
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, 30);
        } else {
            card.style.display = 'none';
        }
    });

    document.getElementById('noResults').style.display = visible === 0 ? 'block' : 'none';
}
</script>

<style>
.template-card:hover { border-color: var(--accent) !important; transform: translateY(-3px); box-shadow: 0 4px 20px rgba(0,0,0,0.15); }
.filter-btn:hover:not([style*="var(--accent)"]) { border-color: var(--border-strong) !important; color: var(--text-primary) !important; }
@media (prefers-reduced-motion: reduce) { .template-card { transition: none !important; } }
</style>
