dance.html 28.7 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 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>换装跳舞直播间</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" />
<link rel="stylesheet" href="dance.css" />
<style>
  .like-btn { margin-top: 6px; font: bold 12px Tahoma, sans-serif; cursor: pointer; border: 3px solid #000; border-radius: 10px; background: #fff; color: var(--ink); padding: 4px 10px; box-shadow: var(--shadow-sm); }
  .like-btn:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #000; }
</style>
</head>
<body>
<div class="channel">
  <header class="topbar">
    <h1 class="logo">换装跳舞直播间</h1>
    <div class="spacer"></div>
    <div class="watching" id="watchingCount" hidden></div>
    <button class="topbar-pill" id="muteBtn">🔇 静音</button>
    <button class="topbar-pill" id="topupBtn" hidden>💰 充值</button>
    <button class="topbar-pill" id="authBtn">登录</button>
    <a class="topbar-pill" href="live.html">AI 短剧频道 →</a>
  </header>

  <div id="topupBanner" hidden></div>

  <div class="body" id="body">
    <aside class="left-col" id="leftCol">
      <div class="wardrobe-tabs" id="wardrobeTabs">
        <button data-tab="wardrobe" class="active">衣柜</button>
        <button data-tab="garment">传衣服</button>
        <button data-tab="character">传人</button>
      </div>
      <div class="clip-list" id="wardrobePanel"></div>
      <div class="site-credit">🍋 <span>换装跳舞直播间</span></div>
    </aside>

    <div class="player-col">
      <div class="player-wrap">
        <div class="live-pill" id="liveDot"><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><button class="like-btn" id="likeBtn" hidden>❤️ <span id="likeCount">0</span></button></div>
        </div>
        <video id="player" autoplay playsinline muted></video>
      </div>
    </div>

    <aside class="right-col" id="rightCol">
      <div class="section-title">互动</div>
      <div class="clip-list" id="queueList"></div>
    </aside>

    <div class="mobile-subtabs" id="mobileSubtabs">
      <button data-sub="wardrobe" class="active">衣柜</button>
      <button data-sub="queue">互动</button>
    </div>
  </div>
</div>

<!-- 5.1 节:首次进入强制年龄确认,非模态(点背景不关),一次性 cookie 记忆 -->
<div class="nickname-modal" id="ageGateModal" hidden>
  <div class="nickname-box age-box">
    <div class="nickname-title">进入前确认</div>
    <div class="age-disclaimer">
      本频道播放 AI 生成的换装舞蹈内容,服饰类别可能包含泳装/舞台表演装等,全部角色与画面均由 AI 生成,不代表真实人物行为。<br /><br />
      继续访问即表示您确认已年满 18 周岁。
    </div>
    <button id="ageConfirmBtn">我已满18岁,继续</button>
  </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>

<!-- T29: topup tier picker — reuses .nickname-modal/.nickname-box's shell -->
<div class="nickname-modal" id="topupModal" hidden>
  <div class="nickname-box">
    <div class="nickname-title">充值</div>
    <div id="topupTierList"></div>
    <button class="auth-link-btn" id="topupCloseBtn">取消</button>
  </div>
</div>

<script>
let wardrobe = [];
let leftTab = "wardrobe";
let mobileSub = "wardrobe";
let currentClipId = null;
let statePollTimer = null;
let advanceTimer = null;
let upNextCache = [];
const clientId = Math.random().toString(36).slice(2);

const player = document.getElementById("player");
const wardrobePanel = document.getElementById("wardrobePanel");
const queueList = document.getElementById("queueList");
const nowPlayingBox = document.getElementById("nowPlayingBox");
const nowPlayingNick = document.getElementById("nowPlayingNick");
const nowPlayingTime = document.getElementById("nowPlayingTime");
const nowPlayingText = document.getElementById("nowPlayingText");
const likeBtn = document.getElementById("likeBtn");
const likeCount = document.getElementById("likeCount");
const watchingCount = document.getElementById("watchingCount");
const muteBtn = document.getElementById("muteBtn");
const leftCol = document.getElementById("leftCol");
const rightCol = document.getElementById("rightCol");
const mobileSubtabs = document.getElementById("mobileSubtabs");
const ageGateModal = document.getElementById("ageGateModal");
const ageConfirmBtn = document.getElementById("ageConfirmBtn");
const nicknameModal = document.getElementById("nicknameModal");
const nicknameInput = document.getElementById("nicknameInput");
const nicknameConfirmBtn = document.getElementById("nicknameConfirmBtn");

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" });
}
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`;
}

// ---- 5.1 年龄确认:非模态强制,一次性记忆,不能点背景关闭(没有绑定 backdrop click) ----
if (!getCookie("dance_age_confirmed")) ageGateModal.hidden = false;
ageConfirmBtn.addEventListener("click", () => {
  setCookie("dance_age_confirmed", "1", 365);
  ageGateModal.hidden = true;
});

// ---- viewer identity: same cookie pair as live.html, only needed to vote ----
function getIdentity() {
  const uid = getCookie("viewer_uid");
  const nickname = getCookie("viewer_nickname");
  return uid && nickname ? { uid, nickname } : null;
}
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);
    return { uid, nickname };
  });
}

// ---- account login (dev-plan-3.md T19-T22) — entirely optional. Free
// wardrobe picks/voting keep 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 topupBtn = document.getElementById("topupBtn");
const topupBanner = document.getElementById("topupBanner");
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";
let currentUser = null; // T28/T29 need to know login/emailVerified/creditBalance beyond just "is authBtn's dot lit"

function renderAuthButton(user) {
  currentUser = user;
  authBtn.textContent = user ? `${user.nickname || user.email.split("@")[0]} · 💰${user.creditBalance} · 退出` : "登录";
  authBtn.dataset.loggedIn = user ? "1" : "";
  topupBtn.hidden = !user;
  if (leftTab === "garment" || leftTab === "character") renderWardrobe(); // price/balance-gated panels depend on login state
}

async function refreshAuthState() {
  try {
    const res = await fetch("/api/auth/me");
    if (res.ok) {
      renderAuthButton(await res.json());
      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();

// ---- T29: 积分余额 + 充值 (dev-plan-4.md) ----
let pricing = [];
async function loadPricing() {
  try {
    pricing = await fetch("/api/pricing").then((r) => r.json());
  } catch {
    pricing = [];
  }
}

const topupModal = document.getElementById("topupModal");
const topupTierList = document.getElementById("topupTierList");
const topupCloseBtn = document.getElementById("topupCloseBtn");

function renderTopupTiers() {
  const tiers = pricing.filter((p) => p.kind === "topup_tier");
  topupTierList.innerHTML = tiers.length
    ? tiers
        .map(
          (t) => `
      <div class="topup-tier">
        <div><div class="credits">${t.credits} 积分</div>${t.priceCents != null ? `<div class="hint">$${(t.priceCents / 100).toFixed(2)}</div>` : ""}</div>
        <button data-tier="${t.key}">购买</button>
      </div>`
        )
        .join("")
    : `<div class="empty-hint">暂无可购买档位</div>`;
  topupTierList.querySelectorAll("[data-tier]").forEach((btn) =>
    btn.addEventListener("click", async () => {
      btn.disabled = true;
      try {
        const res = await fetch("/api/credits/checkout", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ tierKey: btn.dataset.tier }),
        });
        const data = await res.json();
        if (!res.ok) {
          alert(data.error || "创建支付会话失败");
          return;
        }
        location.href = data.url; // Stripe's hosted page (real) or the mock completion URL — both redirect back here
      } finally {
        btn.disabled = false;
      }
    })
  );
}

topupBtn.addEventListener("click", async () => {
  if (!currentUser) {
    openAuthModal("login");
    return;
  }
  if (!pricing.length) await loadPricing();
  renderTopupTiers();
  topupModal.hidden = false;
});
topupCloseBtn.addEventListener("click", () => {
  topupModal.hidden = true;
});

// A redirect back from Stripe (or the mock checkout) lands here with
// ?topup=success/cancelled — show a one-off banner, then scrub the query
// string so a page refresh doesn't keep re-showing it.
(function showTopupBanner() {
  const topup = new URLSearchParams(location.search).get("topup");
  if (!topup) return;
  topupBanner.hidden = false;
  topupBanner.className = topup === "success" ? "topup-banner success" : "topup-banner cancelled";
  topupBanner.textContent = topup === "success" ? "充值成功!" : "已取消充值";
  history.replaceState(null, "", location.pathname);
})();

loadPricing();

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

// ---- 左侧栏:衣柜 / 传衣服 / 传人 三个 tab(3.1 节,本期只做衣柜) ----
function garmentName(id) {
  const g = wardrobe.find((x) => x.id === id);
  return g ? g.name : id;
}

function renderWardrobe() {
  document.querySelectorAll("#wardrobeTabs button").forEach((b) => b.classList.toggle("active", b.dataset.tab === leftTab));
  if (leftTab === "garment") {
    renderGarmentUploadPanel();
    return;
  }
  if (leftTab === "character") {
    renderCharacterUploadPanel();
    return;
  }
  if (wardrobe.length === 0) {
    wardrobePanel.innerHTML = `<div class="empty-hint">衣柜还是空的</div>`;
    return;
  }
  wardrobePanel.innerHTML = `<div class="wardrobe-grid">${wardrobe
    .map(
      (g) => `
      <div class="wardrobe-card" data-garment="${g.id}">
        <img src="${escapeHtml(g.thumbnailUrl || g.imageUrl)}" />
        <div class="name">${escapeHtml(g.name)}</div>
      </div>`
    )
    .join("")}</div>`;
  wardrobePanel.querySelectorAll("[data-garment]").forEach((card) =>
    card.addEventListener("click", () => pickGarment(card.dataset.garment, card))
  );
}

// ---- T28: 模式二"传衣服"(付费,需登录+邮箱验证) ----
function renderGarmentUploadPanel() {
  const spendGarment = pricing.find((p) => p.key === "spend_garment");
  const priceLine = spendGarment ? `上传一张衣服照片,AI 换装生成跳舞视频,扣 ${spendGarment.credits} 积分` : "加载价格中…";
  wardrobePanel.innerHTML = `
    <div class="upload-panel">
      <div class="hint">${priceLine}</div>
      <input type="file" id="garmentFileInput" accept="image/jpeg,image/png,image/webp" />
      <button id="garmentUploadBtn">上传并生成</button>
      <div class="upload-error" id="garmentUploadError" hidden></div>
      <div class="upload-status" id="garmentUploadStatus" hidden></div>
    </div>`;
  document.getElementById("garmentUploadBtn").addEventListener("click", submitGarmentUpload);
}

async function submitGarmentUpload() {
  const fileInput = document.getElementById("garmentFileInput");
  const errorBox = document.getElementById("garmentUploadError");
  const statusBox = document.getElementById("garmentUploadStatus");
  const btn = document.getElementById("garmentUploadBtn");
  errorBox.hidden = true;
  statusBox.hidden = true;

  // 未登录/未验证先引导,而不是提交后静默失败(T28 验收标准)
  if (!currentUser) {
    openAuthModal("login");
    return;
  }
  if (!currentUser.emailVerified) {
    errorBox.hidden = false;
    errorBox.textContent = "请先完成邮箱验证后再上传(查看邮箱中的验证链接)";
    return;
  }
  const file = fileInput.files[0];
  if (!file) {
    errorBox.hidden = false;
    errorBox.textContent = "请先选择一张图片";
    return;
  }

  btn.disabled = true;
  statusBox.hidden = false;
  statusBox.textContent = "上传中…";
  try {
    const fd = new FormData();
    fd.append("file", file);
    const res = await fetch("/api/dance/upload-garment", { method: "POST", body: fd });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      statusBox.hidden = true;
      errorBox.hidden = false;
      if (res.status === 402) {
        errorBox.textContent = "积分不足,请先充值";
      } else {
        errorBox.textContent = data.error || "上传失败";
      }
      return;
    }
    const message = data.status === "ready" ? "生成完成,已加入播放队列!" : "生成中,完成后会自动加入播放队列";
    // refreshAuthState() re-renders this whole panel (creditBalance changed
    // -> renderAuthButton -> renderWardrobe) — setting the message before
    // that would just get wiped by the fresh render, so set it after and
    // re-query, not on the (now-replaced) statusBox/fileInput above.
    await refreshAuthState();
    document.getElementById("garmentFileInput").value = "";
    const freshStatusBox = document.getElementById("garmentUploadStatus");
    freshStatusBox.hidden = false;
    freshStatusBox.textContent = message;
    pollState(); // surface the new queue entry immediately, same as pickGarment
  } catch {
    statusBox.hidden = true;
    errorBox.hidden = false;
    errorBox.textContent = "网络错误,请重试";
  } finally {
    btn.disabled = false;
  }
}

// ---- T37: 模式三"传人"(付费,需登录+邮箱验证) ----
function renderCharacterUploadPanel() {
  const spendCharacter = pricing.find((p) => p.key === "spend_character_per_segment");
  const costPerSegment = spendCharacter ? Math.ceil(spendCharacter.credits / (spendCharacter.segmentsPerUnit || 1)) : null;
  const priceLine = costPerSegment != null ? `上传一张人物照片,每购买 1 个 10 秒片段扣 ${costPerSegment} 积分——买得越多,这个新角色在直播间露出的时长越长` : "加载价格中…";
  const garmentOptions = wardrobe.map((g) => `<option value="${g.id}">${escapeHtml(g.name)}</option>`).join("");
  wardrobePanel.innerHTML = `
    <div class="upload-panel">
      <div class="hint">${priceLine}</div>
      <input type="file" id="characterFileInput" accept="image/jpeg,image/png,image/webp" />
      <label class="field-label" for="characterGarmentSelect">搭配衣服(不选则随机搭配)</label>
      <select id="characterGarmentSelect">
        <option value="">随机搭配</option>
        ${garmentOptions}
      </select>
      <label class="field-label" for="characterSegmentsInput">购买片段数(每个 10 秒)</label>
      <input type="number" id="characterSegmentsInput" min="1" max="20" value="3" style="width:100%;margin-bottom:10px;" />
      <button id="characterUploadBtn">上传并插队播放</button>
      <div class="upload-error" id="characterUploadError" hidden></div>
      <div class="upload-status" id="characterUploadStatus" hidden></div>
    </div>`;
  document.getElementById("characterUploadBtn").addEventListener("click", submitCharacterUpload);
}

async function submitCharacterUpload() {
  const fileInput = document.getElementById("characterFileInput");
  const garmentSelect = document.getElementById("characterGarmentSelect");
  const segmentsInput = document.getElementById("characterSegmentsInput");
  const errorBox = document.getElementById("characterUploadError");
  const statusBox = document.getElementById("characterUploadStatus");
  const btn = document.getElementById("characterUploadBtn");
  errorBox.hidden = true;
  statusBox.hidden = true;
  statusBox.classList.remove("boosted");

  // 未登录/未验证先引导,而不是提交后静默失败(同 T28 验收标准)
  if (!currentUser) {
    openAuthModal("login");
    return;
  }
  if (!currentUser.emailVerified) {
    errorBox.hidden = false;
    errorBox.textContent = "请先完成邮箱验证后再上传(查看邮箱中的验证链接)";
    return;
  }
  const file = fileInput.files[0];
  if (!file) {
    errorBox.hidden = false;
    errorBox.textContent = "请先选择一张人物照片";
    return;
  }

  btn.disabled = true;
  statusBox.hidden = false;
  statusBox.textContent = "上传中…";
  try {
    const fd = new FormData();
    fd.append("file", file);
    if (garmentSelect.value) fd.append("garmentId", garmentSelect.value);
    fd.append("segments", segmentsInput.value || "3");
    const res = await fetch("/api/dance/upload-character", { method: "POST", body: fd });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) {
      statusBox.hidden = true;
      errorBox.hidden = false;
      errorBox.textContent = res.status === 402 ? "积分不足,请先充值" : data.error || "上传失败";
      return;
    }
    // 付费插队跟模式一/二的普通"排队"视觉上要有区别(T37 验收标准)——
    // 不管此刻是"生成中"还是缓存命中的"ready",都是走 priorityInbox
    // 插队通道,不进投票队列. Message set after refreshAuthState(), same
    // reasoning as submitGarmentUpload — it re-renders this panel
    // (creditBalance changed), which would wipe anything set beforehand.
    const message = data.status === "ready" ? "🎉 生成完成,已插队播放!" : "🎉 生成中,完成后将直接插队播放(不用排队投票)";
    await refreshAuthState();
    document.getElementById("characterFileInput").value = "";
    const freshStatusBox = document.getElementById("characterUploadStatus");
    freshStatusBox.hidden = false;
    freshStatusBox.classList.add("boosted");
    freshStatusBox.textContent = message;
    pollState(); // surface the new priority entry immediately
  } catch {
    statusBox.hidden = true;
    errorBox.hidden = false;
    errorBox.textContent = "网络错误,请重试";
  } finally {
    btn.disabled = false;
  }
}

document.querySelectorAll("#wardrobeTabs button").forEach((b) =>
  b.addEventListener("click", () => {
    leftTab = b.dataset.tab;
    renderWardrobe();
  })
);

async function loadWardrobe() {
  const res = await fetch("/api/dance/wardrobe");
  wardrobe = await res.json();
  renderWardrobe();
}

async function pickGarment(garmentId, card) {
  if (card.classList.contains("disabled")) return;
  card.classList.add("disabled");
  try {
    const identity = getIdentity(); // 免费模式一不强制登录(架构文档 2.7 节)— 有 cookie 就带上昵称,没有也能提交
    const res = await fetch("/api/dance/pick", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ garmentId, nickname: identity ? identity.nickname : undefined }),
    });
    const data = await res.json();
    if (!res.ok) {
      alert(data.error || "提交失败");
      return;
    }
    pollState();
  } finally {
    card.classList.remove("disabled");
  }
}

// ---- 右侧栏:接下来播放 / 生成中 / 排队中(可点赞),复用 live.html 的分组思路 ----
function renderQueue(state) {
  const upcoming = state.upNext || [];
  const queue = state.queue || [];
  const generating = queue.filter((q) => q.status === "generating");
  const failed = queue.filter((q) => q.status === "failed");

  const upcomingHtml = upcoming
    .map(
      (c) => `
      <div class="clip-row">
        <div class="prompt">${escapeHtml(c.prompt || garmentName(c.garmentId))}</div>
        ${c.requestedBy ? `<div class="meta">by ${escapeHtml(c.requestedBy)}</div>` : ""}
      </div>`
    )
    .join("");
  const generatingHtml = generating
    .map(
      (q) => `
      <div class="qrow">
        <div class="clip-row gen">
          <div class="prompt">👗 ${escapeHtml(garmentName(q.garmentId))}</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(garmentName(q.garmentId))}</div>
        <div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}❌ 生成失败</div>
      </div>`
    )
    .join("");

  queueList.innerHTML =
    (upcomingHtml ? `<div class="section-head">接下来播放</div>${upcomingHtml}` : "") +
    (generatingHtml ? `<div class="section-head">生成中(可点赞)</div>${generatingHtml}` : "") +
    (failedHtml ? `<div class="section-head">生成失败</div>${failedHtml}` : "") ||
    `<div class="empty-hint">暂无排队,去左边衣柜选一件衣服吧</div>`;

  queueList.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/dance/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;
  }
}

// ---- 播放器:跟 live.html 一样,服务端 endAt 是权威时钟,轮询只是纠偏 ----
function setNowPlaying(nick, time, text, clip) {
  nowPlayingBox.hidden = false;
  nowPlayingNick.hidden = !nick;
  nowPlayingNick.textContent = nick || "";
  nowPlayingTime.hidden = !time;
  nowPlayingTime.textContent = time || "";
  nowPlayingText.textContent = text;
  likeBtn.hidden = !clip;
  if (clip) {
    likeCount.textContent = clip.likes || 0;
    likeBtn.onclick = async () => {
      const res = await fetch(`/api/like/${clip.id}`, { method: "POST" });
      if (res.ok) likeCount.textContent = (await res.json()).likes;
    };
  }
}

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 }
    );
  }
  player.play().catch(() => {});
  setNowPlaying(requestedBy, fmtClock(Date.now()), clip.prompt, clip);
}

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

    clearTimeout(advanceTimer);
    if (state.current && state.current.clip) {
      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);
      }
      if (upNextCache.length) {
        const msUntilEnd = state.current.endAt - Date.now();
        advanceTimer = setTimeout(() => switchToClip(upNextCache[0], 0, upNextCache[0].requestedBy), Math.max(0, msUntilEnd));
      }
    } else if (!currentClipId) {
      nowPlayingText.textContent = "衣柜还没有内容,去左边选一件衣服开播吧";
      nowPlayingBox.hidden = false;
    }
  } catch {
    // transient — next poll retries
  }
}

function applyMobileSub() {
  leftCol.classList.toggle("mobile-inactive", mobileSub !== "wardrobe");
  rightCol.classList.toggle("mobile-inactive", mobileSub !== "queue");
  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();
  })
);
applyMobileSub();

loadWardrobe();
pollState();
statePollTimer = setInterval(pollState, 4000);
</script>
</body>
</html>