<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { SButton, SCard, SConfigProvider, SInput, STag } from '@soybeanjs/ui';

type ChatItem = Record<string, any> & { _deleting?: boolean };
type BanItem = Record<string, any> & { _loading?: boolean };
type LogItem = { time?: string; level?: string; message?: string };
type GroupItem = { chat_id: number; name: string };
type ShopItem = Record<string, any>;
type LotteryItem = Record<string, any>;

const sseConnected = ref(false);
const chatLogs = ref<ChatItem[]>([]);
const bans = ref<BanItem[]>([]);
const logs = ref<LogItem[]>([]);
const groups = ref<GroupItem[]>([]);
const selectedChatId = ref<number | null>(null);
const shopItems = ref<ShopItem[]>([]);
const shopTransactions = ref<Record<string, any>[]>([]);
const lotteries = ref<LotteryItem[]>([]);
const lotteryParticipants = ref<Record<string, any>[]>([]);
const shopForm = reactive({ item_key: '', name: '', cost: 0, desc: '', enabled: true });
const lotteryForm = reactive({ id: 0, title: '', prize: '', description: '', condition_type: 'all', condition_value: 0, draw_type: 'people', end_type: 'people', end_value: 3, max_participants: 3, draw_at: '', status: 'draft' });
const activePage = ref<'dashboard' | 'shop' | 'lottery' | 'bans'>('dashboard');
const activeTab = reactive({ shop: 'items', lottery: 'events' });
const toast = ref('');
const confirmState = reactive({ open: false, title: '', message: '', confirmText: '确认', danger: false, resolver: null as null | ((value: boolean) => void) });
const authReady = ref(false);
const authenticated = ref(false);
const loginForm = reactive({ username: '', password: '' });
const loggingIn = ref(false);
const newMessage = ref('');
const sending = ref(false);
const restarting = ref(false);
const restartingBot = ref(false);
const stats = reactive({ today_bans: 0, total_bans: 0, active_bans: 0 });
const logScroll = ref<HTMLElement | null>(null);
let es: EventSource | null = null;
let statTimer: number | undefined;

const chatCount = computed(() => chatLogs.value.length);
const selectedQuery = computed(() => selectedChatId.value ? `?chat_id=${selectedChatId.value}` : '');

const pageTitle = computed(() => ({
  dashboard: '群组安全总览', shop: '商城管理', lottery: '抽奖管理', bans: '封禁记录'
}[activePage.value]));
const pageDesc = computed(() => ({
  dashboard: '实时审计聊天、封禁、日志和运营活动', shop: '商品 CRUD 与兑换交易记录', lottery: '抽奖项目、开奖条件与参与记录', bans: '封禁审计与手动解封'
}[activePage.value]));
function goPage(page: typeof activePage.value) {
  activePage.value = page;
  if (page === 'shop') { loadShopItems(); loadShopTransactions(); }
  if (page === 'lottery') loadLotteries();
  if (page === 'bans') loadBans();
}


function formatTime(value?: string) {
  if (!value) return '-';
  const text = String(value);
  const m = text.match(/(\d{2}:\d{2}:\d{2})/);
  if (m) return m[1];
  return text.replace('T', ' ').slice(11, 19) || text;
}
function compactLog(msg?: string) {
  const text = String(msg || '').replace(/\s+/g, ' ').trim();
  return text.length > 260 ? `${text.slice(0, 260)}...` : text;
}
function chatStatusText(item: ChatItem) {
  if (item.deleted) return '已删';
  if (item.spam) return '垃圾';
  if (Number(item.user_id || 0) === 0) return 'Web';
  return '正常';
}
function chatStatusClass(item: ChatItem) {
  if (item.deleted) return 'deleted';
  if (item.spam) return 'spam';
  if (Number(item.user_id || 0) === 0) return 'web';
  return 'normal';
}
function chatItemClass(item: ChatItem) {
  return ['chat-item', chatStatusClass(item)];
}
function tagColor(item: ChatItem) {
  if (item.deleted) return 'secondary';
  if (item.spam) return 'destructive';
  if (Number(item.user_id || 0) === 0) return 'accent';
  return 'primary';
}

function showToast(message: string) {
  toast.value = message;
  window.setTimeout(() => { if (toast.value === message) toast.value = ''; }, 2600);
}
function askConfirm(title: string, message: string, options: { confirmText?: string; danger?: boolean } = {}) {
  confirmState.open = true;
  confirmState.title = title;
  confirmState.message = message;
  confirmState.confirmText = options.confirmText || '确认';
  confirmState.danger = Boolean(options.danger);
  return new Promise<boolean>((resolve) => { confirmState.resolver = resolve; });
}
function closeConfirm(value: boolean) {
  confirmState.open = false;
  confirmState.resolver?.(value);
  confirmState.resolver = null;
}

async function checkAuth() {
  try {
    const data = await fetchJson('/api/auth/status');
    authenticated.value = Boolean(data.authenticated);
  } catch {
    authenticated.value = false;
  } finally {
    authReady.value = true;
  }
}
async function login() {
  if (!loginForm.username || !loginForm.password) return showToast('请输入账号和密码');
  loggingIn.value = true;
  try {
    await fetchJson('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(loginForm) });
    authenticated.value = true;
    await bootstrapData();
  } catch (e: any) {
    showToast(e.message || '登录失败');
  } finally { loggingIn.value = false; }
}
async function logout() {
  await fetchJson('/api/auth/logout', { method: 'POST' }).catch(() => {});
  authenticated.value = false;
}

async function fetchJson(url: string, options?: RequestInit) {
  const res = await fetch(url, options);
  const data = await res.json().catch(() => ({}));
  if (!res.ok || data.ok === false) throw new Error(data.error || data.message || `HTTP ${res.status}`);
  return data;
}
async function loadChatHistory() {
  try {
    const data = await fetchJson(`/api/chat${selectedQuery.value}`);
    chatLogs.value = data.map((m: ChatItem) => ({ ...m, _deleting: false }));
  } catch {}
}
async function loadBans() {
  try {
    const data = await fetchJson(`/api/bans${selectedQuery.value}`);
    bans.value = data.map((b: BanItem) => ({ ...b, _loading: false }));
  } catch {}
}
async function loadStats() {
  try {
    Object.assign(stats, await fetchJson(`/api/stats${selectedQuery.value}`));
  } catch {}
}
async function loadLogs() {
  try {
    logs.value = await fetchJson('/api/logs');
    scrollLogBottom();
  } catch {}
}
function scrollLogBottom() {
  nextTick(() => {
    if (logScroll.value) logScroll.value.scrollTop = logScroll.value.scrollHeight;
  });
}

async function loadGroups() {
  try {
    groups.value = await fetchJson('/api/groups');
    if (!selectedChatId.value && groups.value.length) selectedChatId.value = groups.value[0].chat_id;
  } catch {}
}
async function loadShopItems() {
  try { shopItems.value = await fetchJson(`/api/shop-items${selectedQuery.value}`); } catch {}
}
async function loadShopTransactions() {
  try { shopTransactions.value = await fetchJson(`/api/shop-transactions${selectedQuery.value}`); } catch {}
}
async function saveShopItem() {
  if (!shopForm.item_key || !shopForm.name) return showToast('请填写商品编号和名称');
  await fetchJson('/api/shop-items', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ...shopForm, chat_id: selectedChatId.value || 0 })
  });
  Object.assign(shopForm, { item_key: '', name: '', cost: 0, desc: '', enabled: true });
  await loadShopItems();
}
async function editShopItem(item: ShopItem) { Object.assign(shopForm, item); }
async function deleteShopItem(item: ShopItem) {
  if (!await askConfirm('删除商品', `确认删除商品「${item.name}」？交易记录会保留。`, { confirmText: '删除', danger: true })) return;
  await fetchJson(`/api/shop-items/${item.item_key}${selectedQuery.value}`, { method: 'DELETE' });
  await loadShopItems();
}
async function loadLotteries() {
  try { lotteries.value = await fetchJson(`/api/lotteries${selectedQuery.value}`); } catch {}
}
function resetLotteryForm() { Object.assign(lotteryForm, { id: 0, title: '', prize: '', description: '', condition_type: 'all', condition_value: 0, draw_type: 'people', end_type: 'people', end_value: 3, max_participants: 3, draw_at: '', status: 'draft' }); }
function editLottery(item: LotteryItem) { Object.assign(lotteryForm, { ...item, id: item.id || 0 }); }
async function saveLottery() {
  if (!lotteryForm.title || !lotteryForm.prize) return showToast('请填写抽奖标题和奖品');
  lotteryForm.end_type = lotteryForm.draw_type;
  if (lotteryForm.draw_type === 'people') lotteryForm.max_participants = Number(lotteryForm.end_value || lotteryForm.max_participants || 1);
  const url = lotteryForm.id ? `/api/lotteries/${lotteryForm.id}` : '/api/lotteries';
  await fetchJson(url, { method: lotteryForm.id ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...lotteryForm, chat_id: selectedChatId.value || 0 }) });
  resetLotteryForm();
  await loadLotteries();
}
async function deleteLottery(item: LotteryItem) {
  if (!await askConfirm('删除抽奖', `确认删除抽奖「${item.title || item.prize}」？参与记录会一并移除。`, { confirmText: '删除', danger: true })) return;
  await fetchJson(`/api/lotteries/${item.id}`, { method: 'DELETE' });
  await loadLotteries();
}
async function loadLotteryParticipants(item: LotteryItem) {
  lotteryParticipants.value = await fetchJson(`/api/lotteries/${item.id}/participants`);
}
async function cancelLottery(item: LotteryItem) {
  if (!await askConfirm('取消抽奖', '确认取消这个抽奖？已参与用户不会自动补偿。', { confirmText: '取消抽奖', danger: true })) return;
  await fetchJson(`/api/lotteries/${item.id}/cancel`, { method: 'POST' });
  await loadLotteries();
}
async function drawLottery(item: LotteryItem) {
  if (!await askConfirm('立即开奖', '确认现在开奖？开奖后状态会变更。', { confirmText: '立即开奖' })) return;
  await fetchJson(`/api/lotteries/${item.id}/draw`, { method: 'POST' });
  await loadLotteries();
}
function reloadByGroup() { loadChatHistory(); loadBans(); loadStats(); loadShopItems(); loadShopTransactions(); loadLotteries(); }

function connectSSE() {
  if (es) es.close();
  es = new EventSource('/api/stream');
  es.addEventListener('connected', () => { sseConnected.value = true; });
  es.addEventListener('chat', (e) => {
    const data = JSON.parse((e as MessageEvent).data);
    chatLogs.value.unshift(data);
    if (chatLogs.value.length > 120) chatLogs.value.pop();
  });
  es.addEventListener('spam', (e) => {
    const data = JSON.parse((e as MessageEvent).data);
    const item = chatLogs.value.find(x => x.msg_id === data.msg_id);
    if (item) Object.assign(item, data);
  });
  es.addEventListener('chat_delete', (e) => {
    const data = JSON.parse((e as MessageEvent).data);
    const item = chatLogs.value.find(x => x.id === data.id);
    if (item) Object.assign(item, { deleted: true, manually_deleted: true, deleted_at: data.deleted_at });
    loadStats();
  });
  es.addEventListener('ban', (e) => {
    const data = JSON.parse((e as MessageEvent).data);
    bans.value.unshift({ ...data, _loading: false });
    if (bans.value.length > 80) bans.value.pop();
    loadStats();
  });
  es.addEventListener('unban', (e) => {
    const data = JSON.parse((e as MessageEvent).data);
    const ban = bans.value.find(b => b.user_id === data.user_id);
    if (ban) ban.auto_unban = false;
    loadStats();
  });
  es.addEventListener('log', (e) => {
    logs.value.push(JSON.parse((e as MessageEvent).data));
    if (logs.value.length > 300) logs.value.shift();
    scrollLogBottom();
  });
  es.onerror = () => {
    sseConnected.value = false;
    window.setTimeout(connectSSE, 3000);
  };
}

async function sendMessage() {
  const text = newMessage.value.trim();
  if (!text || sending.value) return;
  sending.value = true;
  try {
    await fetchJson('/api/send', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text, chat_id: selectedChatId.value })
    });
    newMessage.value = '';
  } catch (e: any) {
    showToast(`发送失败：${e.message}`);
  } finally {
    sending.value = false;
  }
}
async function deleteChatMessage(item: ChatItem, ban = false) {
  const action = ban ? '删除并封禁' : '删除';
  if (!await askConfirm(action, `确认${action}这条消息？`, { confirmText: action, danger: true })) return;
  item._deleting = true;
  try {
    await fetchJson(`/api/messages/${item.id}/delete`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ban_user: ban })
    });
    Object.assign(item, { deleted: true, manually_deleted: true });
    await loadStats();
  } catch (e: any) {
    showToast(`${action}失败：${e.message}`);
  } finally {
    item._deleting = false;
  }
}
async function unban(item: BanItem) {
  if (!await askConfirm('解除封禁', `确认解封 ${item.username || item.user_id}？`, { confirmText: '解封' })) return;
  item._loading = true;
  try {
    await fetchJson(`/api/unban/${item.user_id}`, { method: 'POST' });
    item.auto_unban = false;
    await loadStats();
  } catch (e: any) {
    showToast(`解封失败：${e.message}`);
  } finally {
    item._loading = false;
  }
}
async function restartBot() {
  if (!await askConfirm('重启 Bot', '确认只重启 Telegram Bot？Web 管理页不会重启。', { confirmText: '重启 Bot' })) return;
  restartingBot.value = true;
  try {
    await fetchJson('/api/restart-bot', { method: 'POST' });
    window.setTimeout(() => { restartingBot.value = false; loadLogs(); }, 5000);
  } catch (e: any) {
    restartingBot.value = false;
    showToast(`重启 Bot 失败：${e.message}`);
  }
}
async function restartService() {
  if (!await askConfirm('重启服务', '确认重启 TG Spam Guard 服务？重启期间 Web 和 Bot 会短暂不可用。', { confirmText: '重启服务', danger: true })) return;
  restarting.value = true;
  try {
    await fetchJson('/api/restart', { method: 'POST' });
  } catch {}
  window.setTimeout(() => location.reload(), 8000);
}
function copyLogs() {
  const text = logs.value.map(l => `${formatTime(l.time)} ${l.level || ''} ${compactLog(l.message)}`).join('\n');
  navigator.clipboard?.writeText(text);
}

async function bootstrapData() {
  await loadGroups().then(reloadByGroup);
  loadChatHistory();
  loadBans();
  loadStats();
  loadShopItems();
  loadLotteries();
  loadLogs();
  connectSSE();
  if (!statTimer) statTimer = window.setInterval(loadStats, 30000);
}
onMounted(async () => {
  await checkAuth();
  if (authenticated.value) await bootstrapData();
});
onBeforeUnmount(() => {
  if (es) es.close();
  if (statTimer) window.clearInterval(statTimer);
});
</script>

<template>
  <SConfigProvider :theme="{ theme: { primary: 'indigo' }, size: 'sm' }">
    <div v-if="!authReady" class="login-page"><div class="login-card">正在检查登录状态...</div></div>
    <div v-else-if="!authenticated" class="login-page"><form class="login-card" @submit.prevent="login"><img class="brand-icon" src="/icon.svg" alt="TG Spam Guard" /><h1>TG Spam Guard</h1><p>请输入管理账号密码</p><SInput v-model="loginForm.username" placeholder="账号" /><SInput v-model="loginForm.password" type="password" placeholder="密码" /><SButton type="submit" color="primary" :disabled="loggingIn">登录</SButton></form></div>
    <main v-else class="admin-shell">
      <aside class="sidebar">
        <div class="side-brand">
          <img class="brand-icon" src="/icon.svg" alt="TG Spam Guard" />
          <div>
            <h1>TG Spam Guard</h1>
            <p>群组安全后台</p>
          </div>
        </div>
        <div class="side-section">
          <span class="side-label">当前群组</span>
          <select v-model="selectedChatId" class="form-select side-select" @change="reloadByGroup"><option :value="null">全部群组</option><option v-for="g in groups" :key="g.chat_id" :value="g.chat_id">{{ g.label || g.name }}</option></select>
        </div>
        <nav class="side-nav">
          <button :class="{active: activePage === 'dashboard'}" @click="goPage('dashboard')"><span>总览</span><em>Dashboard</em></button>
          <button :class="{active: activePage === 'shop'}" @click="goPage('shop')"><span>商城管理</span><em>Shop</em></button>
          <button :class="{active: activePage === 'lottery'}" @click="goPage('lottery')"><span>抽奖管理</span><em>Lottery</em></button>
          <button :class="{active: activePage === 'bans'}" @click="goPage('bans')"><span>封禁记录</span><em>Bans</em></button>
        </nav>
        <div class="side-footer">
          <span class="conn" :class="sseConnected ? 'on' : 'off'">{{ sseConnected ? '实时连接' : '连接中' }}</span>
          <small>Bot 管理控制台</small>
        </div>
      </aside>

      <section class="admin-main">
        <header class="admin-header" id="dashboard">
          <div>
            <span class="eyebrow">CONTROL CENTER</span>
            <h2>{{ pageTitle }}</h2>
            <p>{{ pageDesc }}</p>
          </div>
          <div class="top-actions">
            <SButton size="xs" variant="outline" @click="goPage('shop')">商城管理</SButton>
            <SButton size="xs" variant="outline" @click="goPage('lottery')">抽奖管理</SButton>
            <SButton size="xs" variant="outline" @click="goPage('bans')">封禁记录</SButton>
            <SButton size="xs" variant="outline" @click="logout">退出</SButton>
            <SButton size="xs" variant="outline" color="primary" :disabled="restartingBot" @click="restartBot">重启 Bot</SButton>
            <SButton size="xs" variant="soft" color="warning" :disabled="restarting" @click="restartService">重启服务</SButton>
          </div>
        </header>

      <section v-show="activePage === 'dashboard'" class="stats-grid">
        <SCard class="stat-card blue"><span>今日封禁</span><strong>{{ stats.today_bans || 0 }}</strong></SCard>
        <SCard class="stat-card red"><span>累计封禁</span><strong>{{ stats.total_bans || 0 }}</strong></SCard>
        <SCard class="stat-card orange"><span>当前封禁</span><strong>{{ stats.active_bans || 0 }}</strong></SCard>
        <SCard class="stat-card green"><span>聊天记录</span><strong>{{ chatCount }}</strong></SCard>
      </section>

      <section v-show="activePage === 'dashboard'" class="main-grid">
        <SCard id="chat" class="panel chat-panel" title="聊天记录" :description="`${chatCount} 条`">
          <div class="scroll-area chat-scroll">
            <div v-if="!chatLogs.length" class="empty">等待消息...</div>
            <article v-for="(item, i) in chatLogs" :key="item.id || i" :class="chatItemClass(item)">
              <div class="chat-head">
                <div class="chat-user-line">
                  <STag size="xs" :color="tagColor(item)" variant="soft">{{ chatStatusText(item) }}</STag>
                  <span class="chat-user">@{{ item.username || item.first_name || 'unknown' }}</span>
                  <span class="chat-uid">{{ item.user_id }}</span>
                </div>
                <div class="chat-meta-line">
                  <span class="chat-id">#{{ item.msg_id || '-' }}</span>
                  <span class="chat-time">{{ formatTime(item.time) }}</span>
                </div>
              </div>
              <div class="chat-text">{{ item.text || '（空消息）' }}</div>
              <div class="chat-foot">
                <STag v-if="item.spam" class="reason-tag" size="xs" color="destructive" variant="soft" :title="item.reason || item.spam_reason">{{ item.reason || item.spam_reason }}</STag>
                <span v-else />
                <div class="chat-actions">
                  <STag v-if="item.deleted" size="xs" color="secondary" variant="soft">已删 · {{ formatTime(item.deleted_at) }}</STag>
                  <template v-else>
                    <SButton size="xs" variant="link" color="destructive" :disabled="item._deleting" @click="deleteChatMessage(item, false)">删除</SButton>
                    <SButton v-if="item.user_id" size="xs" variant="link" color="warning" :disabled="item._deleting" @click="deleteChatMessage(item, true)">删封</SButton>
                  </template>
                </div>
              </div>
            </article>
          </div>
        </SCard>

        <SCard class="panel log-panel" title="📜 实时日志" :description="`${logs.length} 条`">
          <template #extra>
            <div class="panel-extra">
              <SButton size="xs" variant="outline" @click="copyLogs">复制</SButton>
              <SButton size="xs" variant="outline" @click="loadLogs">刷新</SButton>
            </div>
          </template>
          <div ref="logScroll" class="log-window">
            <div v-if="!logs.length" class="empty dark">等待日志...</div>
            <div v-for="(item, i) in logs" :key="i" class="log-line" :class="item.level" :title="compactLog(item.message)">
              <span class="log-time">{{ formatTime(item.time) }}</span>
              <span class="log-level">{{ item.level }}</span>
              <span class="log-msg">{{ compactLog(item.message) }}</span>
            </div>
          </div>
        </SCard>
      </section>

      <section v-show="activePage === 'shop'" class="tab-page manager-layout">
        <aside class="editor-panel"><div class="section-title"><span>商品编辑</span><small>{{ shopForm.item_key ? '编辑中' : '新建' }}</small></div><label>商品编号<SInput v-model="shopForm.item_key" placeholder="如 1 / vip_card" /></label><label>商品名称<SInput v-model="shopForm.name" placeholder="补签卡" /></label><label>积分价格<SInput v-model="shopForm.cost" placeholder="50" /></label><label>说明<SInput v-model="shopForm.desc" placeholder="展示在 /shop 内" /></label><label class="switch-line"><input v-model="shopForm.enabled" type="checkbox" /> 上架销售</label><div class="editor-actions"><SButton size="xs" color="primary" @click="saveShopItem">保存商品</SButton><SButton size="xs" variant="outline" @click="Object.assign(shopForm, { item_key: '', name: '', cost: 0, desc: '', enabled: true })">新建</SButton></div></aside>
        <section class="data-panel"><div class="tabbar"><button :class="{active: activeTab.shop === 'items'}" @click="activeTab.shop='items'">商品列表</button><button :class="{active: activeTab.shop === 'tx'}" @click="activeTab.shop='tx'; loadShopTransactions()">交易记录</button></div><div v-if="activeTab.shop === 'items'" class="data-table"><div class="table-head"><span>编号/商品</span><span>价格</span><span>状态</span><span>操作</span></div><div v-for="item in shopItems" :key="item.item_key" class="table-row"><span><b>{{ item.item_key }}</b><em>{{ item.name }}</em><small>{{ item.desc || '无说明' }}</small></span><span>{{ item.cost }} 分</span><span><STag size="xs" :color="item.enabled ? 'success' : 'secondary'" variant="soft">{{ item.enabled ? '上架' : '下架' }}</STag></span><span class="row-actions"><SButton size="xs" variant="outline" @click="editShopItem(item)">编辑</SButton><SButton size="xs" variant="soft" color="destructive" @click="deleteShopItem(item)">删除</SButton></span></div></div><div v-else class="data-table tx-table"><div class="table-head"><span>用户</span><span>商品</span><span>积分</span><span>时间</span></div><div v-for="tx in shopTransactions" :key="tx.id" class="table-row"><span>@{{ tx.username || tx.user_id }}</span><span>{{ tx.item_name }}</span><span>{{ tx.cost }} 分</span><span>{{ formatTime(tx.created_at) }}</span></div></div></section>
      </section>

      <section v-show="activePage === 'lottery'" class="tab-page manager-layout">
        <aside class="editor-panel wide-editor"><div class="section-title"><span>抽奖项目</span><small>{{ lotteryForm.id ? `#${lotteryForm.id}` : '新建' }}</small></div><label>标题<SInput v-model="lotteryForm.title" placeholder="七月群友福利" /></label><label>奖品<SInput v-model="lotteryForm.prize" placeholder="月卡 / 邀请码 / 积分" /></label><label>描述<SInput v-model="lotteryForm.description" placeholder="规则说明，会展示给群友" /></label><div class="form-two"><label>参与条件<select v-model="lotteryForm.condition_type" class="form-select"><option value="all">所有人</option><option value="checkin">今日签到</option><option value="min_points">积分门槛</option></select></label><label>条件值<SInput v-model="lotteryForm.condition_value" placeholder="积分门槛" /></label></div><div class="form-two"><label>开奖方式<select v-model="lotteryForm.draw_type" class="form-select"><option value="instant">即开即中</option><option value="people">人满开奖</option><option value="time">指定时间</option><option value="manual">手动开奖</option></select></label><label>人数/分钟<SInput v-model="lotteryForm.end_value" placeholder="3" /></label></div><label>指定时间<SInput v-model="lotteryForm.draw_at" placeholder="2026-07-07 20:00" /></label><label>状态<select v-model="lotteryForm.status" class="form-select"><option value="draft">草稿</option><option value="active">进行中</option><option value="cancelled">取消</option></select></label><div class="editor-actions"><SButton size="xs" color="primary" @click="saveLottery">保存抽奖</SButton><SButton size="xs" variant="outline" @click="resetLotteryForm">新建</SButton></div></aside>
        <section class="data-panel"><div class="tabbar"><button :class="{active: activeTab.lottery === 'events'}" @click="activeTab.lottery='events'">抽奖项目</button><button :class="{active: activeTab.lottery === 'participants'}" @click="activeTab.lottery='participants'">参与记录</button></div><div v-if="activeTab.lottery === 'events'" class="data-table lottery-table"><div class="table-head"><span>项目</span><span>方式</span><span>状态</span><span>操作</span></div><div v-for="item in lotteries" :key="item.id" class="table-row"><span><b>#{{ item.id }} {{ item.title || item.prize }}</b><em>{{ item.prize }}</em><small>{{ item.description || '无描述' }}</small></span><span>{{ item.draw_type || item.end_type }}</span><span><STag size="xs" variant="soft">{{ item.status }}</STag></span><span class="row-actions"><SButton size="xs" variant="outline" @click="editLottery(item); loadLotteryParticipants(item); activeTab.lottery='participants'">编辑/参与</SButton><SButton size="xs" variant="outline" :disabled="item.status !== 'active'" @click="drawLottery(item)">开奖</SButton><SButton size="xs" variant="soft" color="warning" :disabled="item.status !== 'active'" @click="cancelLottery(item)">取消</SButton><SButton size="xs" variant="soft" color="destructive" @click="deleteLottery(item)">删除</SButton></span></div></div><div v-else class="data-table"><div class="table-head"><span>用户</span><span>用户ID</span><span>参与时间</span><span>抽奖</span></div><div v-for="p in lotteryParticipants" :key="p.id" class="table-row"><span>@{{ p.username || p.first_name || 'unknown' }}</span><span>{{ p.user_id }}</span><span>{{ formatTime(p.created_at) }}</span><span>#{{ p.event_id }}</span></div><div v-if="!lotteryParticipants.length" class="empty">选择某个抽奖后查看参与记录</div></div></section>
      </section>

      <section v-show="activePage === 'bans'" class="tab-page">
        <SCard class="ban-panel page-panel" title="封禁记录" :description="`${bans.length} 条`"><template #extra><SButton size="xs" variant="outline" @click="loadBans">刷新</SButton></template><div class="ban-list"><div v-if="!bans.length" class="empty">暂无封禁记录</div><div v-for="(item, i) in bans" :key="item.id || i" class="ban-item"><div class="ban-main"><b>@{{ item.username || item.first_name || item.user_id }}</b><span>{{ item.reason || '-' }}</span></div><div class="ban-meta"><span>{{ formatTime(item.time) }}</span><SButton v-if="item.auto_unban" size="xs" variant="outline" color="success" :disabled="item._loading" @click="unban(item)">解封</SButton><STag v-else size="xs" color="secondary" variant="soft">已处理</STag></div></div></div></SCard>
      </section>

      <form v-if="activePage === 'dashboard'" class="send-box floating-chat-send" @submit.prevent="sendMessage">
        <SInput v-model="newMessage" placeholder="发送消息到 TG 群" />
        <SButton type="submit" color="primary" :disabled="sending || !newMessage.trim()">发送</SButton>
      </form>

      <div v-if="toast" class="toast">{{ toast }}</div>
      <div v-if="confirmState.open" class="confirm-mask" @click.self="closeConfirm(false)">
        <div class="confirm-card">
          <h3>{{ confirmState.title }}</h3>
          <p>{{ confirmState.message }}</p>
          <div class="confirm-actions">
            <SButton size="xs" variant="outline" @click="closeConfirm(false)">取消</SButton>
            <SButton size="xs" :color="confirmState.danger ? 'destructive' : 'primary'" @click="closeConfirm(true)">{{ confirmState.confirmText }}</SButton>
          </div>
        </div>
      </div>
      </section>
    </main>
  </SConfigProvider>
</template>
