<?php
/**
 * 模板中心
 */

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
require_once ROOT_PATH . 'core/lib/template_categories.php';
require_once ROOT_PATH . 'core/lib/template_package.php';

if (!isset($templateLoader) || !is_object($templateLoader)) {
    $templateLoader = new \Core\Lib\TemplateLoader($license);
}
if (!isset($templatePackageManager) || !is_object($templatePackageManager)) {
    $templatePackageManager = new \Core\Lib\TemplatePackageManager($db, $license);
}

if ($action === 'list') {
    $licenseInfo = $license->getStatus();
    $currentLevel = (int) ($licenseInfo['level'] ?? 1);
    $levelNames = [1 => '免费版', 2 => '基础版', 3 => '专业版'];
    $currentLevelName = $levelNames[$currentLevel] ?? '免费版';

    $levelFilter = isset($_GET['level_filter']) ? trim((string) $_GET['level_filter']) : 'all';
    $categoryFilter = isset($_GET['category_filter']) ? trim((string) $_GET['category_filter']) : 'all';
    $templateTab = isset($_GET['template_tab']) ? trim((string) $_GET['template_tab']) : 'remote';
    if (!in_array($templateTab, ['remote', 'export', 'import', 'local'], true)) {
        $templateTab = 'remote';
    }

    $templateCategories = cmsTemplateCategoryOptions();
    $siteRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'site_template'");
    $lastRow = $db->fetch("SELECT config_value FROM {$db->table('config')} WHERE config_key = 'last_template_key'");
    $currentTemplateKey = trim((string) ($lastRow['config_value'] ?? ($siteRow['config_value'] ?? 'default')));
    if ($currentTemplateKey === '') {
        $currentTemplateKey = 'default';
    }

    $remoteTemplates = [];
    $remoteResult = $templateLoader->fetchRemoteTemplateList(999);
    if ((int) ($remoteResult['code'] ?? 500) === 200 && !empty($remoteResult['templates']) && is_array($remoteResult['templates'])) {
        $remoteTemplates = $remoteResult['templates'];
    }
    foreach ($remoteTemplates as &$tpl) {
        $tpl['category'] = cmsTemplateNormalizeCategoryKey((string) ($tpl['category'] ?? ''));
        $tpl['category_label'] = trim((string) ($tpl['category_label'] ?? '')) !== ''
            ? trim((string) $tpl['category_label'])
            : cmsTemplateCategoryLabel((string) ($tpl['category'] ?? ''));
    }
    unset($tpl);
    $remoteTemplates = cmsSortTemplatesNewestFirst($remoteTemplates);

    $localTemplates = $templatePackageManager->listInstalledTemplates($currentTemplateKey);
    $installedKeyMap = [];
    $localTemplateThumbnails = [];
    foreach ($localTemplates as $item) {
        $localKey = trim((string) ($item['template_key'] ?? ''));
        if ($localKey === '') {
            continue;
        }
        $installedKeyMap[$localKey] = true;
        $manifest = $templateLoader->readManifest($localKey);
        $thumb = '';
        if (is_array($manifest)) {
            $thumb = trim((string) ($manifest['thumbnail'] ?? ''));
            if ($thumb === '') {
                $thumb = trim((string) ($manifest['preview'] ?? ''));
            }
        }
        if ($thumb === '') {
            $templateDir = dirname(__DIR__, 2) . '/template/' . $localKey;
            foreach (['thumbnail.jpg', 'thumbnail.jpeg', 'thumbnail.png', 'preview.jpg', 'preview.jpeg', 'preview.png', 'thumb.jpg', 'thumb.png'] as $candidate) {
                if (is_file($templateDir . '/' . $candidate)) {
                    $thumb = '/template/' . rawurlencode($localKey) . '/' . rawurlencode($candidate);
                    break;
                }
            }
        }
        $localTemplateThumbnails[$localKey] = $thumb;
    }

    $templateFilters = ['all' => '全部模板', '1' => '免费版', '2' => '基础版', '3' => '专业版'];
    $templateFilterCounts = ['all' => count($remoteTemplates), '1' => 0, '2' => 0, '3' => 0];
    foreach ($remoteTemplates as $tpl) {
        $requiredLevel = (string) (int) ($tpl['required_level'] ?? 1);
        if (isset($templateFilterCounts[$requiredLevel])) {
            $templateFilterCounts[$requiredLevel]++;
        }
    }
    if (!isset($templateFilters[$levelFilter])) {
        $levelFilter = 'all';
    }
    if ($categoryFilter !== 'all' && !isset($templateCategories[$categoryFilter])) {
        $categoryFilter = 'all';
    }

    $categoryFilterCounts = ['all' => 0];
    foreach ($templateCategories as $categoryKey => $categoryLabel) {
        $categoryFilterCounts[$categoryKey] = 0;
    }
    foreach ($remoteTemplates as $tpl) {
        $requiredLevel = (int) ($tpl['required_level'] ?? 1);
        if ($levelFilter !== 'all' && $requiredLevel !== (int) $levelFilter) {
            continue;
        }
        $category = (string) ($tpl['category'] ?? 'other');
        if (!isset($categoryFilterCounts[$category])) {
            $category = 'other';
            if (!isset($categoryFilterCounts[$category])) {
                $categoryFilterCounts[$category] = 0;
            }
        }
        $categoryFilterCounts['all']++;
        $categoryFilterCounts[$category]++;
    }

    $displayTemplates = array_values(array_filter($remoteTemplates, function ($tpl) use ($levelFilter, $categoryFilter) {
        $requiredLevel = (int) ($tpl['required_level'] ?? 1);
        $category = (string) ($tpl['category'] ?? 'other');
        if ($levelFilter !== 'all' && $requiredLevel !== (int) $levelFilter) {
            return false;
        }
        if ($categoryFilter !== 'all' && $category !== $categoryFilter) {
            return false;
        }
        return true;
    }));
    $templatePageSize = 20;
    $templateTotal = count($displayTemplates);
    $templateTotalPages = max(1, (int) ceil($templateTotal / $templatePageSize));
    $templatePage = max(1, min($templateTotalPages, intval($_GET['template_page'] ?? 1)));
    $pagedTemplates = array_slice($displayTemplates, ($templatePage - 1) * $templatePageSize, $templatePageSize);
    $templatePageQuery = [
        'act' => 'template',
        'template_tab' => 'remote',
        'level_filter' => $levelFilter,
        'category_filter' => $categoryFilter,
    ];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div>
                <h2 style="margin:0;font-size:20px;color:#0f172a;">模板中心</h2>
                <p style="margin:6px 0 0;color:#64748b;">远程模板、本地模板、导入导出统一管理</p>
            </div>
            <div style="padding:8px 14px;background:#eff6ff;border-radius:999px;color:#2563eb;font-weight:600;">当前授权：<?php echo htmlspecialchars($currentLevelName); ?></div>
        </div>

        <div class="template-summary-grid">
            <div class="template-summary-card">
                <div class="template-summary-label">远程模板</div>
                <div class="template-summary-value"><?php echo count($remoteTemplates); ?></div>
            </div>
            <div class="template-summary-card">
                <div class="template-summary-label">筛选结果</div>
                <div class="template-summary-value"><?php echo $templateTotal; ?></div>
            </div>
            <div class="template-summary-card">
                <div class="template-summary-label">当前使用</div>
                <div class="template-summary-value"><?php echo htmlspecialchars($currentTemplateKey); ?></div>
            </div>
            <div class="template-summary-card">
                <div class="template-summary-label">本地模板</div>
                <div class="template-summary-value"><?php echo count($localTemplates); ?></div>
            </div>
        </div>

        <div class="content-card" style="padding:18px 20px;">
            <div class="template-tab-bar">
                <button type="button" class="template-tab-btn <?php echo $templateTab === 'remote' ? 'active' : ''; ?>" data-template-tab="remote">远程模板</button>
                <button type="button" class="template-tab-btn <?php echo $templateTab === 'export' ? 'active' : ''; ?>" data-template-tab="export">模板导出</button>
                <button type="button" class="template-tab-btn <?php echo $templateTab === 'import' ? 'active' : ''; ?>" data-template-tab="import">模板导入</button>
                <button type="button" class="template-tab-btn <?php echo $templateTab === 'local' ? 'active' : ''; ?>" data-template-tab="local">本地已安装模板</button>
            </div>

            <div class="template-tab-panel <?php echo $templateTab === 'export' ? 'active' : ''; ?>" data-template-panel="export">
                <div class="template-package-panel">
                    <div class="template-package-head"><strong>模板导出</strong><span>可导出当前模板、站点配置、页面装修 JSON 和自定义变量</span></div>
                    <form method="post" action="?act=template&action=export_local_template" class="template-package-form">
                        <input type="hidden" name="action" value="export_local_template">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                        <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($currentTemplateKey); ?>">
                        <div class="template-package-meta">导出后可在其他站点后台直接导入。</div>
                        <div class="template-package-group">
                            <span class="template-package-group-label">导出内容</span>
                            <label class="template-package-check"><input type="checkbox" name="include_template_config" value="1" checked> 模板绑定与配置</label>
                            <label class="template-package-check"><input type="checkbox" name="export_basic" value="1" checked> 基础信息</label>
                            <label class="template-package-check"><input type="checkbox" name="export_seo" value="1" checked> SEO 与链接</label>
                            <label class="template-package-check"><input type="checkbox" name="export_appearance" value="1" checked> 视觉外观</label>
                            <label class="template-package-check"><input type="checkbox" name="export_contact" value="1" checked> 联系信息</label>
                        </div>
                        <label class="template-package-check"><input type="checkbox" name="include_builder_pages" value="1" checked> 页面装修数据</label>
                        <label class="template-package-check"><input type="checkbox" name="include_custom_vars" value="1" checked> 自定义变量</label>
                        <button type="button" class="btn btn-secondary template-package-preview-btn" data-preview-url="?act=template&action=preview_local_template">预览包内容</button>
                        <button type="submit" class="btn btn-primary">导出当前模板包</button>
                    </form>
                </div>
            </div>

            <div class="template-tab-panel <?php echo $templateTab === 'import' ? 'active' : ''; ?>" data-template-panel="import">
                <div class="template-package-panel">
                    <div class="template-package-head"><strong>模板导入</strong><span>支持本地 ZIP 模板包导入</span></div>
                    <form method="post" action="?act=template&action=import_local_template" enctype="multipart/form-data" class="template-package-form">
                        <input type="hidden" name="action" value="import_local_template">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                        <input type="file" name="template_package" accept=".zip,.yttpl.zip" class="template-package-file" required>
                        <label class="template-package-check"><input type="checkbox" name="activate_after_import" value="1" checked> 导入后直接启用</label>
                        <button type="submit" class="btn btn-secondary">导入本地模板包</button>
                    </form>
                </div>
            </div>

            <div class="template-tab-panel <?php echo $templateTab === 'local' ? 'active' : ''; ?>" data-template-panel="local">
                <div class="template-local-head">
                    <div>
                        <h3>本地已安装模板</h3>
                        <p>这里显示服务器上已有的模板目录，可直接启用、导出或删除。</p>
                    </div>
                    <form method="post" action="?act=template" onsubmit="return confirm('确定清理无效模板吗？');">
                        <input type="hidden" name="action" value="delete_invalid_local_templates">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                        <button type="submit" class="btn btn-danger btn-sm">清理无效模板</button>
                    </form>
                </div>
                <div class="template-local-grid">
                    <?php foreach ($localTemplates as $localTpl):
                        $localKey = trim((string) ($localTpl['template_key'] ?? ''));
                        $localName = trim((string) ($localTpl['name'] ?? $localKey));
                        $localVersion = trim((string) ($localTpl['version'] ?? ''));
                        $localActive = !empty($localTpl['is_active']);
                        $localDefault = !empty($localTpl['is_default']);
                        $localLocked = !empty($localTpl['is_locked']);
                        $localValid = !empty($localTpl['is_valid']);
                        $localThumb = trim((string) ($localTemplateThumbnails[$localKey] ?? ''));
                    ?>
                    <div class="template-local-card <?php echo $localActive ? 'active' : ''; ?> <?php echo !$localValid ? 'invalid' : ''; ?>">
                        <div class="template-thumb">
                            <?php if ($localThumb !== ''): ?>
                                <img src="<?php echo htmlspecialchars($localThumb); ?>" alt="<?php echo htmlspecialchars($localName); ?>">
                            <?php else: ?>
                                <div class="template-thumb-placeholder">模板</div>
                            <?php endif; ?>
                            <span class="template-state-badge"><?php echo $localActive ? '当前使用' : ($localValid ? '可用' : '异常'); ?></span>
                        </div>
                        <div class="template-local-top">
                            <div>
                                <div class="template-local-name"><?php echo htmlspecialchars($localName); ?></div>
                                <div class="template-local-key"><?php echo htmlspecialchars($localKey); ?><?php echo $localVersion !== '' ? ' · v' . htmlspecialchars($localVersion) : ''; ?></div>
                            </div>
                            <span class="badge <?php echo $localActive ? 'badge-success' : ($localValid ? 'badge-primary' : 'badge-danger'); ?>">
                                <?php echo $localActive ? '当前启用' : ($localValid ? '可用' : '异常'); ?>
                            </span>
                        </div>
                        <div class="template-local-actions">
                            <?php if (!$localActive && !$localLocked): ?>
                            <button type="button" class="btn btn-primary btn-sm js-local-activate" data-template-key="<?php echo htmlspecialchars($localKey); ?>">启用</button>
                            <?php endif; ?>
                            <form method="post" action="?act=template" class="template-inline-form">
                                <input type="hidden" name="action" value="export_local_template">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                                <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($localKey); ?>">
                                <button type="submit" class="btn btn-secondary btn-sm">导出</button>
                            </form>
                            <?php if (!$localDefault && !$localActive): ?>
                            <form method="post" action="?act=template" class="template-inline-form" onsubmit="return confirm('确定删除这个模板吗？');">
                                <input type="hidden" name="action" value="delete_local_template">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                                <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($localKey); ?>">
                                <button type="submit" class="btn btn-danger btn-sm">删除</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="template-tab-panel <?php echo $templateTab === 'remote' ? 'active' : ''; ?>" data-template-panel="remote">
                <div class="template-filter-block">
                    <div class="template-filter-bar">
                        <?php foreach ($templateFilters as $filterValue => $filterLabel): ?>
                        <a href="?<?php echo htmlspecialchars(http_build_query(['act' => 'template', 'template_tab' => 'remote', 'level_filter' => $filterValue, 'category_filter' => $categoryFilter]), ENT_QUOTES, 'UTF-8'); ?>" class="template-filter-chip <?php echo $levelFilter === $filterValue ? 'active' : ''; ?>">
                            <?php echo htmlspecialchars($filterLabel); ?>
                            <span class="template-filter-count"><?php echo (int) ($templateFilterCounts[$filterValue] ?? 0); ?></span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                    <div class="template-filter-bar template-filter-bar-secondary">
                        <a href="?<?php echo htmlspecialchars(http_build_query(['act' => 'template', 'template_tab' => 'remote', 'level_filter' => $levelFilter, 'category_filter' => 'all']), ENT_QUOTES, 'UTF-8'); ?>" class="template-filter-chip template-category-chip <?php echo $categoryFilter === 'all' ? 'active' : ''; ?>">
                            全部分类
                            <span class="template-filter-count"><?php echo (int) ($categoryFilterCounts['all'] ?? 0); ?></span>
                        </a>
                        <?php foreach ($templateCategories as $categoryKey => $categoryLabel): ?>
                        <a href="?<?php echo htmlspecialchars(http_build_query(['act' => 'template', 'template_tab' => 'remote', 'level_filter' => $levelFilter, 'category_filter' => $categoryKey]), ENT_QUOTES, 'UTF-8'); ?>" class="template-filter-chip template-category-chip <?php echo $categoryFilter === $categoryKey ? 'active' : ''; ?>">
                            <?php echo htmlspecialchars($categoryLabel); ?>
                            <span class="template-filter-count"><?php echo (int) ($categoryFilterCounts[$categoryKey] ?? 0); ?></span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>

                <?php if (empty($displayTemplates)): ?>
                    <div class="empty-state" style="padding:60px 20px;">当前筛选下没有模板</div>
                <?php else: ?>
                    <div class="template-remote-grid">
                        <?php foreach ($pagedTemplates as $tpl):
                            $tplKey = trim((string) ($tpl['template_key'] ?? ''));
                            $name = trim((string) ($tpl['name'] ?? $tplKey));
                            $thumbnail = trim((string) ($tpl['thumbnail'] ?? ''));
                            $licenseCenterBase = defined('LICENSE_CENTER_URL') ? rtrim((string) LICENSE_CENTER_URL, '/') : 'http://yutou.wtbidc.cn/license-center';
                            $demoUrl = $licenseCenterBase . '/portal_template_preview.php?template=' . rawurlencode($tplKey);
                            $requiredLevel = (int) ($tpl['required_level'] ?? 1);
                            $requiredLevelName = $levelNames[$requiredLevel] ?? '更高版本';
                            $isFree = (int) ($tpl['is_free'] ?? 0) === 1;
                            $isLocked = !$isFree && $requiredLevel > $currentLevel;
                            $isInstalled = !empty($installedKeyMap[$tplKey]);
                            $isActive = ($tplKey === $currentTemplateKey);
                            $statusText = $isActive ? '当前使用' : ($isLocked ? '需升级' : ($isInstalled ? '已安装' : '可安装'));
                        ?>
                        <div class="template-card <?php echo $isActive ? 'active' : ''; ?> <?php echo $isLocked ? 'locked' : ''; ?>">
                            <div class="template-thumb">
                                <?php if ($thumbnail !== ''): ?>
                                    <img src="<?php echo htmlspecialchars($thumbnail); ?>" alt="<?php echo htmlspecialchars($name); ?>">
                                <?php else: ?>
                                    <div class="template-thumb-placeholder">模板</div>
                                <?php endif; ?>
                                <span class="template-state-badge <?php echo $isLocked ? 'is-upgrade' : ''; ?>"><?php echo htmlspecialchars($statusText); ?></span>
                            </div>
                            <div class="template-info">
                                <div class="template-name"><?php echo htmlspecialchars($name); ?></div>
                                <div class="template-meta">
                                    <span><?php echo htmlspecialchars($tplKey); ?></span>
                                    <span><?php echo htmlspecialchars((string) ($tpl['category_label'] ?? '')); ?></span>
                                    <span>V<?php echo (int) $requiredLevel; ?></span>
                                </div>
                                <?php if (!empty($tpl['description'])): ?>
                                    <div class="template-desc"><?php echo htmlspecialchars((string) $tpl['description']); ?></div>
                                <?php endif; ?>
                                <div class="template-actions">
                                    <a href="<?php echo htmlspecialchars($demoUrl); ?>" target="_blank" rel="noopener noreferrer" class="btn btn-secondary btn-sm">查看模板演示</a>
                                    <?php if ($isActive): ?>
                                        <span class="badge badge-success">当前使用</span>
                                    <?php elseif (!$isLocked): ?>
                                        <form method="post" action="?act=template" class="template-inline-form js-remote-switch-form">
                                            <input type="hidden" name="action" value="switch_template">
                                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                                            <input type="hidden" name="template_key" value="<?php echo htmlspecialchars($tplKey); ?>">
                                            <button type="submit" class="btn btn-primary btn-sm"><?php echo $isInstalled ? '启用' : '安装并启用'; ?></button>
                                        </form>
                                    <?php else: ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if ($templateTotalPages > 1): ?>
                    <nav class="pagination template-pagination" aria-label="模板分页">
                        <?php if ($templatePage > 1): ?>
                        <a href="?<?php echo htmlspecialchars(http_build_query($templatePageQuery + ['template_page' => $templatePage - 1]), ENT_QUOTES, 'UTF-8'); ?>" aria-label="上一页">上一页</a>
                        <?php endif; ?>
                        <?php
                        $pageStart = max(1, $templatePage - 2);
                        $pageEnd = min($templateTotalPages, $templatePage + 2);
                        if ($pageStart > 1): ?>
                            <a href="?<?php echo htmlspecialchars(http_build_query($templatePageQuery + ['template_page' => 1]), ENT_QUOTES, 'UTF-8'); ?>">1</a>
                            <?php if ($pageStart > 2): ?><span class="ellipsis">…</span><?php endif; ?>
                        <?php endif; ?>
                        <?php for ($pageNo = $pageStart; $pageNo <= $pageEnd; $pageNo++): ?>
                            <a href="?<?php echo htmlspecialchars(http_build_query($templatePageQuery + ['template_page' => $pageNo]), ENT_QUOTES, 'UTF-8'); ?>" class="<?php echo $pageNo === $templatePage ? 'active' : ''; ?>" <?php echo $pageNo === $templatePage ? 'aria-current="page"' : ''; ?>><?php echo $pageNo; ?></a>
                        <?php endfor; ?>
                        <?php if ($pageEnd < $templateTotalPages): ?>
                            <?php if ($pageEnd < $templateTotalPages - 1): ?><span class="ellipsis">…</span><?php endif; ?>
                            <a href="?<?php echo htmlspecialchars(http_build_query($templatePageQuery + ['template_page' => $templateTotalPages]), ENT_QUOTES, 'UTF-8'); ?>"><?php echo $templateTotalPages; ?></a>
                        <?php endif; ?>
                        <?php if ($templatePage < $templateTotalPages): ?>
                        <a href="?<?php echo htmlspecialchars(http_build_query($templatePageQuery + ['template_page' => $templatePage + 1]), ENT_QUOTES, 'UTF-8'); ?>" aria-label="下一页">下一页</a>
                        <?php endif; ?>
                    </nav>
                    <div class="template-page-meta">第 <?php echo $templatePage; ?> / <?php echo $templateTotalPages; ?> 页 · 每页 <?php echo $templatePageSize; ?> 个 · 共 <?php echo $templateTotal; ?> 个模板</div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>

            <div id="templatePackagePreview" class="template-package-preview" style="display:none;"></div>
        </div>
    </div>

    <style>
        .template-tab-bar{display:flex;gap:10px;margin-bottom:18px;flex-wrap:wrap}
        .template-tab-btn{border:1px solid #dbe3f0;background:#fff;color:#475569;padding:10px 16px;border-radius:999px;cursor:pointer;font-size:13px;font-weight:600}
        .template-tab-btn.active{background:#4c73ff;color:#fff;border-color:#4c73ff}
        .template-tab-panel{display:none}
        .template-tab-panel.active{display:block}
        .template-filter-block{display:flex;flex-direction:column;gap:14px;margin-bottom:18px}
        .template-filter-bar{display:flex;gap:10px;flex-wrap:wrap}
        .template-filter-chip{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border:1px solid #dbe3f0;border-radius:999px;background:#fff;color:#475569;text-decoration:none;font-size:13px}
        .template-filter-chip.active{background:#eef4ff;border-color:#4c73ff;color:#1d4ed8}
        .template-filter-count{font-size:12px;color:#94a3b8}
        .template-package-panel{padding:4px 0}
        .template-package-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:12px}
        .template-package-head strong{font-size:16px;color:#0f172a}
        .template-package-head span{color:#64748b;font-size:13px}
        .template-package-form{display:flex;flex-direction:column;gap:10px}
        .template-package-meta,.template-package-check,.template-package-group-label,.template-package-file{font-size:13px;color:#475569}
        .template-package-group{display:flex;flex-wrap:wrap;gap:10px;padding:12px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px}
        .template-package-check{display:inline-flex;align-items:center;gap:6px}
        .template-local-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:16px}
        .template-local-head h3{margin:0;font-size:16px;color:#0f172a}
        .template-local-head p{margin:6px 0 0;color:#64748b;font-size:13px}
        .template-local-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px}
        .template-remote-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px}
        .template-local-card,.template-card{border:1px solid #e2e8f0;border-radius:14px;background:#fff;overflow:hidden}
        .template-local-card{padding:16px;display:flex;flex-direction:column;gap:14px}
        .template-card{display:flex;flex-direction:column}
        .template-card.active{border-color:#4c73ff;box-shadow:0 0 0 1px rgba(76,115,255,.08)}
        .template-card.locked{opacity:.82}
        .template-local-card.invalid{border-style:dashed}
        .template-local-top{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
        .template-local-name,.template-name{font-size:16px;font-weight:700;color:#0f172a}
        .template-local-key,.template-meta,.template-desc{font-size:12px;color:#64748b}
        .template-local-actions,.template-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
        .template-inline-form{display:inline-flex;margin:0}
        .template-desc{line-height:1.5;min-height:36px}
        .template-state-badge.is-upgrade{background:#dc2626;color:#fff;border:1px solid #b91c1c;box-shadow:0 12px 24px rgba(220,38,38,.32);font-weight:800;padding:6px 10px;font-size:13px}
        .template-thumb{height:160px;background:#f8fafc;display:flex;align-items:center;justify-content:center;overflow:hidden;position:relative}
        .template-thumb img{width:100%;height:100%;object-fit:cover;display:block}
        .template-card .template-thumb{width:100%;height:auto;aspect-ratio:16/9;margin:0;background:#fff;border-radius:14px 14px 0 0}
        .template-card .template-thumb img{object-fit:contain;object-position:center}
        .template-thumb-placeholder{color:#94a3b8;font-size:14px}
        .template-state-badge{position:absolute;left:10px;top:10px;padding:4px 8px;background:rgba(15,23,42,.78);color:#fff;border-radius:999px;font-size:12px;line-height:1}
        .template-info{height:100%;padding:14px 16px;display:flex;flex-direction:column;gap:10px}
        .template-actions{margin-top:auto}
        .template-meta{display:flex;flex-wrap:wrap;gap:8px}
        .template-meta span{padding:3px 8px;background:#f1f5f9;border-radius:999px}
        .template-package-preview{margin-top:16px;padding:16px;border:1px solid #dbe3f0;border-radius:12px;background:#f8fbff}
        .template-summary-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin:0 0 16px}
        .template-summary-card{padding:16px 18px;border:1px solid #e2e8f0;border-radius:14px;background:linear-gradient(180deg,#ffffff 0%,#f8fbff 100%);box-shadow:0 8px 24px rgba(15,23,42,.04)}
        .template-summary-label{font-size:13px;color:#64748b;margin-bottom:6px}
        .template-summary-value{font-size:22px;font-weight:800;color:#0f172a;line-height:1.1}
        .template-pagination{margin:22px 0 8px;padding:0;align-items:center;flex-wrap:wrap}
        .template-pagination .ellipsis{display:inline-flex;align-items:center;padding:6px 3px;color:#94a3b8}
        .template-page-meta{text-align:center;color:#94a3b8;font-size:12px}
        @media (max-width: 768px){
            .template-package-head,.template-local-head{flex-direction:column}
            .template-remote-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
        }
        @media (max-width: 480px){.template-remote-grid{grid-template-columns:1fr}}
    </style>

    <script>
    (function() {
        var csrfToken = <?php echo json_encode(getAdminCsrfToken(), JSON_UNESCAPED_UNICODE); ?>;
        function setTab(tab) {
            var url = new URL(window.location.href);
            url.searchParams.set('template_tab', tab);
            window.history.replaceState({}, '', url.toString());
            document.querySelectorAll('.template-tab-btn').forEach(function(btn) {
                btn.classList.toggle('active', btn.getAttribute('data-template-tab') === tab);
            });
            document.querySelectorAll('.template-tab-panel').forEach(function(panel) {
                panel.classList.toggle('active', panel.getAttribute('data-template-panel') === tab);
            });
        }

        document.querySelectorAll('.template-tab-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                setTab(btn.getAttribute('data-template-tab'));
            });
        });

        document.querySelectorAll('.template-package-preview-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var form = btn.closest('form');
                if (!form) return;
                fetch(btn.getAttribute('data-preview-url'), {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    body: new FormData(form)
                }).then(function(resp) {
                    return resp.json();
                }).then(function(json) {
                    var preview = document.getElementById('templatePackagePreview');
                    if (!preview) return;
                    if (!json || json.code !== 200) {
                        preview.style.display = 'block';
                        preview.innerHTML = '<strong>预览失败</strong><div style="margin-top:8px;color:#b91c1c;">' + ((json && json.msg) ? json.msg : '未知错误') + '</div>';
                        return;
                    }
                    var previewData = json.preview || {};
                    var summary = previewData.summary || {};
                    var siteConfigs = Array.isArray(previewData.site_configs) ? previewData.site_configs : [];
                    var builderPages = Array.isArray(previewData.builder_pages) ? previewData.builder_pages : [];
                    var customVars = Array.isArray(previewData.custom_vars) ? previewData.custom_vars : [];
                    var siteConfigHtml = siteConfigs.slice(0, 5).map(function(row) {
                        return '<li><code>' + String(row.config_key || '') + '</code> = ' + String(row.config_value || '') + '</li>';
                    }).join('');
                    var builderPageHtml = builderPages.slice(0, 5).map(function(row) {
                        return '<li><code>' + String(row.page_name || row.page_key || '') + '</code></li>';
                    }).join('');
                    var customVarHtml = customVars.slice(0, 5).map(function(row) {
                        return '<li><code>' + String(row.var_key || '') + '</code></li>';
                    }).join('');
                    preview.style.display = 'block';
                    preview.innerHTML = ''
                        + '<strong>模板包预览</strong>'
                        + '<div style="margin-top:8px;color:#475569;">站点配置：' + (summary.site_configs || 0) + '，页面装修：' + (summary.builder_pages || 0) + '，变量：' + (summary.custom_vars || 0) + '</div>'
                        + '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;margin-top:12px;">'
                        + '<div><div style="font-weight:600;margin-bottom:6px;">站点配置</div><ul style="margin:0;padding-left:18px;">' + siteConfigHtml + '</ul></div>'
                        + '<div><div style="font-weight:600;margin-bottom:6px;">页面装修</div><ul style="margin:0;padding-left:18px;">' + builderPageHtml + '</ul></div>'
                        + '<div><div style="font-weight:600;margin-bottom:6px;">自定义变量</div><ul style="margin:0;padding-left:18px;">' + customVarHtml + '</ul></div>'
                        + '</div>';
                }).catch(function() {
                    var preview = document.getElementById('templatePackagePreview');
                    if (preview) {
                        preview.style.display = 'block';
                        preview.innerHTML = '<strong>预览失败</strong><div style="margin-top:8px;color:#b91c1c;">请求异常</div>';
                    }
                });
            });
        });

        document.querySelectorAll('.js-local-activate').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var templateKey = btn.getAttribute('data-template-key');
                if (!templateKey) return;
                var data = new FormData();
                data.append('action', 'activate_local_template');
                data.append('csrf_token', csrfToken);
                data.append('template_key', templateKey);
                fetch('?act=template', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    body: data
                }).then(function(resp) { return resp.text(); }).then(function(text) {
                    var json = null;
                    try {
                        json = JSON.parse(text);
                    } catch (err) {
                        alert(text && text.trim() ? text : '请求失败');
                        return;
                    }
                    if (json && json.code === 200) {
                        window.location.href = '?act=template&template_tab=local';
                        return;
                    }
                    alert((json && json.msg) ? json.msg : '启用失败');
                }).catch(function() {
                    alert('请求失败');
                });
            });
        });

        document.querySelectorAll('.js-remote-switch-form').forEach(function(form) {
            form.addEventListener('submit', function(ev) {
                ev.preventDefault();
                fetch('?act=template', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: {'X-Requested-With': 'XMLHttpRequest'},
                    body: new FormData(form)
                }).then(function(resp) { return resp.json(); }).then(function(json) {
                    if (json && json.code === 200) {
                        window.location.href = '?act=template&template_tab=remote';
                        return;
                    }
                    alert((json && json.msg) ? json.msg : '操作失败');
                }).catch(function() {
                    alert('请求失败');
                });
            });
        });
    })();
    </script>
    <?php
}
