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

$groups = list_domain_groups();
ensure_template_packs_dir();
initialize_builtin_template_packs();
$templatePacks = list_template_pack_options(array('page'));
$aiModels = list_enabled_ai_model_options();
$statuses = array(
    'enabled'  => '启用',
    'pending'  => '待审核',
    'disabled' => '停用'
);

$error = '';
$success = '';
$results = array();
$form = array(
    'domains'   => '',
    'site_name' => '',
    'site_language' => 'zh-CN',
    'group'     => '',
    'template_mode' => 'assign',
    'template'  => '',
    'status'    => 'enabled',
    'remark'    => '',
    'logo_url'  => ''
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $form['domains']   = isset($_POST['domains'])   ? trim((string)$_POST['domains'])   : '';
    $form['site_name'] = isset($_POST['site_name']) ? trim((string)$_POST['site_name']) : '';
    $form['site_language'] = isset($_POST['site_language']) ? trim((string)$_POST['site_language']) : 'zh-CN';
    $form['group']     = isset($_POST['group'])     ? trim((string)$_POST['group'])     : '';
    $form['template_mode'] = isset($_POST['template_mode']) ? trim((string)$_POST['template_mode']) : 'assign';
    $form['template']  = isset($_POST['template_pack']) ? trim((string)$_POST['template_pack']) : '';
    $form['status']    = isset($_POST['status'])    ? trim((string)$_POST['status'])    : 'enabled';
    $form['remark']    = isset($_POST['remark'])    ? trim((string)$_POST['remark'])    : '';
    $form['logo_url']  = isset($_POST['logo_url'])  ? trim((string)$_POST['logo_url'])  : '';

    // 接收 AI 生成的逐域名站点名称
    $siteNamesArray = isset($_POST['site_names']) && is_array($_POST['site_names']) ? $_POST['site_names'] : array();

    $rawDomains = preg_split('/[\r\n,;，；\s]+/', $form['domains'], -1, PREG_SPLIT_NO_EMPTY);
    $domainList = array();
    foreach ($rawDomains as $rd) {
        $d = strtolower(trim($rd));
        if ($d !== '' && !in_array($d, $domainList, true)) {
            $domainList[] = $d;
        }
    }

    if (empty($domainList)) {
        $error = '请输入至少一个域名。';
    } elseif ($form['group'] === '') {
        $error = '请选择域名分组。';
    } elseif ($form['template_mode'] === 'assign' && $form['template'] === '') {
        $error = '请选择模板套件，或选择"随机分配"模式。';
    } else {
        try {
            $packCodes = array();
            if ($form['template_mode'] === 'random' && !empty($templatePacks)) {
                foreach ($templatePacks as $tp) {
                    $packCodes[] = isset($tp['value']) ? $tp['value'] : $tp['code'];
                }
            }
            $okCount = 0;
            $skipCount = 0;
            $failCount = 0;

            $pdo = db_connection();
            $checkStmt = $pdo->prepare("SELECT id FROM domains WHERE domain = :domain AND user_id = :uid LIMIT 1");

            foreach ($domainList as $domain) {
                if (!preg_match('/^[a-zA-Z0-9]([a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/', $domain)) {
                    $results[] = array('domain' => $domain, 'status' => 'fail', 'msg' => '格式不正确');
                    $failCount++;
                    continue;
                }

                $checkStmt->execute(array(':domain' => $domain, ':uid' => current_user_id()));
                if ($checkStmt->fetch()) {
                    $results[] = array('domain' => $domain, 'status' => 'skip', 'msg' => '已存在');
                    $skipCount++;
                    continue;
                }

                $assignedPack = $form['template'];
                if ($form['template_mode'] === 'random' && !empty($packCodes)) {
                    $assignedPack = $packCodes[array_rand($packCodes)];
                }

                // 优先使用 AI 生成的逐域名站名，其次通用站名，最后取域名前缀
                $domainIndex = array_search($domain, $domainList, true);
                $siteName = '';
                if ($domainIndex !== false && isset($siteNamesArray[$domainIndex])) {
                    $siteName = trim((string)$siteNamesArray[$domainIndex]);
                }
                if ($siteName === '' && $form['site_name'] !== '') {
                    $siteName = $form['site_name'];
                }
                if ($siteName === '') {
                    $parts = explode('.', $domain);
                    $siteName = ucfirst($parts[0]);
                }

                try {
                    create_domain_record(array(
                        'domain' => $domain,
                        'site_name' => $siteName,
                        'site_language' => $form['site_language'],
                        'group_name' => $form['group'],
                        'template_pack' => $assignedPack,
                        'status' => $form['status'],
                        'remark' => $form['remark'],
                        'logo_url' => $form['logo_url'],
                    ));
                    $results[] = array('domain' => $domain, 'status' => 'ok', 'msg' => '成功（站名：' . $siteName . '，模板：' . $assignedPack . '）');
                    $okCount++;
                } catch (Exception $innerEx) {
                    if ($innerEx->getMessage() === '已存在') {
                        $results[] = array('domain' => $domain, 'status' => 'skip', 'msg' => '已存在');
                        $skipCount++;
                    } else {
                        $results[] = array('domain' => $domain, 'status' => 'fail', 'msg' => $innerEx->getMessage());
                        $failCount++;
                    }
                }
            }

            $success = '批量导入完成：成功 ' . $okCount . ' 个';
            if ($skipCount > 0) $success .= '，跳过 ' . $skipCount . ' 个（已存在）';
            if ($failCount > 0) $success .= '，失败 ' . $failCount . ' 个';
            $success .= '。';
        } catch (Exception $e) {
            $error = '数据库写入失败：' . $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">
</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">
                    <a class="btn-ghost" href="/admin/domain/list.php">返回列表</a>
                </div>
            </header>

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

            <?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>
                    <?php if (!empty($results)): ?>
                    <table class="data-table" style="margin-top:12px;">
                        <thead><tr><th>域名</th><th>结果</th><th>说明</th></tr></thead>
                        <tbody>
                        <?php foreach ($results as $r): ?>
                            <tr>
                                <td><code><?php echo e($r['domain']); ?></code></td>
                                <td><?php
                                    if ($r['status'] === 'ok') echo '<span style="color:#15803d;">✓ 成功</span>';
                                    elseif ($r['status'] === 'skip') echo '<span style="color:#d97706;">⊘ 跳过</span>';
                                    else echo '<span style="color:#dc2626;">✗ 失败</span>';
                                ?></td>
                                <td><?php echo e($r['msg']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                    <div class="filter-row" style="margin-top:14px;">
                        <a class="btn-primary" href="/admin/domain/add.php">继续新增</a>
                        <a class="btn-soft" href="/admin/domain/list.php">返回列表</a>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($success === ''): ?>
            <section class="page-card">
                <div class="card-head"><div><h2>批量新增域名</h2><p>支持一次输入多个域名，可指定模板或随机分配。</p></div></div>
                <form method="post" action="/admin/domain/add.php">
                    <?php echo csrf_field(); ?>
                    <div class="form-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:14px 16px;">
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>* 域名（每行一个，支持逗号/分号分隔，不带http(s)://）</span>
                            <textarea class="input" name="domains" rows="5" placeholder="example1.com&#10;example2.com&#10;example3.com"><?php echo e($form['domains']); ?></textarea>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>站点名称 — AI 智能生成</span>
                            <div style="display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap;">
                                <div style="flex:1; min-width:180px;">
                                    <input class="input" type="text" id="aiKeyword" placeholder="输入行业关键词，如：装修、教育、律师" style="margin:0;">
                                </div>
                                <div style="min-width:160px;">
                                    <select class="select" id="aiModel" style="margin:0;height:40px;">
                                        <?php if (empty($aiModels)): ?>
                                            <option value="">暂无可用模型</option>
                                        <?php else: ?>
                                            <?php foreach ($aiModels as $m): ?>
                                                <option value="<?php echo (int)$m['id']; ?>"><?php echo e($m['provider'] . ' / ' . $m['name']); ?></option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>
                                <div style="width:90px;">
                                    <input class="input" type="number" id="aiCount" min="1" max="200" value="1" placeholder="数量" style="margin:0;">
                                </div>
                                <button type="button" class="btn-primary" id="btnAiGen" onclick="aiGenerateSiteNames()" style="white-space:nowrap;height:40px;">AI 生成站名</button>
                            </div>
                            <p style="color:#6b7280;font-size:13px;margin:6px 0 0;">选择AI模型，输入关键词后点击生成；AI 会为每个域名自动生成独特的站点名称，生成后可逐条编辑。</p>
                        </div>
                        <div id="aiStreamWrap" style="grid-column:1/-1; display:none;">
                            <span style="display:block; font-weight:600; font-size:14px; color:#1e293b; margin-bottom:8px;">AI 生成中 <span id="aiStreamDot" style="color:#6366f1;">●</span></span>
                            <div id="aiStreamBox" style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:14px 16px; font-family:monospace; font-size:14px; color:#334155; white-space:pre-wrap; word-break:break-all; min-height:48px; max-height:200px; overflow-y:auto;"></div>
                        </div>
                        <div id="siteNameListWrap" style="grid-column:1/-1; display:none;">
                            <span style="display:block; font-weight:600; font-size:14px; color:#1e293b; margin-bottom:8px;">站名分配预览 <span id="siteNameStats" style="font-weight:400;color:#6b7280;font-size:13px;"></span></span>
                            <div id="siteNameList" style="max-height:360px; overflow-y:auto; border:1px solid #e2e8f0; border-radius:8px; background:#fafbfc;"></div>
                        </div>
                        <div class="input-group">
                            <span>* 域名分组</span>
                            <div style="display:flex; gap:8px; align-items:center;">
                                <select class="select" id="groupSelect" onchange="toggleCustomGroup(this)" style="flex:1;">
                                    <option value="">请选择分组</option>
                                    <?php foreach ($groups as $g): ?>
                                        <option value="<?php echo e($g); ?>"<?php echo $form['group'] === $g ? ' selected' : ''; ?>><?php echo e($g); ?></option>
                                    <?php endforeach; ?>
                                    <option value="__custom__"<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? ' selected' : ''; ?>>+ 自定义分组</option>
                                </select>
                                <input class="input" type="text" id="customGroupInput" name="custom_group" placeholder="输入自定义分组名称" value="<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? e($form['group']) : ''; ?>" style="flex:1; display:<?php echo ($form['group'] !== '' && !in_array($form['group'], $groups, true)) ? 'block' : 'none'; ?>; margin:0;">
                            </div>
                            <input type="hidden" name="group" id="groupValue" value="<?php echo e($form['group']); ?>">
                        </div>
                        <div class="input-group">
                            <span>* 站点语言</span>
                            <select class="select" name="site_language">
                                <?php foreach (domain_language_options() as $langCode => $langLabel): ?>
                                    <option value="<?php echo e($langCode); ?>"<?php echo $form['site_language'] === $langCode ? ' selected' : ''; ?>><?php echo e($langLabel); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <p style="color:#6b7280;font-size:13px;margin:6px 0 0;">新建域名后，菜单、首页、定时任务和 AI 生成内容会默认继承该语言。</p>
                        </div>
                        <div class="input-group">
                            <span>* 模板分配方式</span>
                            <select class="select" name="template_mode" id="tplMode" onchange="document.getElementById('tplSelect').style.display=this.value==='assign'?'':'none';">
                                <option value="assign"<?php echo $form['template_mode'] === 'assign' ? ' selected' : ''; ?>>指定模板</option>
                                <option value="random"<?php echo $form['template_mode'] === 'random' ? ' selected' : ''; ?>>随机分配</option>
                            </select>
                        </div>
                        <div class="input-group" id="tplSelect"<?php echo $form['template_mode'] === 'random' ? ' style="display:none;"' : ''; ?>>
                            <span>模板套件</span>
                            <select class="select" name="template_pack">
                                <option value="">请选择模板套件</option>
                                <?php foreach ($templatePacks as $tp):
                                    $tpValue = isset($tp['value']) ? $tp['value'] : $tp['code'];
                                    $tpSelected = ($form['template'] === $tpValue || (strpos($form['template'], ':') === false && $form['template'] === $tp['code']));
                                ?>
                                    <option value="<?php echo e($tpValue); ?>"<?php echo $tpSelected ? ' selected' : ''; ?>><?php echo e($tp['name']); ?> (<?php echo e(isset($tp['serial_label']) ? $tp['serial_label'] : $tp['code']); ?>) · <?php echo isset($tp['pack_type']) && $tp['pack_type'] === 'standard' ? '常规' : '变体'; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group">
                            <span>初始状态</span>
                            <select class="select" name="status">
                                <?php foreach ($statuses as $k => $v): ?>
                                    <option value="<?php echo e($k); ?>"<?php echo $form['status'] === $k ? ' selected' : ''; ?>><?php echo e($v); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="input-group">
                            <span>站点 Logo <small style="color:#94a3b8;">（图片URL，留空则前台显示站点名称文本）</small></span>
                            <div style="display:flex; gap:10px; align-items:flex-start;">
                                <input class="input" type="text" name="logo_url" id="logoUrlInput" value="<?php echo e($form['logo_url']); ?>" placeholder="https://example.com/logo.png 或 /uploads/logo.png" style="flex:1;">
                                <label class="btn-soft" style="cursor:pointer; white-space:nowrap; margin:0; display:inline-flex; align-items:center; gap:4px;">
                                    <input type="file" accept="image/*" id="logoFileInput" style="display:none;">
                                    上传图片
                                </label>
                            </div>
                            <?php if ($form['logo_url'] !== ''): ?>
                            <div style="margin-top:8px;"><img src="<?php echo e($form['logo_url']); ?>" alt="Logo预览" style="max-height:48px; max-width:240px; border:1px solid #e2e8f0; border-radius:6px; background:#f8fafc; padding:4px;" onerror="this.style.display='none'"></div>
                            <?php endif; ?>
                        </div>
                        <div class="input-group" style="grid-column:1/-1;">
                            <span>备注</span>
                            <textarea class="input" name="remark" rows="2" placeholder="可选，填写域名用途或关键词说明"><?php echo e($form['remark']); ?></textarea>
                        </div>
                    </div>
                    <div class="filter-row" style="margin-top:18px;">
                        <button class="btn-primary" type="submit">批量提交</button>
                        <a class="btn-ghost" href="/admin/domain/list.php">取消</a>
                    </div>
                </form>
            </section>
            <?php endif; ?>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
var csrfToken = <?php echo json_encode(csrf_token()); ?>;

// 解析域名文本框获取域名列表
function parseDomains() {
    var raw = document.querySelector('textarea[name="domains"]').value;
    var arr = raw.split(/[\r\n,;，；\s]+/).filter(function(s){ return s.trim() !== ''; });
    var unique = [];
    arr.forEach(function(d){
        d = d.trim().toLowerCase();
        if (d && unique.indexOf(d) === -1) unique.push(d);
    });
    return unique;
}

// 域名框变化时自动更新数量
document.querySelector('textarea[name="domains"]').addEventListener('input', function(){
    var domains = parseDomains();
    var countInput = document.getElementById('aiCount');
    if (domains.length > 0) {
        countInput.value = domains.length;
    }
});

// AI 生成站名（流式）
function aiGenerateSiteNames() {
    var keyword = document.getElementById('aiKeyword').value.trim();
    var count = parseInt(document.getElementById('aiCount').value, 10);
    var domains = parseDomains();
    var btn = document.getElementById('btnAiGen');
    var siteLanguageSel = document.querySelector('select[name="site_language"]');
    var siteLanguage = siteLanguageSel ? siteLanguageSel.value : 'zh-CN';

    if (!keyword) {
        alert('请输入行业关键词');
        document.getElementById('aiKeyword').focus();
        return;
    }
    // 约束生成数量：如域名数>0，则强制按域名数量生成；否则至少生成1个
    var desiredCount = (domains.length > 0) ? domains.length : (count > 0 ? count : 1);

    btn.disabled = true;
    btn.textContent = 'AI 生成中…';

    // 显示流式输出区域，隐藏之前的站名列表
    var streamWrap = document.getElementById('aiStreamWrap');
    var streamBox = document.getElementById('aiStreamBox');
    var listWrap = document.getElementById('siteNameListWrap');
    streamWrap.style.display = '';
    streamBox.textContent = '';
    listWrap.style.display = 'none';

    // 闪烁动画
    var dotEl = document.getElementById('aiStreamDot');
    var dotTimer = setInterval(function(){ dotEl.style.opacity = dotEl.style.opacity === '0' ? '1' : '0'; }, 500);

    var modelId = document.getElementById('aiModel').value;
    if (!modelId) {
        finish();
        alert('请先配置并启用AI模型');
        return;
    }

    var fd = new FormData();
    fd.append('_csrf_token', csrfToken);
    fd.append('keyword', keyword);
    fd.append('count', desiredCount);
    fd.append('model_id', modelId);
    fd.append('site_language', siteLanguage);

    fetch('/admin/api/ai-generate-site-names.php', { method: 'POST', body: fd })
        .then(function(resp) {
            var ct = resp.headers.get('content-type') || '';
            // 如果返回的是 JSON（参数校验错误），直接按 JSON 处理
            if (ct.indexOf('application/json') !== -1) {
                return resp.json().then(function(data) {
                    finish();
                    alert(data.error || '生成失败');
                });
            }
            // SSE 流式读取
            var reader = resp.body.getReader();
            var decoder = new TextDecoder('utf-8');
            var buffer = '';
            var completed = false;

            function readChunk() {
                return reader.read().then(function(result) {
                    if (result.done) {
                        if (!completed) {
                            var fallbackNames = extractSiteNames(streamBox.textContent, desiredCount);
                            if (fallbackNames.length > 0) {
                                streamWrap.style.display = 'none';
                                renderSiteNameList(domains, fallbackNames);
                            }
                        }
                        finish();
                        return;
                    }
                    buffer += decoder.decode(result.value, { stream: true });
                    // 按行解析 SSE
                    var parts = buffer.split('\n\n');
                    buffer = parts.pop(); // 最后一段可能不完整
                    parts.forEach(function(part) {
                        part = part.trim();
                        if (part.indexOf('data: ') !== 0) return;
                        var json;
                        try { json = JSON.parse(part.substring(6)); } catch(e) { return; }

                        if (json.type === 'start') {
                            // 连接建立，忽略
                        } else if (json.type === 'chunk') {
                            streamBox.textContent += json.text;
                            streamBox.scrollTop = streamBox.scrollHeight;
                        } else if (json.type === 'done') {
                            completed = true;
                            streamWrap.style.display = 'none';
                            try {
                                var names = Array.isArray(json.names) ? json.names.slice(0, desiredCount) : [];
                                if (names.length === 0) {
                                    names = extractSiteNames(streamBox.textContent, desiredCount);
                                }
                                renderSiteNameList(domains, names);
                            } catch (e) {
                                var fb = extractSiteNames(streamBox.textContent, desiredCount);
                                renderSiteNameList(domains, fb);
                            }
                            finish();
                            return;
                        } else if (json.type === 'error') {
                            finish();
                            alert(json.text || '生成失败');
                            return;
                        }
                    });
                    return readChunk();
                });
            }
            return readChunk();
        })
        .catch(function(err) {
            finish();
            alert('请求失败，请检查网络或AI模型配置');
        });

    function finish() {
        btn.disabled = false;
        btn.textContent = 'AI 生成站名';
        clearInterval(dotTimer);
        dotEl.style.opacity = '1';
    }
}

// 渲染可编辑站名列表
function renderSiteNameList(domains, names) {
    var wrap = document.getElementById('siteNameListWrap');
    var list = document.getElementById('siteNameList');
    var stats = document.getElementById('siteNameStats');
    wrap.style.display = '';

    var html = '<table style="width:100%; border-collapse:collapse; font-size:14px;">';
    html += '<thead><tr style="background:#f1f5f9;"><th style="padding:8px 12px; text-align:left; color:#475569; font-weight:600; width:40px;">#</th><th style="padding:8px 12px; text-align:left; color:#475569; font-weight:600;">域名</th><th style="padding:8px 12px; text-align:left; color:#475569; font-weight:600;">站点名称（可编辑）</th></tr></thead><tbody>';

    var total = Math.max(domains.length, names.length);
    for (var i = 0; i < total; i++) {
        var domain = domains[i] || '（待填写域名 #' + (i + 1) + '）';
        var name = names[i] || '';
        var bg = i % 2 === 0 ? '#fff' : '#fafbfc';
        html += '<tr style="background:' + bg + ';">'
            + '<td style="padding:6px 12px; color:#94a3b8;">' + (i + 1) + '</td>'
            + '<td style="padding:6px 12px;"><code style="font-size:13px; color:#334155;">' + escHtml(domain) + '</code></td>'
            + '<td style="padding:4px 8px;"><input type="text" name="site_names[]" value="' + escAttr(name) + '" class="input" style="margin:0; padding:6px 10px; font-size:14px; height:auto;"></td>'
            + '</tr>';
    }
    html += '</tbody></table>';
    list.innerHTML = html;
    stats.textContent = '（共 ' + total + ' 条）';
}

function escHtml(s) {
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
}
function escAttr(s) {
    return s.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

function extractSiteNames(text, limit) {
    var names = [];
    String(text || '').split(/[\r\n、，,；;]+/).forEach(function(line){
        line = line.replace(/^\s*\d+[\.\)、）]\s*/, '').replace(/^\s*[-–—·•]\s*/, '').trim();
        line = line.replace(/^["'“‘]+|["'”’]+$/g, '');
        if (line && line.length <= 20 && names.indexOf(line) === -1) {
            names.push(line);
        }
    });
    return names.slice(0, Math.max(1, parseInt(limit, 10) || 1));
}

// 自定义分组切换
function toggleCustomGroup(sel) {
    var customInput = document.getElementById('customGroupInput');
    var hiddenInput = document.getElementById('groupValue');
    if (sel.value === '__custom__') {
        customInput.style.display = '';
        customInput.focus();
        hiddenInput.value = customInput.value;
    } else {
        customInput.style.display = 'none';
        hiddenInput.value = sel.value;
    }
}
// 自定义分组输入同步
(function(){
    var customInput = document.getElementById('customGroupInput');
    if (customInput) {
        customInput.addEventListener('input', function(){
            document.getElementById('groupValue').value = this.value.trim();
        });
    }
    // 表单提交前同步
    var form = document.querySelector('form[action="/admin/domain/add.php"]');
    if (form) {
        form.addEventListener('submit', function(){
            var sel = document.getElementById('groupSelect');
            var hidden = document.getElementById('groupValue');
            if (sel && sel.value === '__custom__') {
                hidden.value = customInput ? customInput.value.trim() : '';
            } else if (sel) {
                hidden.value = sel.value;
            }
        });
    }
})();

// Logo 上传（与编辑页保持一致的交互）
(function(){
    var fileInput = document.getElementById('logoFileInput');
    var urlInput = document.getElementById('logoUrlInput');
    if (!fileInput || !urlInput) return;
    fileInput.addEventListener('change', function(){
        var file = this.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) { alert('图片不能超过5MB'); this.value = ''; return; }
        var fd = new FormData();
        fd.append('upload', file);
        var btn = this.parentElement;
        btn.style.opacity = '0.5';
        btn.style.pointerEvents = 'none';
        fetch('/admin/api/editor-upload-image.php', { method: 'POST', body: fd })
            .then(function(r){ return r.json(); })
            .then(function(d){
                btn.style.opacity = ''; btn.style.pointerEvents = '';
                if (d.uploaded && d.url) {
                    urlInput.value = d.url;
                    var group = urlInput.closest('.input-group');
                    var preview = group ? group.querySelector('img') : null;
                    if (preview) { preview.src = d.url; preview.style.display = ''; }
                    else if (group) {
                        var div = document.createElement('div');
                        div.style.marginTop = '8px';
                        div.innerHTML = '<img src="' + d.url + '" alt="Logo预览" style="max-height:48px;max-width:240px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;padding:4px;" onerror="this.style.display=\'none\'">';
                        group.appendChild(div);
                    }
                } else {
                    alert(d.error && d.error.message ? d.error.message : '上传失败');
                }
            })
            .catch(function(){ btn.style.opacity = ''; btn.style.pointerEvents = ''; alert('上传请求失败'); });
        this.value = '';
    });
})();

// 初始化：从 localStorage 读取批量前缀生成的域名
(function(){
    try {
        var prefill = localStorage.getItem('prefill_domains');
        if (prefill && prefill.trim() !== '') {
            var ta = document.querySelector('textarea[name="domains"]');
            if (ta && ta.value.trim() === '') {
                ta.value = prefill;
            }
            localStorage.removeItem('prefill_domains');
        }
    } catch(e){}
    var domains = parseDomains();
    if (domains.length > 0) {
        document.getElementById('aiCount').value = domains.length;
    }
})();
</script>
</body>
</html>
