<?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 = '';
$activeTab = isset($_GET['tab']) ? trim((string)$_GET['tab']) : 'packs';
if (!in_array($activeTab, array('packs', 'modules'))) { $activeTab = 'packs'; }

ensure_template_packs_dir();
initialize_builtin_template_packs();

// ── 套件操作 ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    require_csrf();
    $action = trim((string)$_POST['action']);

    if ($action === 'create') {
        $newCode = isset($_POST['code']) ? trim((string)$_POST['code']) : '';
        $newName = isset($_POST['name']) ? trim((string)$_POST['name']) : '';
        $newDesc = isset($_POST['description']) ? trim((string)$_POST['description']) : '';
        $newPackType = isset($_POST['pack_type']) ? trim((string)$_POST['pack_type']) : 'variation';
        try {
            create_template_pack($newCode, $newName, $newDesc, $newPackType);
            $success = '模板套件 ' . $newName . ' 创建成功。';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        $activeTab = 'packs';
    } elseif ($action === 'upload') {
        $uploadPackType = isset($_POST['upload_pack_type']) ? trim((string)$_POST['upload_pack_type']) : '';
        if (!in_array($uploadPackType, array('variation', 'standard'))) { $uploadPackType = 'variation'; }
        try {
            $result = upload_template_pack_zip(isset($_FILES['zip_file']) ? $_FILES['zip_file'] : array(), $uploadPackType);
            $msg = '模板套件「' . $result['name'] . '」（' . $result['code'] . '）';
            $msg .= $result['is_overwrite'] ? '已覆盖更新' : '上传成功';
            $msg .= '，共解压 ' . $result['files_count'] . ' 个文件。';
            $success = $msg;
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        $activeTab = 'packs';
        $packSubTab = $uploadPackType;
    } elseif ($action === 'delete') {
        $delCode = isset($_POST['code']) ? trim((string)$_POST['code']) : '';
        try {
            delete_template_pack($delCode);
            $success = '模板套件 ' . $delCode . ' 已删除。';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
        $activeTab = 'packs';
    }
}

$packs = list_template_packs();
$fileKeys = template_pack_file_keys();
$packSubTab = isset($_GET['pack_type']) ? trim((string)$_GET['pack_type']) : 'variation';
if (!in_array($packSubTab, array('variation', 'standard', 'page'))) { $packSubTab = 'variation'; }
$variationPacks = list_template_packs_by_type('variation');
$standardPacks = list_template_packs_by_type('standard');
$pagePacks = list_template_packs_by_type('page');

// 查询每个模板套件被哪些域名使用
$packDomainMap = array();
try {
    $pdo = db_connection();
    $uid = current_user_id();
    $stmt = $pdo->prepare("SELECT template_pack, domain FROM domains WHERE user_id = :uid AND template_pack != '' AND template_pack IS NOT NULL ORDER BY domain");
    $stmt->execute(array(':uid' => $uid));
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $pk = trim((string)$row['template_pack']);
        if ($pk !== '') {
            if (!isset($packDomainMap[$pk])) $packDomainMap[$pk] = array();
            $packDomainMap[$pk][] = (string)$row['domain'];
        }
    }
} catch (Exception $e) { /* ignore */ }

// ── 模块数据 ──
$deleteStatus = isset($_GET['delete_status']) ? trim((string)$_GET['delete_status']) : '';
$dbError = '';
$modules = array();
$domains = array();
$widgetTypes = module_widget_types();
try {
    $domains = list_enabled_domain_options();
    $modules = list_modules();
} catch (Exception $e) {
    $dbError = $e->getMessage();
}
?><!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>
    .tp-tabs { display:flex; gap:4px; margin-bottom:20px; border-bottom:2px solid #e2e8f0; padding-bottom:0; }
    .tp-tabs a { padding:12px 24px; font-size:14px; font-weight:600; color:#64748b; text-decoration:none; border-bottom:2px solid transparent; margin-bottom:-2px; transition:all .2s; }
    .tp-tabs a:hover { color:#334155; }
    .tp-tabs a.is-active { color:#4f46e5; border-bottom-color:#4f46e5; }
    .tab-pane { display:none; }
    .tab-pane.is-active { display:block; }
    .pack-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:16px; }
    .pack-card { padding:16px; border:1px solid rgba(148,163,184,0.16); border-radius:16px; background:linear-gradient(180deg, #ffffff 0%, #f8fafc 100%); display:flex; flex-direction:column; gap:12px; transition:box-shadow 0.2s; }
    .pack-card:hover { box-shadow:0 4px 16px rgba(0,0,0,0.06); }
    .pack-thumb { width:100%; height:90px; border-radius:10px; overflow:hidden; position:relative; }
    .pack-thumb img { width:100%; height:100%; object-fit:cover; display:block; }
    .pack-thumb-letter { width:100%; height:100%; display:flex; align-items:center; justify-content:center; color:#fff; font-size:16px; font-weight:800; letter-spacing:0.04em; text-align:center; padding:8px 12px; line-height:1.3; word-break:break-all; background:#16a34a; }
    .pack-info { flex:1; min-width:0; }
    .pack-info h3 { margin:0 0 2px; font-size:15px; color:#0f172a; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .pack-info .pack-code { font-size:11px; color:#94a3b8; font-family:monospace; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .pack-info p { margin:4px 0 0; color:#64748b; font-size:12px; line-height:1.5; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
    .pack-meta { display:flex; gap:6px; margin-top:8px; flex-wrap:wrap; }
    .pack-meta span { font-size:10px; color:#94a3b8; background:#f1f5f9; padding:2px 7px; border-radius:6px; }
    .pack-actions { display:flex; gap:8px; margin-top:auto; }
    .pack-card { position:relative; }
    .pack-card .pack-domain-tip { display:none; position:absolute; left:50%; transform:translateX(-50%); bottom:100%; margin-bottom:6px; background:#1e293b; color:#f8fafc; font-size:12px; line-height:1.6; padding:8px 14px; border-radius:8px; white-space:nowrap; z-index:100; box-shadow:0 4px 12px rgba(0,0,0,0.15); pointer-events:none; max-width:320px; }
    .pack-card .pack-domain-tip::after { content:''; position:absolute; top:100%; left:50%; transform:translateX(-50%); border:6px solid transparent; border-top-color:#1e293b; }
    .pack-card:hover .pack-domain-tip { display:block; }
    .pack-serial { position:absolute; bottom:12px; right:14px; font-size:11px; font-family:'SFMono-Regular',Consolas,monospace; color:#94a3b8; background:#f1f5f9; padding:2px 8px; border-radius:6px; font-weight:600; letter-spacing:0.02em; }
    .pack-card--standard { background:linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%); border-color:#e2e8f0; }
    .pack-card--standard .pack-thumb-letter { background:#8eaf70; }
    .pack-card--page { background:linear-gradient(180deg, #faf5ff 0%, #f3e8ff 100%); border-color:#e9d5ff; }
    .pack-card--page .pack-thumb-letter { background:#9333ea; }
    .pack-subtabs { display:flex; gap:0; margin-bottom:0; }
    .pack-subtabs a { padding:8px 20px; font-size:13px; font-weight:600; color:#64748b; text-decoration:none; background:#f1f5f9; border:1px solid #e2e8f0; transition:all .2s; }
    .pack-subtabs a:first-child { border-radius:8px 0 0 8px; }
    .pack-subtabs a:last-child { border-radius:0 8px 8px 0; }
    .pack-subtabs a + a { border-left:0; }
    .pack-subtabs a.is-active { background:#4f46e5; color:#fff; border-color:#4f46e5; }
    .pack-subtabs a:not(.is-active):hover { background:#e2e8f0; }
    @media (max-width:1200px) { .pack-grid { grid-template-columns:repeat(3,1fr); } }
    @media (max-width:900px) { .pack-grid { grid-template-columns:repeat(2,1fr); } }
    @media (max-width:640px) { .pack-grid { grid-template-columns:1fr; } }
    @media (max-width: 640px) { .pack-card { flex-direction:column; } }
    /* Modal */
    .tp-modal-overlay { display:none; position:fixed; inset:0; background:rgba(15,23,42,0.45); z-index:9000; justify-content:center; align-items:center; backdrop-filter:blur(2px); }
    .tp-modal-overlay.is-open { display:flex; }
    .tp-modal { background:#fff; border-radius:16px; box-shadow:0 12px 40px rgba(0,0,0,0.18); width:100%; max-width:520px; max-height:90vh; overflow-y:auto; animation:tp-modal-in .2s ease; }
    @keyframes tp-modal-in { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } }
    .tp-modal-head { display:flex; align-items:center; justify-content:space-between; padding:20px 24px 0; }
    .tp-modal-head h2 { margin:0; font-size:17px; color:#0f172a; }
    .tp-modal-close { background:none; border:none; cursor:pointer; font-size:22px; color:#94a3b8; padding:4px; line-height:1; transition:color .15s; }
    .tp-modal-close:hover { color:#334155; }
    .tp-modal-body { padding:16px 24px 24px; }
    .tp-modal-body .input-group { margin-bottom:12px; }
    .tp-modal-body .input-group span { display:block; font-size:13px; font-weight:600; color:#334155; margin-bottom:4px; }
    .tp-modal-body .input { width:100%; height:40px; border:1px solid #e2e8f0; border-radius:8px; padding:0 12px; font-size:14px; color:#1e293b; outline:none; transition:border-color .15s; box-sizing:border-box; }
    .tp-modal-body .input:focus { border-color:#6366f1; }
    .tp-modal-msg { padding:10px 14px; border-radius:8px; font-size:13px; margin-bottom:12px; display:none; }
    .tp-modal-msg.is-error { display:block; background:#fef2f2; color:#dc2626; border:1px solid #fecaca; }
    .tp-modal-msg.is-success { display:block; background:#f0fdf4; color:#15803d; border:1px solid #bbf7d0; }
    .pack-header-actions { display:flex; gap:8px; align-items:center; }
    .pack-header-actions .btn-sm { padding:6px 14px; font-size:12px; font-weight:600; border-radius:8px; cursor:pointer; border:1px solid #e2e8f0; background:#fff; color:#4f46e5; transition:all .15s; text-decoration:none; display:inline-flex; align-items:center; gap:4px; white-space:nowrap; }
    .pack-header-actions .btn-sm:hover { background:#eef2ff; border-color:#6366f1; }
    </style>
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('template_packs', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>模板与模块</h1><p>管理模板套件和自由组合网页模块。</p></div>
                <div class="topbar-actions">
                    <?php if ($activeTab === 'modules'): ?>
                        <a class="btn-primary" href="/admin/component/visual-edit.php">新增可视化模块</a>
                    <?php endif; ?>
                </div>
            </header>

            <?php if ($success !== ''): ?>
                <div class="page-card" style="border-left:4px solid #22c55e; margin-bottom:18px;">
                    <div class="card-head"><div><h2 style="color:#15803d;">操作成功</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; ?>

            <div class="tp-tabs">
                <a href="/admin/template-pack/list.php?tab=packs" class="<?php echo $activeTab === 'packs' ? 'is-active' : ''; ?>">套件管理</a>
                <a href="/admin/template-pack/list.php?tab=modules" class="<?php echo $activeTab === 'modules' ? 'is-active' : ''; ?>">模块管理</a>
            </div>

            <!-- ═══ Tab: 套件管理 ═══ -->
            <div class="tab-pane <?php echo $activeTab === 'packs' ? 'is-active' : ''; ?>">
                <?php
                    if ($packSubTab === 'page') { $displayPacks = $pagePacks; }
                    elseif ($packSubTab === 'standard') { $displayPacks = $standardPacks; }
                    else { $displayPacks = $variationPacks; }
                ?>
                <section class="page-card">
                    <div class="card-head" style="display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px;">
                        <div style="display:flex; align-items:center; gap:12px;">
                            <div class="pack-subtabs">
                            <a href="/admin/template-pack/list.php?tab=packs&pack_type=variation" class="<?php echo $packSubTab === 'variation' ? 'is-active' : ''; ?>">变体模板组件 (<?php echo count($variationPacks); ?>)</a>
                            <a href="/admin/template-pack/list.php?tab=packs&pack_type=standard" class="<?php echo $packSubTab === 'standard' ? 'is-active' : ''; ?>">常规模板组件 (<?php echo count($standardPacks); ?>)</a>
                            <a href="/admin/template-pack/list.php?tab=packs&pack_type=page" class="<?php echo $packSubTab === 'page' ? 'is-active' : ''; ?>">页面模板 (<?php echo count($pagePacks); ?>)</a>
                            </div>
                        </div>
                        <div class="pack-header-actions">
                            <button type="button" class="btn-sm" onclick="document.getElementById('modalCreate').classList.add('is-open')">➕ 新建套件</button>
                            <button type="button" class="btn-sm" onclick="document.getElementById('modalCreatePage').classList.add('is-open')">📄 新增页面模板</button>
                            <button type="button" class="btn-sm" onclick="document.getElementById('modalUpload').classList.add('is-open')">⬆ 上传套件</button>
                        </div>
                    </div>
                    <div class="pack-grid">
                        <?php if (empty($displayPacks)): ?>
                            <div style="text-align:center; padding:48px 24px; grid-column:1/-1;">
                                <div style="font-size:40px; margin-bottom:12px;">📦</div>
                                <p style="font-size:15px; color:#475569; margin:0 0 6px; font-weight:600;">暂无<?php echo $packSubTab === 'page' ? '页面' : ($packSubTab === 'standard' ? '常规' : '变体'); ?>模板<?php echo $packSubTab === 'page' ? '' : '组件'; ?></p>
                                <p style="font-size:13px; color:#94a3b8; margin:0 0 20px;"><?php echo $packSubTab === 'page' ? '页面模板用于发布独立页面（如关于我们、联系方式等），不绑定域名套件。' : '前往模板市场一键下载安装精美模板，或手动新建空白模板套件。'; ?></p>
                                <div style="display:flex; gap:10px; justify-content:center;">
                                    <?php if ($packSubTab === 'page'): ?>
                                    <button type="button" onclick="document.getElementById('modalCreatePage').classList.add('is-open')" style="display:inline-flex; align-items:center; gap:6px; padding:10px 22px; background:#4f46e5; color:#fff; border-radius:10px; font-size:13px; font-weight:600; cursor:pointer; transition:all .15s;">📄 新增页面模板</button>
                                    <?php else: ?>
                                    <a href="/admin/template-pack/market.php" style="display:inline-flex; align-items:center; gap:6px; padding:10px 22px; background:#4f46e5; color:#fff; border-radius:10px; font-size:13px; font-weight:600; text-decoration:none; transition:background .15s;">🛒 模板市场</a>
                                    <button type="button" onclick="document.getElementById('modalCreate').classList.add('is-open')" style="display:inline-flex; align-items:center; gap:6px; padding:10px 22px; background:#fff; color:#4f46e5; border:1px solid #e2e8f0; border-radius:10px; font-size:13px; font-weight:600; cursor:pointer; transition:all .15s;">➕ 新建套件</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php foreach ($displayPacks as $pack):
                            $code = isset($pack['code']) ? $pack['code'] : '';
                            $name = isset($pack['name']) ? $pack['name'] : $code;
                            $version = isset($pack['version']) ? $pack['version'] : '';
                            $desc = isset($pack['description']) ? $pack['description'] : '';
                            $curPackType = isset($pack['pack_type']) ? $pack['pack_type'] : 'variation';
                        ?>
                            <?php
                                // When template_pack is stored as "type:code" (e.g. "variation:deep-blue"),
                                // the code from manifest is just "deep-blue". Try both formats.
                                $prefixedCode = $curPackType . ':' . $code;
                                $usedDomains = isset($packDomainMap[$prefixedCode]) ? $packDomainMap[$prefixedCode] : (isset($packDomainMap[$code]) ? $packDomainMap[$code] : array());
                            ?>
                            <div class="pack-card <?php echo $curPackType === 'standard' ? 'pack-card--standard' : ($curPackType === 'page' ? 'pack-card--page' : ''); ?>">
                                <div class="pack-domain-tip">
                                    <?php if (empty($usedDomains)): ?>
                                        暂无域名使用此模板
                                    <?php else: ?>
                                        已使用域名（<?php echo count($usedDomains); ?>个）：<br>
                                        <?php echo e(implode('、', $usedDomains)); ?>
                                    <?php endif; ?>
                                </div>
                                <div class="pack-thumb">
                                    <div class="pack-thumb-letter"><?php echo e($name); ?></div>
                                </div>
                                <div class="pack-info">
                                    <h3><?php echo e($name); ?></h3>
                                    <div class="pack-code"><?php echo e($code); ?></div>
                                    <?php if ($desc !== ''): ?><p><?php echo e($desc); ?></p><?php endif; ?>
                                    <?php if ($version !== ''): ?><div class="pack-meta"><span>v<?php echo e($version); ?></span></div><?php endif; ?>
                                </div>
                                <div class="pack-actions">
                                    <?php $codeWithType = ($curPackType ? ($curPackType . ':' . $code) : $code); ?>
                                    <a class="btn-primary" href="/admin/template-pack/edit.php?code=<?php echo urlencode($codeWithType); ?>">编辑</a>
                                    <form method="post" action="/admin/template-pack/list.php?tab=packs&pack_type=<?php echo e($packSubTab); ?>" style="display:inline;" onsubmit="return confirm('确定要删除模板套件 <?php echo e($name); ?> 吗？此操作不可恢复。');">
                                        <?php echo csrf_field(); ?>
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="code" value="<?php echo e($code); ?>">
                                        <button class="btn-ghost" type="submit" style="color:#dc2626;">删除</button>
                                    </form>
                                </div>
                                <span class="pack-serial"><?php echo e(template_pack_serial_label(isset($pack['serial_no']) ? $pack['serial_no'] : 0, $curPackType)); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
            </div>

            <!-- ═══ Tab: 模块管理 ═══ -->
            <div class="tab-pane <?php echo $activeTab === 'modules' ? 'is-active' : ''; ?>">
                <section class="page-card">
                    <?php if ($deleteStatus === 'success'): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);"><strong style="color:#15803d;">删除成功</strong><p style="margin:0; color:#166534;">模块已删除。</p></div>
                    <?php elseif ($deleteStatus === 'error'): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">删除失败</strong><p style="margin:0; color:#b91c1c;">请稍后重试。</p></div>
                    <?php endif; ?>
                    <?php if ($dbError !== ''): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">数据库读取失败</strong><p style="margin:0; color:#b91c1c;"><?php echo e($dbError); ?></p></div>
                    <?php endif; ?>

                    <table class="data-table">
                        <thead><tr><th>ID</th><th>模块名称</th><th>类型</th><th>调用变量</th><th>组件数</th><th>适用域名</th><th>状态</th><th>更新时间</th><th>操作</th></tr></thead>
                        <tbody>
                        <?php if (!empty($modules)): ?>
                            <?php foreach ($modules as $item): ?>
                                <?php
                                    $domainLabel = '全局';
                                    if ((int)$item['domain_id'] > 0) {
                                        foreach ($domains as $d) {
                                            if ((int)$d['id'] === (int)$item['domain_id']) { $domainLabel = (string)$d['domain']; break; }
                                        }
                                    }
                                    $engine = isset($item['mod_engine']) ? (string)$item['mod_engine'] : 'legacy';
                                    $itemsArr = json_decode((string)$item['mod_items'], true);
                                    $widgetCount = $engine === 'grapesjs' ? '可视化' : (is_array($itemsArr) ? count($itemsArr) : 0);
                                    $varTag = '{{mod_' . e($item['mod_code']) . '}}';
                                    $editUrl = $engine === 'grapesjs' ? '/admin/component/visual-edit.php?id=' . (int)$item['id'] : '/admin/component/edit.php?id=' . (int)$item['id'];
                                ?>
                                <tr>
                                    <td><?php echo (int)$item['id']; ?></td>
                                    <td><strong><?php echo e($item['mod_name']); ?></strong></td>
                                    <td><span class="badge <?php echo $engine === 'grapesjs' ? 'success' : 'info'; ?>"><?php echo $engine === 'grapesjs' ? '可视化' : '旧版'; ?></span></td>
                                    <td><code style="background:#f1f5f9; padding:2px 8px; border-radius:4px; font-size:12px; color:#4f46e5;"><?php echo e($varTag); ?></code></td>
                                    <td><?php echo e((string)$widgetCount); ?><?php echo $engine === 'grapesjs' ? '' : ' 个'; ?></td>
                                    <td><?php echo e($domainLabel); ?></td>
                                    <td><span class="badge <?php echo $item['status'] === 'enabled' ? 'success' : 'info'; ?>"><?php echo e($item['status'] === 'enabled' ? '启用' : '停用'); ?></span></td>
                                    <td><?php echo e($item['updated_at']); ?></td>
                                    <td>
                                        <a href="<?php echo e($editUrl); ?>">编辑</a> /
                                        <form method="post" action="/admin/component/delete.php" style="display:inline;" onsubmit="return confirm('确认删除模块「<?php echo e($item['mod_name']); ?>」吗？');">
                                            <?php echo csrf_field(); ?>
                                            <input type="hidden" name="id" value="<?php echo (int)$item['id']; ?>">
                                            <button type="submit" class="link-btn" style="color:#dc2626;">删除</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9" class="empty-note"><?php echo $dbError === '' ? '暂无模块，点击「新增可视化模块」开始创建。' : '无法加载模块数据。'; ?></td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>

                    <div style="margin-top:24px; padding:20px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:10px;">
                        <h3 style="font-size:14px; font-weight:600; margin:0 0 8px; color:#334155;">可用基础组件</h3>
                        <div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:16px;">
                            <?php foreach ($widgetTypes as $wk => $wv): ?>
                                <span style="display:inline-flex; align-items:center; gap:4px; padding:4px 12px; background:#fff; border:1px solid #e2e8f0; border-radius:6px; font-size:13px;"><strong style="min-width:18px; text-align:center;"><?php echo $wv['icon']; ?></strong> <?php echo e($wv['label']); ?></span>
                            <?php endforeach; ?>
                        </div>
                        <h3 style="font-size:14px; font-weight:600; margin:0 0 8px; color:#334155;">使用方式</h3>
                        <p style="font-size:13px; color:#64748b; margin:0;">新增模块 → 添加组件并填写内容 → 保存后在模板中使用 <code>{{mod_编码}}</code> 调用。</p>
                    </div>
                </section>
            </div>

        </div>
    </main>
</div>
<!-- ═══ Modal: 新建套件 ═══ -->
<div class="tp-modal-overlay" id="modalCreate">
    <div class="tp-modal">
        <div class="tp-modal-head">
            <h2>新建套件</h2>
            <button type="button" class="tp-modal-close" onclick="closeModal('modalCreate')">&times;</button>
        </div>
        <div class="tp-modal-body">
            <div class="tp-modal-msg" id="createMsg"></div>
            <form id="formCreate" onsubmit="return submitCreate(event)">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="create">
                <div class="input-group">
                    <span>套件类型</span>
                    <div style="display:flex; gap:10px; margin-top:2px;">
                        <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer; font-size:13px; color:#334155; padding:5px 12px; border:1px solid #e2e8f0; border-radius:7px;">
                            <input type="radio" name="pack_type" value="variation"<?php echo $packSubTab === 'variation' ? ' checked' : ''; ?> style="accent-color:#6366f1;"> 变体
                        </label>
                        <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer; font-size:13px; color:#334155; padding:5px 12px; border:1px solid #e2e8f0; border-radius:7px;">
                            <input type="radio" name="pack_type" value="standard"<?php echo $packSubTab === 'standard' ? ' checked' : ''; ?> style="accent-color:#64748b;"> 常规
                        </label>
                    </div>
                    <div style="font-size:11px; color:#94a3b8; margin-top:3px;">变体：CSS变量适配变异引擎 | 常规：CSS写死固定外观</div>
                </div>
                <div class="input-group">
                    <span>编码（英文）</span>
                    <input class="input" type="text" name="code" placeholder="如 news-portal" pattern="[a-z0-9][a-z0-9\-]*" required>
                </div>
                <div class="input-group">
                    <span>套件名称</span>
                    <input class="input" type="text" name="name" placeholder="如 新闻门户风格" required>
                </div>
                <div class="input-group">
                    <span>描述</span>
                    <input class="input" type="text" name="description" placeholder="简要说明模板用途和风格">
                </div>
                <button class="btn-primary" type="submit" id="btnCreate" style="margin-top:4px; width:100%;">创建</button>
            </form>
        </div>
    </div>
</div>

<!-- ═══ Modal: 新增页面模板 ═══ -->
<div class="tp-modal-overlay" id="modalCreatePage">
    <div class="tp-modal">
        <div class="tp-modal-head">
            <h2>📄 新增页面模板</h2>
            <button type="button" class="tp-modal-close" onclick="closeModal('modalCreatePage')">&times;</button>
        </div>
        <div class="tp-modal-body">
            <div style="font-size:12px; color:#64748b; background:#faf5ff; border:1px solid #e9d5ff; padding:10px 14px; border-radius:8px; margin-bottom:14px; line-height:1.6;">
                页面模板用于发布独立页面（如关于我们、联系方式、隐私政策等）。<br>
                不绑定域名套件，不参与批量建站，仅在手动发布文章时可选。
            </div>
            <div class="tp-modal-msg" id="createPageMsg"></div>
            <form id="formCreatePage" onsubmit="return submitCreatePage(event)">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="create">
                <input type="hidden" name="pack_type" value="page">
                <div class="input-group">
                    <span>编码（英文）</span>
                    <input class="input" type="text" name="code" placeholder="如 about-us" pattern="[a-z0-9][a-z0-9\-]*" required>
                </div>
                <div class="input-group">
                    <span>模板名称</span>
                    <input class="input" type="text" name="name" placeholder="如 关于我们" required>
                </div>
                <div class="input-group">
                    <span>描述</span>
                    <input class="input" type="text" name="description" placeholder="简要说明页面用途">
                </div>
                <button class="btn-primary" type="submit" id="btnCreatePage" style="margin-top:4px; width:100%; background:#9333ea;">创建页面模板</button>
            </form>
        </div>
    </div>
</div>

<!-- ═══ Modal: 上传套件 ═══ -->
<div class="tp-modal-overlay" id="modalUpload">
    <div class="tp-modal">
        <div class="tp-modal-head">
            <h2>上传套件</h2>
            <button type="button" class="tp-modal-close" onclick="closeModal('modalUpload')">&times;</button>
        </div>
        <div class="tp-modal-body">
            <div class="tp-modal-msg" id="uploadMsg"></div>
            <form id="formUpload" onsubmit="return submitUpload(event)" enctype="multipart/form-data">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="action" value="upload">
                <div class="input-group">
                    <span>套件类型</span>
                    <div style="display:flex; gap:10px; margin-top:2px;">
                        <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer; font-size:13px; color:#334155; padding:5px 12px; border:1px solid #e2e8f0; border-radius:7px;">
                            <input type="radio" name="upload_pack_type" value="variation"<?php echo $packSubTab === 'variation' ? ' checked' : ''; ?> style="accent-color:#6366f1;" onchange="updateUploadDocLink()"> 变体
                        </label>
                        <label style="display:inline-flex; align-items:center; gap:5px; cursor:pointer; font-size:13px; color:#334155; padding:5px 12px; border:1px solid #e2e8f0; border-radius:7px;">
                            <input type="radio" name="upload_pack_type" value="standard"<?php echo $packSubTab === 'standard' ? ' checked' : ''; ?> style="accent-color:#64748b;" onchange="updateUploadDocLink()"> 常规
                        </label>
                    </div>
                    <div style="font-size:11px; color:#94a3b8; margin-top:3px;">变体：CSS变量适配变异引擎，自动换色换风格 | 常规：CSS写死固定外观</div>
                </div>
                <div class="input-group">
                    <span>ZIP 压缩包</span>
                    <input class="input" type="file" name="zip_file" accept=".zip" required style="padding:8px 12px; height:auto;">
                    <div style="font-size:11px; color:#94a3b8; margin-top:3px;">ZIP 内须包含 manifest.json 及必需模板文件，最大 50MB</div>
                </div>
                <button class="btn-primary" type="submit" id="btnUpload" style="margin-top:4px; width:100%;">上传并安装</button>
            </form>
            <p style="margin-top:12px; font-size:12px; color:#94a3b8; line-height:1.5;" id="uploadDocLink">不清楚如何制作模板？请参阅
                <a href="/document/<?php echo $packSubTab === 'standard' ? '常规' : '变体'; ?>模板组件制作规范.html" target="_blank" style="color:#4f46e5; text-decoration:none; font-weight:500;" id="uploadDocAnchor"><?php echo $packSubTab === 'standard' ? '常规' : '变体'; ?>模板制作规范</a>
            </p>
        </div>
    </div>
</div>

<script src="/assets/js/admin-ui.js"></script>
<script>
function closeModal(id) {
    document.getElementById(id).classList.remove('is-open');
}
// 点击遮罩关闭
document.querySelectorAll('.tp-modal-overlay').forEach(function(el) {
    el.addEventListener('click', function(e) {
        if (e.target === el) closeModal(el.id);
    });
});
// ESC 关闭
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.tp-modal-overlay.is-open').forEach(function(el) { closeModal(el.id); });
    }
});

function submitCreate(e) {
    e.preventDefault();
    var form = document.getElementById('formCreate');
    var msg = document.getElementById('createMsg');
    var btn = document.getElementById('btnCreate');
    msg.className = 'tp-modal-msg'; msg.textContent = '';
    btn.disabled = true; btn.textContent = '创建中…';
    var fd = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/template-pack/list.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) return;
        btn.disabled = false; btn.textContent = '创建';
        // 解析返回的HTML页面判断成功还是失败
        var html = xhr.responseText || '';
        if (html.indexOf('创建成功') !== -1) {
            msg.className = 'tp-modal-msg is-success';
            msg.textContent = '套件创建成功，正在刷新…';
            setTimeout(function() { location.href = '/admin/template-pack/list.php?tab=packs&pack_type=<?php echo e($packSubTab); ?>'; }, 600);
        } else {
            // 尝试提取错误信息
            var m = html.match(/class="card-head"[^>]*>[\s\S]*?<p>([\s\S]*?)<\/p>/);
            var errText = m ? m[1].replace(/<[^>]+>/g, '').trim() : '创建失败，请检查编码和名称是否重复。';
            msg.className = 'tp-modal-msg is-error';
            msg.textContent = errText;
        }
    };
    xhr.send(fd);
    return false;
}

function submitCreatePage(e) {
    e.preventDefault();
    var form = document.getElementById('formCreatePage');
    var msg = document.getElementById('createPageMsg');
    var btn = document.getElementById('btnCreatePage');
    msg.className = 'tp-modal-msg'; msg.textContent = '';
    btn.disabled = true; btn.textContent = '创建中…';
    var fd = new FormData(form);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/template-pack/list.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) return;
        btn.disabled = false; btn.textContent = '创建页面模板';
        var html = xhr.responseText || '';
        if (html.indexOf('创建成功') !== -1) {
            msg.className = 'tp-modal-msg is-success';
            msg.textContent = '页面模板创建成功，正在刷新…';
            setTimeout(function() { location.href = '/admin/template-pack/list.php?tab=packs&pack_type=page'; }, 600);
        } else {
            var m = html.match(/class="card-head"[^>]*>[\s\S]*?<p>([\s\S]*?)<\/p>/);
            var errText = m ? m[1].replace(/<[^>]+>/g, '').trim() : '创建失败，请检查编码和名称是否重复。';
            msg.className = 'tp-modal-msg is-error';
            msg.textContent = errText;
        }
    };
    xhr.send(fd);
    return false;
}

function updateUploadDocLink() {
    var radios = document.getElementsByName('upload_pack_type');
    var val = 'variation';
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) { val = radios[i].value; break; }
    }
    var label = val === 'standard' ? '常规' : '变体';
    var anchor = document.getElementById('uploadDocAnchor');
    if (anchor) {
        anchor.href = '/document/' + label + '模板组件制作规范.html';
        anchor.textContent = label + '模板制作规范';
    }
}

function submitUpload(e) {
    e.preventDefault();
    var form = document.getElementById('formUpload');
    var msg = document.getElementById('uploadMsg');
    var btn = document.getElementById('btnUpload');
    msg.className = 'tp-modal-msg'; msg.textContent = '';
    btn.disabled = true; btn.textContent = '上传中…';
    var fd = new FormData(form);
    // 获取选中的套件类型，用于上传后跳转到对应分类
    var uploadType = 'variation';
    var radios = document.getElementsByName('upload_pack_type');
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) { uploadType = radios[i].value; break; }
    }
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/admin/template-pack/list.php', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState !== 4) return;
        btn.disabled = false; btn.textContent = '上传并安装';
        var html = xhr.responseText || '';
        if (html.indexOf('上传成功') !== -1 || html.indexOf('安装成功') !== -1 || html.indexOf('已覆盖更新') !== -1) {
            msg.className = 'tp-modal-msg is-success';
            msg.textContent = '套件上传成功，正在刷新…';
            setTimeout(function() { location.href = '/admin/template-pack/list.php?tab=packs&pack_type=' + uploadType; }, 600);
        } else {
            var m = html.match(/class="card-head"[^>]*>[\s\S]*?<p>([\s\S]*?)<\/p>/);
            var errText = m ? m[1].replace(/<[^>]+>/g, '').trim() : '上传失败，请检查 ZIP 文件格式。';
            msg.className = 'tp-modal-msg is-error';
            msg.textContent = errText;
        }
    };
    xhr.send(fd);
    return false;
}
</script>
</body>
</html>
