live.html 23 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>AI 短剧频道</title>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Shrikhand&display=swap" />
<link rel="stylesheet" href="live.css" />
</head>
<body>
<div class="channel">
  <header class="topbar">
    <h1 class="logo">AI 短剧频道</h1>
    <div class="tabs" id="tabs">
      <button data-mode="live" class="active">🔴 直播</button>
      <button data-mode="newest">🆕 最新</button>
      <button data-mode="oldest">⏮ 最早</button>
      <button data-mode="top">❤️ 最热</button>
    </div>
    <div class="spacer"></div>
    <div class="watching" id="watchingCount" hidden></div>
    <button class="topbar-pill" id="chatToggleBtn">✕ 聊天</button>
    <button class="topbar-pill" id="muteBtn">🔈 有声</button>
    <button class="topbar-pill" id="authBtn">登录</button>
    <a class="topbar-pill" href="dance.html">换装跳舞 →</a>
  </header>

  <div class="body" id="body">
    <aside class="left-col" id="leftCol">
      <div class="clip-list" id="clipList"></div>
      <div class="site-credit">🍋 <span>AI 短剧频道</span></div>
    </aside>

    <div class="player-col">
      <div class="player-wrap">
        <div class="live-pill" id="liveDot" hidden><span class="dot"></span>直播中</div>
        <div class="now-playing-box" id="nowPlayingBox" hidden>
          <span class="np-nick" id="nowPlayingNick"></span>
          <span class="np-time" id="nowPlayingTime"></span>
          <div class="np-text" id="nowPlayingText">加载中…</div>
        </div>
        <video id="player" autoplay playsinline></video>
      </div>
    </div>

    <aside class="right-col" id="rightCol" hidden>
      <div class="section-title">聊天</div>
      <div class="chat-list" id="chatList"></div>
      <div class="chat-identity-row" id="chatIdentityRow" hidden>
        <span id="currentNickname"></span>
        <button id="changeNameBtn">改昵称</button>
      </div>
      <div class="chat-input-row">
        <input type="text" id="chatInput" placeholder="说点什么,或者想看什么…" maxlength="300" />
        <button id="chatSendBtn">发送</button>
      </div>
      <div class="say-hint" id="chatHint"></div>
    </aside>

    <!-- flex item of #body (not .channel) so `order` in the mobile media
         query actually places it between the player and left/right-col. -->
    <div class="mobile-subtabs" id="mobileSubtabs" hidden>
      <button data-sub="queue" class="active">排队队列</button>
      <button data-sub="input">聊天</button>
    </div>
  </div>
</div>

<div class="splash" id="splash">
  <div class="splash-inner">
    <div class="splash-logo">AI 短剧频道</div>
    <div class="splash-play">▶</div>
    <div class="splash-sub">一个永不停播的 AI 生成短剧频道<br />弹幕决定下一集演什么</div>
    <div class="splash-credit">🍋 AI 短剧频道 出品</div>
  </div>
</div>

<div class="nickname-modal" id="nicknameModal" hidden>
  <div class="nickname-box">
    <div class="nickname-title">先起个昵称才能发言</div>
    <input type="text" id="nicknameInput" placeholder="你的昵称" maxlength="20" />
    <button id="nicknameConfirmBtn">确定</button>
  </div>
</div>

<!-- 登录完全可选,不阻塞免费模式一的任何现有流程(dev-plan-3.md T22) -->
<div class="nickname-modal" id="authModal" hidden>
  <div class="nickname-box">
    <div class="nickname-title" id="authTitle">登录</div>
    <input type="email" id="authEmail" placeholder="邮箱" />
    <input type="password" id="authPassword" placeholder="密码(至少8位)" />
    <div class="auth-error" id="authError" hidden></div>
    <button id="authSubmitBtn">登录</button>
    <button class="auth-link-btn" id="authToggleBtn">没有账号?去注册</button>
    <button class="auth-link-btn" id="authCloseBtn">取消</button>
  </div>
</div>

<script>
let mode = "live";
let clips = []; // browse mode: full list
let currentIndex = -1;
let currentClipId = null;
let livePollTimer = null;
let chatPollTimer = null;
let advanceTimer = null; // precise, server-endAt-driven switch to the next clip — the 4s poll is just a resync/fallback
let upNextCache = [];
let mobileSub = "queue";

const player = document.getElementById("player");
const clipList = document.getElementById("clipList");
const nowPlayingBox = document.getElementById("nowPlayingBox");
const nowPlayingNick = document.getElementById("nowPlayingNick");
const nowPlayingTime = document.getElementById("nowPlayingTime");
const nowPlayingText = document.getElementById("nowPlayingText");
const liveDot = document.getElementById("liveDot");
const leftCol = document.getElementById("leftCol");
const rightCol = document.getElementById("rightCol");
const mobileSubtabs = document.getElementById("mobileSubtabs");
const chatList = document.getElementById("chatList");
const chatInput = document.getElementById("chatInput");
const chatSendBtn = document.getElementById("chatSendBtn");
const chatHint = document.getElementById("chatHint");
const watchingCount = document.getElementById("watchingCount");
const muteBtn = document.getElementById("muteBtn");
const chatToggleBtn = document.getElementById("chatToggleBtn");
const nicknameModal = document.getElementById("nicknameModal");
const nicknameInput = document.getElementById("nicknameInput");
const nicknameConfirmBtn = document.getElementById("nicknameConfirmBtn");
const chatIdentityRow = document.getElementById("chatIdentityRow");
const changeNameBtn = document.getElementById("changeNameBtn");
const currentNickname = document.getElementById("currentNickname");
const splash = document.getElementById("splash");
const clientId = Math.random().toString(36).slice(2);

muteBtn.addEventListener("click", () => {
  player.muted = !player.muted;
  muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
});

// Default to sound on. Chrome/Safari block unmuted autoplay without a prior
// user gesture on the site, so if the unmuted play() rejects, fall back to
// muted autoplay (always allowed) and let the button reflect the real state.
function tryPlay() {
  player.play().catch(() => {
    player.muted = true;
    muteBtn.textContent = "🔇 静音";
    player.play().catch(() => {});
  });
}

// Click-to-enter splash (same trick as infiniteslop.ai): the video is already
// autoplaying muted underneath, and this click is the user gesture that lets
// us switch it to unmuted playback — the one reliable way around the browser's
// no-unmuted-autoplay-without-a-gesture policy. Also doubles as a branding
// moment (logo/slogan/credit) instead of a bare "click to unmute" prompt.
// Phones stay muted after entry — unmuted autoplay-adjacent playback on
// mobile Safari/Chrome is unreliable and feels intrusive.
splash.addEventListener("click", () => {
  splash.remove();
  const desktop = matchMedia("(min-width: 769px)").matches;
  player.muted = !desktop;
  player.play().catch(() => {
    player.muted = true;
  });
  muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
});

let chatClosed = false;
chatToggleBtn.addEventListener("click", () => {
  chatClosed = !chatClosed;
  chatToggleBtn.textContent = chatClosed ? "聊天" : "✕ 聊天";
  if (mode === "live") rightCol.hidden = chatClosed;
});

function fmtMeta(c) {
  return `${c.width}x${c.height} · ${c.duration}s · ${new Date(c.createdAt).toLocaleString()}`;
}
function escapeHtml(s) {
  const div = document.createElement("div");
  div.textContent = s || "";
  return div.innerHTML;
}
function fmtClock(ts) {
  return new Date(ts).toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
}
// Same per-nickname pastel-hash used by infiniteslop.ai — a stable, deterministic
// color per person without needing a server-assigned palette.
function pastel(name) {
  let h = 0;
  for (const c of name || "") h = (h * 31 + c.charCodeAt(0)) % 360;
  return `hsl(${h},85%,85%)`;
}

// ---- viewer identity: nickname + uid, stored in cookies ----
function getCookie(name) {
  const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
  return m ? decodeURIComponent(m[1]) : null;
}
function setCookie(name, value, days) {
  document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${days * 86400}; path=/; samesite=lax`;
}
function getIdentity() {
  const uid = getCookie("viewer_uid");
  const nickname = getCookie("viewer_nickname");
  return uid && nickname ? { uid, nickname } : null;
}
function updateNicknameLabel() {
  const existing = getIdentity();
  chatIdentityRow.hidden = !existing;
  if (existing) currentNickname.textContent = existing.nickname;
}

// Shared by first-time setup and the always-visible "昵称 ✎" edit button.
function openNicknameModal(prefill) {
  return new Promise((resolve) => {
    nicknameModal.hidden = false;
    nicknameInput.value = prefill || "";
    nicknameInput.focus();
    const onConfirm = () => {
      const nickname = nicknameInput.value.trim().slice(0, 20);
      if (!nickname) return;
      nicknameModal.hidden = true;
      nicknameConfirmBtn.removeEventListener("click", onConfirm);
      nicknameInput.removeEventListener("keydown", onKeydown);
      resolve(nickname);
    };
    const onKeydown = (e) => {
      if (e.key === "Enter") onConfirm();
    };
    nicknameConfirmBtn.addEventListener("click", onConfirm);
    nicknameInput.addEventListener("keydown", onKeydown);
  });
}

function ensureIdentity() {
  const existing = getIdentity();
  if (existing) return Promise.resolve(existing);
  return openNicknameModal("").then((nickname) => {
    const uid = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
    setCookie("viewer_uid", uid, 365);
    setCookie("viewer_nickname", nickname, 365);
    updateNicknameLabel();
    return { uid, nickname };
  });
}

changeNameBtn.addEventListener("click", async () => {
  const existing = getIdentity();
  const nickname = await openNicknameModal(existing ? existing.nickname : "");
  const uid = existing ? existing.uid : crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
  setCookie("viewer_uid", uid, 365);
  setCookie("viewer_nickname", nickname, 365);
  updateNicknameLabel();
});

// First click into the chat box is what prompts for a nickname — not just
// hitting send — so the identity row above the input appears right away.
chatInput.addEventListener("focus", () => ensureIdentity());

updateNicknameLabel();

// ---- account login (dev-plan-3.md T19-T22) — entirely optional. Free
// chat/voting keeps using the plain viewer_uid cookie above exactly as
// before; logging in just also ties that identity to an account
// server-side (T21) and, on login, re-syncs viewer_uid/viewer_nickname
// onto this browser so switching devices or clearing cookies doesn't
// silently start a fresh anonymous identity.
const authBtn = document.getElementById("authBtn");
const authModal = document.getElementById("authModal");
const authTitle = document.getElementById("authTitle");
const authEmail = document.getElementById("authEmail");
const authPassword = document.getElementById("authPassword");
const authError = document.getElementById("authError");
const authSubmitBtn = document.getElementById("authSubmitBtn");
const authToggleBtn = document.getElementById("authToggleBtn");
const authCloseBtn = document.getElementById("authCloseBtn");
let authMode = "login";

function renderAuthButton(user) {
  authBtn.textContent = user ? `${user.nickname || user.email.split("@")[0]} · 退出` : "登录";
  authBtn.dataset.loggedIn = user ? "1" : "";
}

async function refreshAuthState() {
  try {
    const res = await fetch("/api/auth/me");
    if (res.ok) {
      renderAuthButton(await res.json());
      updateNicknameLabel(); // login may have just re-synced viewer_uid/nickname
      return;
    }
  } catch {}
  renderAuthButton(null);
}

function openAuthModal(mode) {
  authMode = mode;
  authTitle.textContent = mode === "login" ? "登录" : "注册";
  authSubmitBtn.textContent = mode === "login" ? "登录" : "注册";
  authToggleBtn.textContent = mode === "login" ? "没有账号?去注册" : "已有账号?去登录";
  authError.hidden = true;
  authEmail.value = "";
  authPassword.value = "";
  authModal.hidden = false;
  authEmail.focus();
}

authBtn.addEventListener("click", async () => {
  if (authBtn.dataset.loggedIn) {
    await fetch("/api/auth/logout", { method: "POST" });
    await refreshAuthState();
    return;
  }
  openAuthModal("login");
});
authToggleBtn.addEventListener("click", () => openAuthModal(authMode === "login" ? "register" : "login"));
authCloseBtn.addEventListener("click", () => {
  authModal.hidden = true;
});
async function submitAuth() {
  const email = authEmail.value.trim();
  const password = authPassword.value;
  authError.hidden = true;
  const res = await fetch(`/api/auth/${authMode}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  const body = await res.json().catch(() => ({}));
  if (!res.ok) {
    authError.textContent = body.error || "出错了,请重试";
    authError.hidden = false;
    return;
  }
  authModal.hidden = true;
  await refreshAuthState();
}
authSubmitBtn.addEventListener("click", submitAuth);
authPassword.addEventListener("keydown", (e) => {
  if (e.key === "Enter") submitAuth();
});

refreshAuthState();

function renderBrowseList() {
  if (clips.length === 0) {
    clipList.innerHTML = `<div class="section-head">片段列表</div><div class="empty-hint">片段库为空</div>`;
    return;
  }
  const rows = clips
    .map(
      (c, i) => `
    <div class="clip-row ${i === currentIndex ? "active" : ""}" data-i="${i}">
      <div class="prompt">${escapeHtml(c.prompt)}</div>
      <div class="meta">${fmtMeta(c)} · ❤️ <span data-likes="${c.id}">${c.likes || 0}</span></div>
    </div>`
    )
    .join("");
  clipList.innerHTML = `<div class="section-head">片段列表</div>${rows}`;
  clipList.querySelectorAll(".clip-row").forEach((row) => {
    row.addEventListener("click", (e) => {
      if (e.target.dataset.likes) return;
      playBrowse(Number(row.dataset.i));
    });
  });
  clipList.querySelectorAll("[data-likes]").forEach((el) => {
    el.style.cursor = "pointer";
    el.addEventListener("click", async (e) => {
      e.stopPropagation();
      const res = await fetch(`/api/like/${el.dataset.likes}`, { method: "POST" });
      if (res.ok) el.textContent = (await res.json()).likes;
    });
  });
}

function setNowPlaying(nick, time, text) {
  nowPlayingBox.hidden = false;
  nowPlayingNick.hidden = !nick;
  nowPlayingNick.textContent = nick || "";
  nowPlayingTime.hidden = !time;
  nowPlayingTime.textContent = time || "";
  nowPlayingText.textContent = text;
}

function playBrowse(index) {
  if (index < 0 || index >= clips.length) return;
  currentIndex = index;
  const c = clips[index];
  player.src = `/lib/video/${c.id}`;
  tryPlay();
  setNowPlaying(null, null, c.prompt);
  renderBrowseList();
}

player.addEventListener("ended", () => {
  if (mode !== "live" && clips.length) playBrowse((currentIndex + 1) % clips.length);
});

async function loadBrowse(sort) {
  const res = await fetch(`/api/library?sort=${sort}`);
  clips = await res.json();
  currentIndex = -1;
  renderBrowseList();
  if (clips.length) playBrowse(0);
}

// Left queue, grouped like infiniteslop.ai: 接下来播放 (already scheduled) /
// 生成中 (mid-generation) / 排队中 (waiting their turn — votable).
function renderLiveList(state) {
  const upcoming = state.upNext || [];
  const queue = state.queue || [];
  const generating = queue.filter((q) => q.status === "generating");
  const waiting = queue.filter((q) => q.status === "matched" || q.status === "ready");
  const failed = queue.filter((q) => q.status === "failed");

  const upcomingHtml = upcoming
    .map(
      (c) => `
      <div class="clip-row">
        <div class="prompt">${escapeHtml(c.prompt)}</div>
        ${c.requestedBy ? `<div class="meta">by ${escapeHtml(c.requestedBy)}</div>` : ""}
      </div>`
    )
    .join("");
  const generatingHtml = generating
    .map(
      (q) => `
      <div class="clip-row gen">
        <div class="prompt">💬 ${escapeHtml(q.prompt)}</div>
        <div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}生成中…</div>
      </div>`
    )
    .join("");
  const waitingHtml = waiting
    .map(
      (q) => `
      <div class="qrow">
        <div class="clip-row">
          <div class="prompt">💬 ${escapeHtml(q.prompt)}</div>
          <div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}即将播放</div>
        </div>
        <button class="up-btn ${q.voted ? "voted" : ""}" data-vote="${q.id}">▲<span>${q.votes || 0}</span></button>
      </div>`
    )
    .join("");
  const failedHtml = failed
    .map(
      (q) => `
      <div class="clip-row failed">
        <div class="prompt">💬 ${escapeHtml(q.prompt)}</div>
        <div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}❌ 生成失败</div>
      </div>`
    )
    .join("");

  clipList.innerHTML =
    (upcomingHtml ? `<div class="section-head">接下来播放</div>${upcomingHtml}` : "") +
    (generatingHtml ? `<div class="section-head">生成中</div>${generatingHtml}` : "") +
    (waitingHtml || failedHtml ? `<div class="section-head">排队中</div>${waitingHtml}${failedHtml}` : "") ||
    `<div class="empty-hint">暂无排队</div>`;

  clipList.querySelectorAll("[data-vote]").forEach((btn) => {
    btn.addEventListener("click", () => voteQueueItem(btn.dataset.vote, btn));
  });
}

async function voteQueueItem(id, btn) {
  const identity = await ensureIdentity();
  btn.disabled = true;
  try {
    const res = await fetch(`/api/queue/vote/${id}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ uid: identity.uid }),
    });
    if (!res.ok) return;
    const data = await res.json();
    btn.classList.toggle("voted", data.voted);
    btn.querySelector("span").textContent = data.votes;
  } finally {
    btn.disabled = false;
  }
}

function switchToClip(clip, offsetSec, requestedBy) {
  currentClipId = clip.id;
  player.src = `/lib/video/${clip.id}`;
  if (offsetSec > 0) {
    player.addEventListener(
      "loadedmetadata",
      () => {
        player.currentTime = Math.min(offsetSec, player.duration || offsetSec);
      },
      { once: true }
    );
  }
  tryPlay();
  setNowPlaying(requestedBy, fmtClock(Date.now()), clip.prompt);
}

async function pollLive() {
  try {
    const identity = getIdentity();
    const res = await fetch(`/api/live/state?cid=${clientId}${identity ? `&uid=${encodeURIComponent(identity.uid)}` : ""}`);
    const state = await res.json();
    if (mode !== "live") return;
    watchingCount.hidden = false;
    watchingCount.textContent = `👀 ${state.watching}`;
    renderLiveList(state);
    upNextCache = state.upNext || [];

    clearTimeout(advanceTimer);
    if (state.current) {
      if (state.current.clip.id !== currentClipId) {
        const offsetSec = Math.max(0, (state.now - state.current.startAt) / 1000);
        switchToClip(state.current.clip, offsetSec, state.current.requestedBy);
      }
      // Fire the switch to the next clip exactly when this one should end,
      // instead of waiting for the next 4s poll to notice — the poll still
      // runs on schedule and will correct any drift.
      if (upNextCache.length) {
        const msUntilEnd = state.current.endAt - Date.now();
        advanceTimer = setTimeout(() => switchToClip(upNextCache[0], 0, upNextCache[0].requestedBy), Math.max(0, msUntilEnd));
      }
    }
  } catch {
    // transient — next poll retries
  }
}

const chatStatusLabel = { rejected: "❌ 未通过审核", generating: "生成中…", matched: "即将播放", scheduled: "即将播放", ready: "已排播放", failed: "❌ 生成失败" };
function renderChat(messages) {
  const atBottom = chatList.scrollHeight - chatList.scrollTop - chatList.clientHeight < 40;
  chatList.innerHTML = messages
    .map((m) => {
      const status = m.status && chatStatusLabel[m.status] ? `<span class="chat-status">${chatStatusLabel[m.status]}</span>` : "";
      return `<div class="chat-msg" style="background:${pastel(m.nickname)}"><b class="chat-nick">${escapeHtml(m.nickname)}</b><span class="chat-text">${escapeHtml(m.text)}</span>${status}</div>`;
    })
    .join("");
  if (atBottom) chatList.scrollTop = chatList.scrollHeight;
}

async function pollChat() {
  try {
    const res = await fetch(`/api/chat?cid=${clientId}`);
    renderChat(await res.json());
  } catch {
    // transient — next poll retries
  }
}

async function sendChat() {
  const text = chatInput.value.trim();
  if (!text) return;
  const identity = await ensureIdentity();
  chatSendBtn.disabled = true;
  try {
    const res = await fetch("/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ uid: identity.uid, nickname: identity.nickname, text }),
    });
    const data = await res.json();
    if (res.status === 429) {
      chatHint.textContent = data.error;
      return;
    }
    chatInput.value = "";
    chatHint.textContent =
      data.status === "rejected" ? `未通过审核:${data.reason}` : data.status === "matched" ? "已匹配片段,即将播放" : data.status === "generating" ? "库里没有,已提交生成,请稍候…" : "";
    pollChat();
  } finally {
    chatSendBtn.disabled = false;
  }
}
chatSendBtn.addEventListener("click", sendChat);
chatInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter") sendChat();
});

function applyMobileSub() {
  leftCol.classList.toggle("mobile-inactive", mobileSub !== "queue");
  rightCol.classList.toggle("mobile-inactive", mobileSub !== "input");
  mobileSubtabs.querySelectorAll("button").forEach((b) => b.classList.toggle("active", b.dataset.sub === mobileSub));
}
mobileSubtabs.querySelectorAll("button").forEach((b) =>
  b.addEventListener("click", () => {
    mobileSub = b.dataset.sub;
    applyMobileSub();
  })
);

async function setMode(newMode) {
  mode = newMode;
  document.querySelectorAll("#tabs button").forEach((b) => b.classList.toggle("active", b.dataset.mode === newMode));
  clearInterval(livePollTimer);
  clearInterval(chatPollTimer);
  clearTimeout(advanceTimer);
  currentClipId = null;
  chatToggleBtn.hidden = newMode !== "live";
  if (newMode === "live") {
    liveDot.hidden = false;
    rightCol.hidden = chatClosed;
    mobileSubtabs.hidden = false;
    applyMobileSub();
    await Promise.all([pollLive(), pollChat()]);
    livePollTimer = setInterval(pollLive, 4000);
    chatPollTimer = setInterval(pollChat, 3000);
  } else {
    liveDot.hidden = true;
    rightCol.hidden = true;
    mobileSubtabs.hidden = true;
    watchingCount.hidden = true;
    leftCol.classList.remove("mobile-inactive");
    await loadBrowse(newMode);
  }
}

document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => setMode(b.dataset.mode)));

setMode("live");
</script>
</body>
</html>