<?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));

$keyword = isset($_GET['keyword']) ? trim((string)$_GET['keyword']) : '';
$status = isset($_GET['status']) ? trim((string)$_GET['status']) : '';
$group = isset($_GET['group']) ? trim((string)$_GET['group']) : '';
$deleteStatus = isset($_GET['delete_status']) ? trim((string)$_GET['delete_status']) : '';
$deletedDomain = isset($_GET['deleted_domain']) ? trim((string)$_GET['deleted_domain']) : '';
$publishStatus = isset($_GET['publish_status']) ? trim((string)$_GET['publish_status']) : '';
$publishedDomain = isset($_GET['published_domain']) ? trim((string)$_GET['published_domain']) : '';
$publishedCount = isset($_GET['published_count']) ? (int)$_GET['published_count'] : 0;
$publishMessage = isset($_GET['publish_message']) ? trim((string)$_GET['publish_message']) : '';
$checkStatus = isset($_GET['check_status']) ? trim((string)$_GET['check_status']) : '';
$checkedDomain = isset($_GET['checked_domain']) ? trim((string)$_GET['checked_domain']) : '';
$checkedRoot = isset($_GET['checked_root']) ? trim((string)$_GET['checked_root']) : '';
$checkMessage = isset($_GET['check_message']) ? trim((string)$_GET['check_message']) : '';

$dbError = '';
$filteredDomains = array();

try {
    ensure_domains_table_has_site_root();
    ensure_domains_table_has_template_pack();
    $pdo = db_connection();
    $sql = 'SELECT id, domain, site_name, site_root, group_name, template_name, template_pack, status, remark, created_at, updated_at FROM domains WHERE user_id = :uid';
    $params = array(':uid' => current_user_id());

    if ($keyword !== '') {
        $sql .= ' AND (domain LIKE :kw1 OR site_name LIKE :kw2 OR template_name LIKE :kw3)';
        $params[':kw1'] = '%' . $keyword . '%';
        $params[':kw2'] = '%' . $keyword . '%';
        $params[':kw3'] = '%' . $keyword . '%';
    }

    if ($status !== '' && $status !== 'all') {
        $sql .= ' AND status = :status';
        $params[':status'] = $status;
    }

    if ($group !== '' && $group !== 'all') {
        $sql .= ' AND group_name = :group_name';
        $params[':group_name'] = $group;
    }

    $sql .= ' ORDER BY id DESC';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $filteredDomains = $stmt->fetchAll();
} catch (Exception $e) {
    $dbError = $e->getMessage();
}

$homepageDomainIds = array();
try {
    $homepageDomainIds = list_domain_ids_with_published_homepage();
} catch (Exception $e) {}

usort($filteredDomains, function($a, $b) use ($homepageDomainIds) {
    $aHas = isset($homepageDomainIds[(int)$a['id']]) ? 1 : 0;
    $bHas = isset($homepageDomainIds[(int)$b['id']]) ? 1 : 0;
    if ($aHas !== $bHas) return $bHas - $aHas;
    return (int)$b['id'] - (int)$a['id'];
});

$statusOptions = domain_status_options();
$groups = list_domain_groups();
?><!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">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('domains', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1>域名管理</h1><p>支持域名分组、站点状态、模板绑定和基础筛选。</p></div>
                <div class="topbar-actions"><button class="btn-ghost btn-batch-delete" type="button" id="btnBatchDelete" style="display:none;color:#dc2626;border-color:rgba(220,38,38,.3);">删除选中 (<span id="batchCount">0</span>)</button><button class="btn-ghost" type="button">批量导入</button><button class="btn-soft" type="button" id="btnPrefixGen">批量域名前缀</button><a class="btn-primary" href="/admin/domain/add.php">新增域名</a></div>
            </header>
            <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;"><?php echo e($deletedDomain); ?> 已删除。</p>
                    </div>
                <?php elseif ($deleteStatus === 'missing'): ?>
                    <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 elseif ($deleteStatus === 'invalid'): ?>
                    <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;">缺少有效的域名ID，无法删除。</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 ($publishStatus === '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;">域名 <?php echo e($publishedDomain); ?> 已完成静态发布，共处理 <?php echo (int)$publishedCount; ?> 个已发布页面。</p>
                    </div>
                <?php elseif ($publishStatus === 'missing'): ?>
                    <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 elseif ($publishStatus === '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;"><?php echo e($publishMessage !== '' ? $publishMessage : '请稍后重试。'); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($checkStatus === '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;">域名 <?php echo e($checkedDomain); ?> 的站点目录 `<?php echo e($checkedRoot); ?>` 可正常写入。<?php echo e($checkMessage); ?></p>
                    </div>
                <?php elseif ($checkStatus === 'missing'): ?>
                    <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 elseif ($checkStatus === '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;"><?php echo e($checkMessage !== '' ? $checkMessage : '请检查站点根目录配置。'); ?><?php echo $checkedRoot !== '' ? ' 当前目录：' . e($checkedRoot) : ''; ?></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>
                        <p style="margin:8px 0 0; color:#7f1d1d;">请先导入 `database/domains.sql`，并检查 `app/config.php` 中的数据库账号密码。</p>
                    </div>
                <?php endif; ?>
                <form class="filter-row" method="get" action="/admin/domain/list.php">
                    <input class="input" type="text" name="keyword" value="<?php echo e($keyword); ?>" placeholder="搜索域名 / 站点名称 / 模板名">
                    <select class="select" name="status">
                        <option value="all"<?php echo ($status === '' || $status === 'all') ? ' selected' : ''; ?>>全部状态</option>
                        <option value="enabled"<?php echo $status === 'enabled' ? ' selected' : ''; ?>>启用</option>
                        <option value="disabled"<?php echo $status === 'disabled' ? ' selected' : ''; ?>>停用</option>
                        <option value="pending"<?php echo $status === 'pending' ? ' selected' : ''; ?>>待审核</option>
                    </select>
                    <select class="select" name="group">
                        <option value="all"<?php echo ($group === '' || $group === 'all') ? ' selected' : ''; ?>>全部分组</option>
                        <?php foreach ($groups as $g): ?>
                            <option value="<?php echo e($g); ?>"<?php echo $group === $g ? ' selected' : ''; ?>><?php echo e($g); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button class="btn-soft" type="submit">搜索</button>
                    <a class="btn-ghost" href="/admin/domain/list.php">重置</a>
                </form>
                <form id="batchDeleteForm" method="post" action="/admin/domain/delete.php">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="batch" value="1">
                <table class="data-table">
                    <thead><tr><th style="width:40px;text-align:center;"><input type="checkbox" id="checkAll" title="全选/取消全选"></th><th>域名</th><th>站点名称</th><th>站点目录</th><th>分组</th><th>默认模板</th><th>变异</th><th>状态</th><th>更新时间</th><th>操作</th></tr></thead>
                    <tbody>
                    <?php if (!empty($filteredDomains)): ?>
                        <?php foreach ($filteredDomains as $item): ?>
                            <tr>
                                <td style="text-align:center;"><input type="checkbox" class="domain-check" name="ids[]" value="<?php echo (int)$item['id']; ?>" data-domain="<?php echo e($item['domain']); ?>"></td>
                                <td><a href="https://<?php echo e($item['domain']); ?>/" target="_blank" title="预览站点" style="color:#4f46e5;text-decoration:none;"><?php echo e($item['domain']); ?> <span style="font-size:11px;opacity:.5;">↗</span></a><?php if (isset($homepageDomainIds[(int)$item['id']])): ?> <span style="display:inline-block;font-size:11px;padding:1px 6px;border-radius:4px;background:rgba(34,197,94,.1);color:#15803d;font-weight:600;vertical-align:middle;">首页已生成</span><?php endif; ?></td>
                                <td><?php echo e($item['site_name']); ?></td>
                                <td><?php echo e(default_shared_site_root()); ?><div style="font-size:12px; color:#94a3b8;">系统自动识别共享站点目录</div></td>
                                <td><?php echo e($item['group_name']); ?></td>
                                <td><?php
                                    $tpCode = isset($item['template_pack']) && $item['template_pack'] !== '' ? $item['template_pack'] : '';
                                    if ($tpCode !== '') {
                                        $tpManifest = load_template_pack_manifest($tpCode);
                                        $tpDisplayName = $tpManifest ? (isset($tpManifest['name']) ? $tpManifest['name'] : $tpCode) : $tpCode;
                                        echo e($tpDisplayName);
                                        $tpType = $tpManifest && isset($tpManifest['pack_type']) ? $tpManifest['pack_type'] : '';
                                        if ($tpType === '') {
                                            $tpType = (strpos($tpCode, 'standard:') === 0) ? 'standard' : ((strpos($tpCode, 'variation:') === 0) ? 'variation' : '');
                                        }
                                        if ($tpType !== '') {
                                            echo ' <span style="font-size:11px;padding:1px 6px;border-radius:3px;background:' . ($tpType === 'standard' ? '#f0fdf4;color:#166534' : '#eef2ff;color:#4338ca') . ';">' . ($tpType === 'standard' ? '常规' : '变体') . '</span>';
                                        }
                                    } else {
                                        echo e(isset($item['template_name']) ? $item['template_name'] : '-');
                                    }
                                ?></td>
                                <td><?php
                                    if ($tpType === 'variation' && function_exists('variation_class_prefix')) {
                                        $vPrefix = variation_class_prefix((int)$item['id']);
                                        $vColorIdx = variation_pick((int)$item['id'], 'color', count(variation_color_schemes()));
                                        $vColors = variation_color_schemes();
                                        $vPrimary = isset($vColors[$vColorIdx]['--v-primary']) ? $vColors[$vColorIdx]['--v-primary'] : '#6366f1';
                                        echo '<span style="display:inline-block;width:14px;height:14px;border-radius:4px;background:' . e($vPrimary) . ';vertical-align:middle;margin-right:4px;border:1px solid rgba(0,0,0,.08);"></span>';
                                        echo '<span style="font-family:monospace;font-size:12px;color:#64748b;">' . e($vPrefix) . '</span>';
                                    } else {
                                        echo '-';
                                    }
                                ?></td>
                                <td><span class="badge <?php echo e(domain_badge_class($item['status'])); ?>"><?php echo e(isset($statusOptions[$item['status']]) ? $statusOptions[$item['status']] : $item['status']); ?></span></td>
                                <td><?php echo e($item['updated_at']); ?></td>
                                <td><a href="/admin/domain/edit.php?id=<?php echo (int)$item['id']; ?>">编辑</a> / <a href="/admin/domain/site-check.php?id=<?php echo (int)$item['id']; ?>">检测目录</a> / <a href="javascript:void(0);" onclick="startDomainBatchPublish(<?php echo (int)$item['id']; ?>, '<?php echo e($item['domain']); ?>');">全量静态发布</a> / <form method="post" action="/admin/domain/delete.php" style="display:inline;" onsubmit="return confirm('确认删除域名 <?php echo e($item['domain']); ?> 吗？');"><?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="10" class="empty-note"><?php echo $dbError === '' ? '没有匹配到域名数据，请调整筛选条件后重试。' : '暂无可展示数据。'; ?></td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
                </form>
                <div class="table-note">勾选域名后可批量删除；当前共 <?php echo count($filteredDomains); ?> 条记录。</div>
            </section>
        </div>
    </main>
</div>
<!-- 批量域名前缀生成弹窗 -->
<div id="prefixModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(15,23,42,.45);backdrop-filter:blur(4px);align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:16px;box-shadow:0 20px 60px rgba(15,23,42,.18);width:620px;max-width:94vw;max-height:90vh;overflow-y:auto;padding:0;">
        <div style="padding:24px 28px 0;">
            <div style="display:flex;justify-content:space-between;align-items:center;">
                <h2 style="margin:0;font-size:18px;color:#1e293b;">批量生成二级域名前缀</h2>
                <button type="button" id="prefixClose" style="background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;padding:4px 8px;line-height:1;">&times;</button>
            </div>
            <p style="margin:6px 0 18px;font-size:13px;color:#64748b;">自动生成不重复的二级域名前缀，结果可一键导入到新增域名页面。</p>
        </div>
        <div style="padding:0 28px 24px;">
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;">
                <div class="input-group" style="grid-column:1/-1;">
                    <span>根域名</span>
                    <input class="input" type="text" id="pfRootDomain" placeholder="例如：domain.cn" value="">
                </div>
                <div class="input-group">
                    <span>前缀组合</span>
                    <select class="select" id="pfCharset">
                        <option value="alpha">纯字母 (a-z)</option>
                        <option value="num">纯数字 (0-9)</option>
                        <option value="alnum" selected>数字+字母</option>
                    </select>
                </div>
                <div class="input-group">
                    <span>前缀字符数</span>
                    <input class="input" type="number" id="pfLength" min="1" max="8" value="3">
                </div>
                <div class="input-group">
                    <span>生成数量</span>
                    <input class="input" type="number" id="pfCount" min="1" max="5000" value="100">
                </div>
                <div class="input-group">
                    <span>排除已有域名</span>
                    <select class="select" id="pfDedup">
                        <option value="1" selected>自动去重（排除数据库已有）</option>
                        <option value="0">不排除</option>
                    </select>
                </div>
            </div>
            <div style="margin-top:16px;display:flex;gap:10px;">
                <button class="btn-primary" type="button" id="pfGenBtn">生成</button>
                <button class="btn-soft" type="button" id="pfCopyBtn" style="display:none;">复制到剪贴板</button>
                <button class="btn-primary" type="button" id="pfImportBtn" style="display:none;">导入到新增页面</button>
            </div>
            <div id="pfResult" style="display:none;margin-top:16px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                    <span style="font-weight:600;font-size:14px;color:#1e293b;">生成结果 <span id="pfResultCount" style="font-weight:400;color:#6b7280;"></span></span>
                </div>
                <textarea class="input" id="pfResultText" rows="10" readonly style="font-family:monospace;font-size:13px;line-height:1.6;resize:vertical;background:#f8fafc;"></textarea>
            </div>
        </div>
    </div>
</div>

<script>
(function(){
    var checkAll = document.getElementById('checkAll');
    var boxes = document.querySelectorAll('.domain-check');
    var btn = document.getElementById('btnBatchDelete');
    var countEl = document.getElementById('batchCount');
    var form = document.getElementById('batchDeleteForm');
    function updateBtn(){
        var checked = document.querySelectorAll('.domain-check:checked');
        var n = checked.length;
        countEl.textContent = n;
        btn.style.display = n > 0 ? '' : 'none';
        if(boxes.length > 0){
            checkAll.checked = (n === boxes.length);
            checkAll.indeterminate = (n > 0 && n < boxes.length);
        }
    }
    if(checkAll){
        checkAll.addEventListener('change', function(){
            boxes.forEach(function(b){ b.checked = checkAll.checked; });
            updateBtn();
        });
    }
    boxes.forEach(function(b){
        b.addEventListener('change', updateBtn);
    });
    if(btn){
        btn.addEventListener('click', function(){
            var checked = document.querySelectorAll('.domain-check:checked');
            var names = [];
            checked.forEach(function(b){ names.push(b.getAttribute('data-domain')); });
            var msg = '确认删除以下 ' + names.length + ' 个域名吗？\n\n' + names.join('\n') + '\n\n此操作不可撤销！';
            if(confirm(msg)){
                form.submit();
            }
        });
    }
})();

// 批量域名前缀生成器
(function(){
    var modal = document.getElementById('prefixModal');
    var openBtn = document.getElementById('btnPrefixGen');
    var closeBtn = document.getElementById('prefixClose');
    var genBtn = document.getElementById('pfGenBtn');
    var copyBtn = document.getElementById('pfCopyBtn');
    var importBtn = document.getElementById('pfImportBtn');
    var resultWrap = document.getElementById('pfResult');
    var resultText = document.getElementById('pfResultText');
    var resultCount = document.getElementById('pfResultCount');

    var existingDomains = <?php echo json_encode(array_map(function($d){ return strtolower($d['domain']); }, $filteredDomains), JSON_UNESCAPED_UNICODE); ?>;

    openBtn.addEventListener('click', function(){
        modal.style.display = 'flex';
        // 自动填入最常用的根域名
        if(!document.getElementById('pfRootDomain').value && existingDomains.length > 0){
            var parts = existingDomains[0].split('.');
            if(parts.length >= 3) document.getElementById('pfRootDomain').value = parts.slice(-2).join('.');
            else document.getElementById('pfRootDomain').value = existingDomains[0];
        }
    });
    closeBtn.addEventListener('click', function(){ modal.style.display = 'none'; });
    modal.addEventListener('click', function(e){ if(e.target === modal) modal.style.display = 'none'; });

    function genPrefix(charset, len){
        var chars = '';
        if(charset === 'alpha') chars = 'abcdefghijklmnopqrstuvwxyz';
        else if(charset === 'num') chars = '0123456789';
        else chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        var s = '';
        // 首字符避免纯数字开头（DNS兼容）
        var firstChars = charset === 'num' ? chars : chars.replace(/[0-9]/g,'');
        if(firstChars === '') firstChars = chars;
        s += firstChars.charAt(Math.floor(Math.random() * firstChars.length));
        for(var i = 1; i < len; i++){
            s += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return s;
    }

    genBtn.addEventListener('click', function(){
        var root = document.getElementById('pfRootDomain').value.trim().toLowerCase();
        var charset = document.getElementById('pfCharset').value;
        var len = parseInt(document.getElementById('pfLength').value, 10);
        var count = parseInt(document.getElementById('pfCount').value, 10);
        var dedup = document.getElementById('pfDedup').value === '1';

        if(!root){ alert('请输入根域名'); return; }
        if(len < 1 || len > 8){ alert('前缀字符数请设置 1-8'); return; }
        if(count < 1 || count > 5000){ alert('生成数量请设置 1-5000'); return; }

        // 计算最大可能组合数
        var poolSize = charset === 'alpha' ? 26 : (charset === 'num' ? 10 : 36);
        var maxCombos = Math.pow(poolSize, len);
        if(count > maxCombos * 0.7){
            alert('组合空间不足！' + len + '位' + (charset === 'alpha'?'纯字母':charset === 'num'?'纯数字':'数字+字母') + '最多约 ' + maxCombos + ' 种组合，请增加字符数或减少数量。');
            return;
        }

        var existSet = {};
        if(dedup){
            existingDomains.forEach(function(d){ existSet[d] = true; });
        }

        var generated = {};
        var results = [];
        var maxAttempts = count * 20;
        var attempts = 0;

        while(results.length < count && attempts < maxAttempts){
            attempts++;
            var prefix = genPrefix(charset, len);
            var domain = prefix + '.' + root;
            if(generated[domain]) continue;
            if(dedup && existSet[domain]) continue;
            generated[domain] = true;
            results.push(domain);
        }

        if(results.length < count){
            alert('仅生成 ' + results.length + ' 个（去重后可用组合不足）');
        }

        resultText.value = results.join('\n');
        resultCount.textContent = '（共 ' + results.length + ' 个）';
        resultWrap.style.display = '';
        copyBtn.style.display = '';
        importBtn.style.display = '';
    });

    copyBtn.addEventListener('click', function(){
        if(navigator.clipboard){
            navigator.clipboard.writeText(resultText.value).then(function(){
                copyBtn.textContent = '已复制！';
                setTimeout(function(){ copyBtn.textContent = '复制到剪贴板'; }, 1500);
            });
        } else {
            resultText.select();
            document.execCommand('copy');
            copyBtn.textContent = '已复制！';
            setTimeout(function(){ copyBtn.textContent = '复制到剪贴板'; }, 1500);
        }
    });

    importBtn.addEventListener('click', function(){
        var domains = resultText.value.trim();
        if(!domains){ alert('请先生成域名'); return; }
        try { localStorage.setItem('prefill_domains', domains); } catch(e){}
        window.location.href = '/admin/domain/add.php?prefill=1';
    });
})();
</script>
<!-- 域名全量静态发布进度弹窗 -->
<div id="domainBatchModal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; z-index:99999; background:rgba(0,0,0,0.45);">
    <div style="position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:#fff; border-radius:16px; padding:32px 36px; width:560px; max-width:92vw; box-shadow:0 20px 60px rgba(0,0,0,0.18); z-index:100000;">
        <h3 id="domainBatchTitle" style="margin:0 0 6px; font-size:18px; color:#1e293b;">域名全量静态发布</h3>
        <p id="domainBatchStatus" style="margin:0 0 18px; font-size:14px; color:#64748b;">准备中...</p>
        <div style="background:#f1f5f9; border-radius:8px; height:10px; overflow:hidden; margin-bottom:10px;">
            <div id="domainBatchBar" style="height:100%; width:0%; background:linear-gradient(90deg,#6366f1,#818cf8); border-radius:8px; transition:width 0.3s;"></div>
        </div>
        <div style="display:flex; justify-content:space-between; font-size:13px; color:#94a3b8; margin-bottom:16px;">
            <span id="domainBatchLabel">0 / 0</span>
            <span id="domainBatchPercent">0%</span>
        </div>
        <div id="domainBatchLog" style="max-height:180px; overflow-y:auto; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:10px 14px; font-size:12.5px; line-height:1.7; color:#475569; margin-bottom:18px;"></div>
        <div style="display:flex; gap:10px; justify-content:flex-end;">
            <button id="domainBatchCancel" class="btn-ghost" type="button" onclick="cancelDomainBatchPublish()">取消</button>
            <button id="domainBatchClose" class="btn-soft" type="button" onclick="closeDomainBatchPublish()" style="display:none;">关闭</button>
        </div>
    </div>
</div>
<script>
(function(){
    var _abort = false;
    var CSRF = '<?php echo e(csrf_token()); ?>';
    function $(id){ return document.getElementById(id); }
    function addLog(msg, isErr){
        var d = document.createElement('div');
        d.textContent = msg;
        if (isErr) d.style.color = '#dc2626';
        var w = $('domainBatchLog');
        w.appendChild(d);
        w.scrollTop = w.scrollHeight;
    }
    function setProgress(done, total){
        var p = total > 0 ? Math.round(done / total * 100) : 0;
        $('domainBatchBar').style.width = p + '%';
        $('domainBatchLabel').textContent = done + ' / ' + total;
        $('domainBatchPercent').textContent = p + '%';
    }
    function finishWith(text, color){
        $('domainBatchStatus').textContent = text;
        $('domainBatchStatus').style.color = color || '#16a34a';
        $('domainBatchCancel').style.display = 'none';
        $('domainBatchClose').style.display = '';
    }

    window.startDomainBatchPublish = function(domainId, domainName){
        if (!confirm('确认对域名 ' + domainName + ' 执行全量静态发布吗？\n（包含全部已发布文章 + 栏目页 / 标签页 / 文章聚合页）')) return;
        _abort = false;
        $('domainBatchModal').style.display = 'block';
        $('domainBatchTitle').textContent = '全量静态发布 - ' + domainName;
        $('domainBatchStatus').textContent = '正在加载内容列表...';
        $('domainBatchStatus').style.color = '#64748b';
        $('domainBatchBar').style.width = '0%';
        $('domainBatchLabel').textContent = '0 / 0';
        $('domainBatchPercent').textContent = '0%';
        $('domainBatchLog').innerHTML = '';
        $('domainBatchCancel').style.display = '';
        $('domainBatchClose').style.display = 'none';

        var fd = new FormData();
        fd.append('domain_id', domainId);
        fd.append('_csrf_token', CSRF);
        fetch('/admin/api/domain-publish-init.php', { method: 'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(data){
                if (!data.success) {
                    finishWith('初始化失败：' + (data.message || '未知错误'), '#dc2626');
                    return;
                }
                var ids = data.content_ids || [];
                addLog('域名 ' + domainName + ' 共 ' + ids.length + ' 篇已发布文章待静态化');
                if (ids.length === 0) {
                    addLog('（无文章，跳过文章阶段）');
                    runArchivePhase(domainId, domainName, 0);
                    return;
                }
                runArticlePhase(domainId, domainName, ids);
            })
            .catch(function(e){
                finishWith('初始化请求异常：' + e.message, '#dc2626');
            });
    };

    function runArticlePhase(domainId, domainName, ids){
        var total = ids.length;
        $('domainBatchStatus').textContent = '正在静态化文章页（共 ' + total + ' 篇），请勿关闭页面...';

        var done = 0, ok = 0, fail = 0;
        var CHUNK_SIZE = 10, PARALLEL = 3, DISPLAY_INTERVAL = 80;
        var chunks = [];
        for (var i = 0; i < ids.length; i += CHUNK_SIZE) chunks.push(ids.slice(i, i + CHUNK_SIZE));
        var cursor = 0, active = 0, queue = [], drainTimer = null, fetchDone = false;

        function drain(){
            if (queue.length === 0) {
                drainTimer = null;
                if (fetchDone || _abort) afterArticle();
                return;
            }
            var item = queue.shift();
            done++;
            if (item.success) {
                ok++;
                addLog('[' + done + '/' + total + '] ID:' + item.id + ' ' + (item.title || '') + ' ✓');
            } else {
                fail++;
                addLog('[' + done + '/' + total + '] ID:' + item.id + ' 失败: ' + (item.message || '未知错误'), true);
            }
            setProgress(done, total);
            if (done >= total || (_abort && active <= 0 && queue.length === 0)) {
                afterArticle();
                return;
            }
            drainTimer = setTimeout(drain, DISPLAY_INTERVAL);
        }
        function startDrain(){
            if (!drainTimer && queue.length > 0) drainTimer = setTimeout(drain, DISPLAY_INTERVAL);
        }
        function afterArticle(){
            if (_abort) {
                finishWith('已取消，文章阶段成功 ' + ok + ' / 失败 ' + fail + ' / 剩余 ' + (total - done) + '。', '#ea580c');
                return;
            }
            addLog('文章阶段完成，成功 ' + ok + ' 篇' + (fail > 0 ? '，失败 ' + fail + ' 篇' : ''));
            runArchivePhase(domainId, domainName, fail);
        }
        function doChunk(chunk, isRetry){
            active++;
            var fd = new FormData();
            fd.append('ids', chunk.join(','));
            fd.append('_csrf_token', CSRF);
            fetch('/admin/api/content-batch-publish-chunk.php', { method: 'POST', body: fd })
                .then(function(r){ return r.json(); })
                .then(function(data){
                    active--;
                    if (data.results && Array.isArray(data.results)) {
                        data.results.forEach(function(r){ queue.push(r); });
                    } else {
                        chunk.forEach(function(id){ queue.push({success:false, id:id, message:'返回格式异常'}); });
                    }
                    startDrain();
                    if (!_abort) runNext();
                    if (active <= 0 && cursor >= chunks.length) fetchDone = true;
                })
                .catch(function(e){
                    active--;
                    if (!isRetry) {
                        addLog('批次异常（' + chunk.length + ' 篇），2秒后重试...', true);
                        setTimeout(function(){ doChunk(chunk, true); }, 2000);
                    } else {
                        chunk.forEach(function(id){ queue.push({success:false, id:id, message:'请求异常: ' + e.message}); });
                        startDrain();
                        if (!_abort) runNext();
                        if (active <= 0 && cursor >= chunks.length) fetchDone = true;
                    }
                });
        }
        function runNext(){
            while (active < PARALLEL && cursor < chunks.length && !_abort) {
                doChunk(chunks[cursor++], false);
            }
        }
        runNext();
    }

    function runArchivePhase(domainId, domainName, articleFail){
        $('domainBatchStatus').textContent = '正在生成栏目 / 标签 / 聚合页静态文件...';
        addLog('开始列表页静态化（栏目 / 标签 / 聚合页）');
        var fd = new FormData();
        fd.append('domain_id', domainId);
        fd.append('_csrf_token', CSRF);
        fetch('/admin/api/domain-archive-publish.php', { method: 'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(data){
                if (!data.success) {
                    addLog('列表页失败：' + (data.message || '未知错误'), true);
                    finishWith('完成（含错误）。文章失败 ' + articleFail + ' 篇；列表页失败：' + (data.message || ''), '#ea580c');
                    return;
                }
                var pages = data.archive_pages || [];
                pages.forEach(function(p){ addLog('  · ' + p + ' ✓'); });
                addLog('列表页阶段完成，共生成 ' + pages.length + ' 个页面');
                if (articleFail > 0) {
                    finishWith('全量静态发布完成。文章 ' + articleFail + ' 篇失败，列表页 ' + pages.length + ' 个已生成。', '#ea580c');
                } else {
                    finishWith('全量静态发布完成！列表页 ' + pages.length + ' 个已生成。', '#16a34a');
                }
            })
            .catch(function(e){
                addLog('列表页请求异常：' + e.message, true);
                finishWith('列表页阶段请求异常：' + e.message, '#dc2626');
            });
    }

    window.cancelDomainBatchPublish = function(){
        _abort = true;
        $('domainBatchStatus').textContent = '正在取消...';
    };
    window.closeDomainBatchPublish = function(){
        $('domainBatchModal').style.display = 'none';
    };
})();
</script>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
