dance.html 49.5 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 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
<!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; }
  .wardrobe-card .meta { font-size: 11px; font-weight: bold; opacity: .6; margin-top: 3px; }
</style>
</head>
<body>
<div class="channel">
  <header class="topbar">
    <h1 class="logo" id="roomTitle">换装跳舞直播间</h1>
    <div class="spacer"></div>
    <div class="watching" id="watchingCount" hidden></div>
    <button class="topbar-pill" id="muteBtn">🔇 静音</button>
    <a class="topbar-pill" id="myWorksLink" href="my-works.html" hidden>📁 我的作品</a>
    <button class="topbar-pill" id="topupBtn" hidden>💰 充值</button>
    <button class="topbar-pill" id="authBtn">登录</button>
    <a class="topbar-pill" href="dance-rooms.html">🏠 直播间列表</a>
    <a class="topbar-pill" href="live.html">AI 短剧频道 →</a>
  </header>

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

  <div class="body" id="body">
    <!-- T42: "传衣服"/"传人" 两个 tab 撤掉了,付费上传的入口挪到底下换装
         横条里的 DIY 卡片(见 #diyModal)——左栏现在只剩"待播放",不需要
         tab 切换 UI 了。 -->
    <aside class="left-col" id="leftCol">
      <div class="section-head">待播放</div>
      <div class="clip-list" id="leftPanel"></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>
        <!-- T40: 居中"正在换装"胶囊,取代原来贴在左上角、跟昵称混在一起的
             now-playing-box 文字框;空态提示文案("还没有可播放的内容…")
             复用同一个胶囊,只是不带 🔥 前缀(见 setNowPlaying)。 -->
        <div class="active-pill" id="activePill" hidden>
          <span class="active-label" id="activeLabel">🔥 正在换装</span>
          <span class="active-nick" id="activeNick"></span>
        </div>
        <div class="queue-strip" id="queueStrip" hidden></div>
        <div class="now-playing-box" id="nowPlayingBox" hidden>
          <button class="like-btn" id="likeBtn" hidden>❤️ <span id="likeCount">0</span></button>
        </div>
        <video id="player" autoplay playsinline></video>
        <div class="curtain" id="curtain"><div class="curtain-half left"></div><div class="curtain-half right"></div></div>
      </div>
      <!-- T42: 原来右侧栏的"选衣服"网格改成贴视频底部的横向条。 -->
      <div class="wardrobe-strip-wrap">
        <div class="wardrobe-strip-title">选衣服</div>
        <div class="wardrobe-strip" id="pickPanel"></div>
      </div>
    </div>

    <!-- T46: 右侧栏回来了,这次装的是聊天,不是选衣服——跟 live.html 同一套
         .chat-list/.chat-msg/.chat-input-row 样式,dance room 专属的
         /api/dance/chat 接口(不走 live.html 那个会触发生成任务的 /api/chat,
         见 server.js pushDanceChatMessage 的注释)。 -->
    <aside class="right-col" id="rightCol">
      <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>
  </div>
</div>

<!-- 点击进入蒙版(同 live.html):视频先静音自动播放,这次点击是浏览器要求的
     "用户手势",借它把播放切到有声——绕开"未经手势不能自动有声播放"的限制。 -->
<div class="splash" id="splash">
  <div class="splash-inner">
    <div class="splash-logo">换装跳舞直播间</div>
    <div class="splash-play">▶</div>
    <div class="splash-sub">AI 生成的换装舞蹈直播<br />点击进入,开声音看直播</div>
    <div class="splash-credit">🍋 换装跳舞直播间 出品</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>

<!-- T42: 换装横条末尾的 DIY 卡片点开后弹这个——先二选一,再展开对应的
     上传表单(原来 T28/T37 各自的左栏 tab 面板,原样搬进来,付费/登录/
     邮箱验证门槛完全不变,只是换了个入口位置)。"传人"会离开当前房间,
     文案里必须写清楚,不能跟"传衣服"的"原地生成"混为一谈。 -->
<div class="nickname-modal" id="diyModal" hidden>
  <div class="nickname-box diy-box">
    <div class="nickname-title">上传</div>
    <div id="diyChoice">
      <button class="diy-choice-btn" data-diy="garment">
        👗 传衣服给 TA 穿
        <span class="diy-choice-hint">原地生成,留在当前房间</span>
      </button>
      <button class="diy-choice-btn" data-diy="character">
        🧑 传新角色,开一个新直播间
        <span class="diy-choice-hint">会离开当前房间,去新角色自己的房间</span>
      </button>
    </div>
    <div id="diyForm"></div>
    <button class="auth-link-btn" id="diyCloseBtn">取消</button>
  </div>
</div>

<script>
// One live room per character (2026-09): this page is always scoped to one
// characterId from the URL — no characterId means there's no room to show.
const characterId = new URLSearchParams(location.search).get("characterId");
if (!characterId) location.href = "dance-rooms.html";

let wardrobe = [];
let lastState = null; // latest /api/dance/live/state response — the "待播放" left tab renders off this
let diyMode = null; // T42: null | "garment" | "character" — which upload form the DIY modal is showing, if any
let currentClipId = null;
let statePollTimer = null;
let advanceTimer = null;
let upNextCache = [];
const clientId = Math.random().toString(36).slice(2);
// T41: whether the primary pointer actually supports hover (mouse/trackpad)
// vs not (touch) — decides whether wardrobe cards reveal "发送" on :hover
// (desktop) or need an explicit first tap (mobile). Read once; doesn't need
// to react to a mid-session input-mode change.
const supportsHover = window.matchMedia("(hover: hover)").matches;

const player = document.getElementById("player");
const leftPanel = document.getElementById("leftPanel");
const pickPanel = document.getElementById("pickPanel");
const roomTitle = document.getElementById("roomTitle");
const nowPlayingBox = document.getElementById("nowPlayingBox");
const activePill = document.getElementById("activePill");
const activeLabel = document.getElementById("activeLabel");
const activeNick = document.getElementById("activeNick");
const queueStrip = document.getElementById("queueStrip");
const likeBtn = document.getElementById("likeBtn");
const likeCount = document.getElementById("likeCount");
const watchingCount = document.getElementById("watchingCount");
const muteBtn = document.getElementById("muteBtn");
const splash = document.getElementById("splash");
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");
// T46
const chatList = document.getElementById("chatList");
const chatInput = document.getElementById("chatInput");
const chatSendBtn = document.getElementById("chatSendBtn");
const chatHint = document.getElementById("chatHint");
const chatIdentityRow = document.getElementById("chatIdentityRow");
const changeNameBtn = document.getElementById("changeNameBtn");
const currentNickname = document.getElementById("currentNickname");
let chatPollTimer = null;

function escapeHtml(s) {
  const div = document.createElement("div");
  div.textContent = s || "";
  return div.innerHTML;
}
// T40: same per-nickname pastel-hash as live.html's chat nicknames — reused
// here for the queue-strip avatar badges (stable color per person, no
// server-assigned avatar system needed).
function pastel(name) {
  let h = 0;
  for (const c of name || "") h = (h * 31 + c.charCodeAt(0)) % 360;
  return `hsl(${h},85%,85%)`;
}
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);
    updateNicknameLabel();
    return { uid, nickname };
  });
}

// T46: same identity-label pattern as live.html — the nickname row above
// the chat input only shows once a cookie actually exists.
function updateNicknameLabel() {
  const existing = getIdentity();
  chatIdentityRow.hidden = !existing;
  if (existing) currentNickname.textContent = existing.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();
});
// 第一次点聊天输入框才弹昵称——跟点赞的既有触发时机一致,不强制进房就填。
chatInput.addEventListener("focus", () => ensureIdentity());
updateNicknameLabel();

// ---- 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 myWorksLink = document.getElementById("myWorksLink");
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;
  myWorksLink.hidden = !user;
  // T42: if the DIY modal's upload form is open, re-render it — price/
  // balance-gated content (登录态、积分余额) depends on login state, same
  // reasoning as the old leftTab-driven re-render this replaces.
  if (diyMode) renderDiyForm(diyMode);
}

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 = "";
  // T42: submitGarmentUpload/submitCharacterUpload can call this while the
  // DIY modal is still open (未登录时先引导登录) — both are .nickname-modal
  // with the same z-index, and diyModal comes later in the DOM, so without
  // this it silently sits on top and hides the login form the user actually
  // needs to see.
  diyModal.hidden = true;
  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(() => {});
});

// Default to sound on (同 live.html). Chrome/Safari 在没有用户手势前不允许
// 有声自动播放,unmuted play() 被拒绝就退回静音自动播放,再靠下面的点击进入
// 蒙版拿到那次手势,切回有声。
function tryPlay() {
  player.play().catch((err) => {
    // Only fall back to muted autoplay for an actual autoplay-policy
    // rejection. tryPlay() re-runs on every clip switch (every ~10s), and a
    // switch mid-load commonly throws AbortError ("interrupted by a new
    // load request") — treating that the same as a policy block used to
    // silently flip sound back off even after the viewer had explicitly
    // unmuted via the splash click or 🔈 button.
    if (err && err.name !== "NotAllowedError") return;
    player.muted = true;
    muteBtn.textContent = "🔇 静音";
    player.play().catch(() => {});
  });
}

splash.addEventListener("click", () => {
  splash.remove();
  const desktop = matchMedia("(min-width: 769px)").matches;
  player.muted = !desktop; // 手机进入后仍保持静音,同 live.html 的理由
  player.play().catch((err) => {
    // Same guard as tryPlay(): only a genuine autoplay-policy rejection
    // should force muted — this click IS the user gesture, so a rejection
    // here is almost always something else (e.g. the clip's src still
    // mid-switch from a just-arrived pollState) and shouldn't silently
    // override the sound-on choice this click just made.
    if (!err || err.name === "NotAllowedError") player.muted = true;
    muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
  });
  muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
});

// ---- 左侧栏:待播放 / 传衣服 / 传人 三个 tab ----
function garmentName(id) {
  const g = wardrobe.find((x) => x.id === id);
  return g ? g.name : id;
}
function garmentImage(id) {
  const g = wardrobe.find((x) => x.id === id);
  return g ? g.thumbnailUrl || g.imageUrl : null;
}

// "待播放" tab just renders lastState.upNext — same data pollState() already
// has, no separate fetch. Shows the garment's own thumbnail, not just its
// name, same wardrobe-card look as the picker on the right.
function renderQueueTab() {
  const upcoming = (lastState && lastState.upNext) || [];
  leftPanel.innerHTML = upcoming.length
    ? `<div class="wardrobe-grid">${upcoming
        .map((c) => {
          const img = garmentImage(c.garmentId);
          return `
      <div class="wardrobe-card">
        ${img ? `<img src="${escapeHtml(img)}" />` : ""}
        <div class="name">${escapeHtml(c.prompt || garmentName(c.garmentId))}</div>
        ${c.requestedBy ? `<div class="meta">by ${escapeHtml(c.requestedBy)}</div>` : ""}
      </div>`;
        })
        .join("")}</div>`
    : `<div class="empty-hint">暂无排队,去右边选一件衣服吧</div>`;
}

// ---- T42: DIY 弹窗——换装横条末尾的 DIY 卡片点开后先二选一,再展开对应
// 的上传表单;下面两个 render*UploadPanel 原来是写进左栏 leftPanel 的,
// 现在改写进弹窗的 #diyForm,付费/登录/邮箱验证逻辑完全不动。 ----
const diyModal = document.getElementById("diyModal");
const diyChoice = document.getElementById("diyChoice");
const diyForm = document.getElementById("diyForm");
const diyCloseBtn = document.getElementById("diyCloseBtn");

function openDiyModal() {
  diyMode = null;
  diyChoice.hidden = false;
  diyForm.innerHTML = "";
  diyModal.hidden = false;
}
function renderDiyForm(mode) {
  diyMode = mode;
  diyChoice.hidden = true;
  if (mode === "garment") renderGarmentUploadPanel();
  else renderCharacterUploadPanel();
}
diyModal.querySelectorAll("[data-diy]").forEach((b) => b.addEventListener("click", () => renderDiyForm(b.dataset.diy)));
diyCloseBtn.addEventListener("click", () => {
  diyModal.hidden = true;
  diyMode = null;
});

// ---- T44: 上传进度条——伪进度+真进度混合(参考分析 §3),共用于模式二/
// 三两个上传表单。`fetch` 的 FormData 上传拿不到进度事件,改用 XHR。 ----
function uploadWithProgress(url, formData, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) onProgress(e.loaded / e.total);
    };
    xhr.onload = () => {
      let data = {};
      try {
        data = JSON.parse(xhr.responseText);
      } catch {
        // non-JSON body — data stays {}, caller falls back to a generic error message
      }
      resolve({ status: xhr.status, data });
    };
    xhr.onerror = () => reject(new Error("network error"));
    xhr.send(formData);
  });
}
// 按文件大小估算一个基准时长,缓动推到 88%;真实进度一旦追上就用真值
// (`report` 内部用 max 卡住不倒退)。`finish()` 保证至少可见 500ms 再跳
// 100%——小图上传经常几十毫秒就完事,不留这个下限的话进度条等于白做,
// 一闪就没了,看不出动画。
function createUploadProgress(bar, fileSize) {
  bar.hidden = false;
  bar.style.setProperty("--pct", "0%");
  const startedAt = Date.now();
  const MIN_VISIBLE_MS = 500;
  let pct = 0;
  const setPct = (p) => {
    pct = Math.max(pct, Math.min(p, 100));
    bar.style.setProperty("--pct", `${pct}%`);
  };
  const durationMs = Math.min(25000, Math.max(3000, (fileSize / 262144) * 1000));
  const timer = setInterval(() => {
    setPct(Math.min(88, ((Date.now() - startedAt) / durationMs) * 88));
  }, 120);
  return {
    report(realPct) {
      setPct(realPct);
    },
    async finish() {
      clearInterval(timer);
      const elapsed = Date.now() - startedAt;
      if (elapsed < MIN_VISIBLE_MS) await new Promise((r) => setTimeout(r, MIN_VISIBLE_MS - elapsed));
      setPct(100);
      await new Promise((r) => setTimeout(r, 400));
      bar.hidden = true;
    },
    stop() {
      clearInterval(timer);
      bar.hidden = true;
    },
  };
}

// ---- T28: 模式二"传衣服"(付费,需登录+邮箱验证) ----
function renderGarmentUploadPanel() {
  const spendGarment = pricing.find((p) => p.key === "spend_garment");
  const priceLine = spendGarment ? `上传一张衣服照片,AI 换装生成跳舞视频,扣 ${spendGarment.credits} 积分` : "加载价格中…";
  diyForm.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-progress" id="garmentUploadProgress" hidden><div class="upload-progress-bar"></div></div>
      <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 progressBar = document.getElementById("garmentUploadProgress");
  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 = "上传中…";
  const progress = createUploadProgress(progressBar, file.size);
  try {
    const fd = new FormData();
    fd.append("file", file);
    fd.append("characterId", characterId);
    const { status, data } = await uploadWithProgress("/api/dance/upload-garment", fd, (frac) => progress.report(frac * 100));
    if (status < 200 || status >= 300) {
      progress.stop();
      statusBox.hidden = true;
      errorBox.hidden = false;
      if (status === 402) {
        errorBox.textContent = "积分不足,请先充值";
      } else {
        errorBox.textContent = data.error || "上传失败";
      }
      return;
    }
    await progress.finish();
    const message = data.status === "ready" ? "生成完成,已加入播放队列!" : "生成中,完成后会自动加入播放队列";
    // refreshAuthState() re-renders this whole panel (creditBalance changed
    // -> renderAuthButton -> renderDiyForm) — 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 {
    progress.stop();
    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("");
  diyForm.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-progress" id="characterUploadProgress" hidden><div class="upload-progress-bar"></div></div>
      <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 progressBar = document.getElementById("characterUploadProgress");
  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 = "上传中…";
  const progress = createUploadProgress(progressBar, file.size);
  try {
    const fd = new FormData();
    fd.append("file", file);
    if (garmentSelect.value) fd.append("garmentId", garmentSelect.value);
    fd.append("segments", segmentsInput.value || "3");
    const { status, data } = await uploadWithProgress("/api/dance/upload-character", fd, (frac) => progress.report(frac * 100));
    if (status < 200 || status >= 300) {
      progress.stop();
      statusBox.hidden = true;
      errorBox.hidden = false;
      errorBox.textContent = status === 402 ? "积分不足,请先充值" : data.error || "上传失败";
      return;
    }
    // This purchase just created a brand-new character, i.e. a brand-new
    // room (getDanceRoomCharacterIds: "有视频就自动开间") — send the buyer
    // straight there instead of leaving them in this room where their new
    // character's clip will never actually appear. Navigating away right
    // after a 200 makes finishing the progress-bar animation pointless —
    // this page is gone before anyone would see it.
    location.href = `dance.html?characterId=${data.characterId}`;
    return;
  } catch {
    progress.stop();
    statusBox.hidden = true;
    errorBox.hidden = false;
    errorBox.textContent = "网络错误,请重试";
  } finally {
    btn.disabled = false;
  }
}

// Wardrobe is scoped to this room and only ever lists garments THIS
// character already has a generated video for (server-side shuffled) — a
// pick here is always a cache hit, never a fresh generation.
async function loadWardrobe() {
  const res = await fetch(`/api/dance/wardrobe?characterId=${characterId}`);
  wardrobe = await res.json();
  renderPickPanel();
}

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" },
      // uid 只在已经有 cookie 时才带上——T48 的"同 uid 限流"只对已识别的
      // uid 生效,没有 cookie 的匿名提交继续不受限(同"免费模式一不强制
      // 登录"的既有承诺,见上面那行注释)。
      body: JSON.stringify({ characterId, garmentId, uid: identity ? identity.uid : undefined, nickname: identity ? identity.nickname : undefined }),
    });
    const data = await res.json();
    if (!res.ok) {
      alert(data.error || "提交失败");
      return;
    }
    pollState();
  } finally {
    card.classList.remove("disabled");
  }
}

// ---- 右侧栏:选衣服(乱序待选列表)+ 生成中/失败(模式二/三上传偶尔会有) ----
function renderPickPanel() {
  const queue = (lastState && lastState.queue) || [];
  const generating = queue.filter((q) => q.status === "generating");
  const failed = queue.filter((q) => q.status === "failed");
  // T48: "generating" is the only status worth checking here — "ready"
  // entries get swept into the schedule within one tick and are never
  // long-lived enough to matter for this UI (and state.queue doesn't even
  // include them, see /api/dance/live/state's own filter).
  const myPending = queue.some((q) => q.mine && q.status === "generating");

  // T41: 缩略图默认只显示图+名字,桌面 hover / 移动端点一下先露出"发送"
  // 按钮再确认,避免像以前那样点一下卡片就直接提交(容易误触)。
  // T42: 横向一条(.wardrobe-strip-row),末尾加一张 DIY 卡片,点开二选一
  // 弹窗(见 openDiyModal)——原来"传衣服/传人"两个左栏 tab 的入口并到
  // 这里,付费上传不受 myPending 限制(T48 只挡免费 pick)。
  const cardsHtml = wardrobe
    .map(
      (g) => `
      <div class="wardrobe-card${myPending ? " disabled" : ""}" data-garment="${g.id}">
        <div class="wardrobe-thumb">
          <img src="${escapeHtml(g.thumbnailUrl || g.imageUrl)}" />
          <div class="wardrobe-send-overlay">
            <button class="wardrobe-send-btn" type="button">发送</button>
          </div>
        </div>
        <div class="name">${escapeHtml(g.name)}</div>
      </div>`
    )
    .join("");
  const diyCardHtml = `
      <div class="wardrobe-card wardrobe-diy" id="diyCard">
        <div class="wardrobe-thumb wardrobe-diy-thumb">
          <span class="wardrobe-diy-icon">⬆️</span>
        </div>
        <div class="name">DIY 上传</div>
      </div>`;
  const pickHtml = wardrobe.length
    ? `<div class="wardrobe-strip-row">${cardsHtml}${diyCardHtml}</div>`
    : `<div class="wardrobe-strip-row">${diyCardHtml}</div>`;
  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("");

  pickPanel.innerHTML =
    (myPending ? `<div class="pending-hint">你已经有一件衣服在排队啦,播放后可以再选新的</div>` : "") +
    pickHtml +
    (generatingHtml ? `<div class="section-head">生成中(可点赞)</div>${generatingHtml}` : "") +
    (failedHtml ? `<div class="section-head">生成失败</div>${failedHtml}` : "");

  // T41: 桌面(真的有 hover)靠 CSS :hover 露出发送按钮,点缩略图本身不做
  // 任何事——只有点"发送"按钮才提交。移动端没有 hover,第一下点缩略图先
  // 露出按钮(同时收起其他已经露出的卡片),第二下点"发送"才真正提交。
  // ponytail: `.revealed` 是纯前端瞬时状态,下一次 pollState()(4s 一次)
  // 整个 pickPanel 会被重新渲染冲掉——移动端如果露出按钮后超过几秒没点,
  // 会自动收回去,需要重新点一下;这是"整块 innerHTML 重渲染"这个既有
  // 轮询模式的通用代价,不是这个任务单独引入的问题,真要根治得给整个
  // 轮询链路做增量 DOM diff,超出本任务范围。
  pickPanel.querySelectorAll(".wardrobe-card[data-garment]").forEach((card) => {
    card.querySelector(".wardrobe-send-btn").addEventListener("click", (e) => {
      e.stopPropagation();
      pickGarment(card.dataset.garment, card);
    });
    if (supportsHover) return;
    card.addEventListener("click", () => {
      if (card.classList.contains("revealed")) return;
      pickPanel.querySelectorAll(".wardrobe-card.revealed").forEach((c) => c.classList.remove("revealed"));
      card.classList.add("revealed");
    });
  });
  pickPanel.querySelectorAll("[data-vote]").forEach((btn) => btn.addEventListener("click", () => voteQueueItem(btn.dataset.vote, btn)));
  // T42: DIY 卡片直接开二选一弹窗,不走 hover/展开 + 发送那一套(点开就是
  // 弹窗,没有"先预览再确认"的必要),也不受 myPending 限制(付费上传)。
  const diyCard = document.getElementById("diyCard");
  if (diyCard) diyCard.addEventListener("click", openDiyModal);
}

// T40: 视频上方的排队头像条——只展示"生成中"(真正在等待播放的),已经
// 是 state.queue 里按票数排好序的同一份数据,不用再排一次序;每人一个
// 昵称首字哈希色块头像 + 右下角迷你服装缩略图角标。
function renderQueueStrip() {
  const waiting = ((lastState && lastState.queue) || []).filter((q) => q.status === "generating");
  queueStrip.hidden = waiting.length === 0;
  if (!waiting.length) return;
  queueStrip.innerHTML = waiting
    .map((q) => {
      const name = q.nickname || "";
      const initial = escapeHtml(name.trim().slice(0, 1) || "?");
      const img = garmentImage(q.garmentId);
      return `
    <div class="queue-avatar" title="${escapeHtml(name || "匿名")} · ${escapeHtml(garmentName(q.garmentId))}">
      <div class="queue-avatar-badge" style="background:${pastel(name)}">${initial}</div>
      ${img ? `<img class="queue-avatar-thumb" src="${escapeHtml(img)}" />` : ""}
    </div>`;
    })
    .join("");
}

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 是权威时钟,轮询只是纠偏 ----
// T40: `nick` doubles as the empty-state message when there's nothing
// playing yet (pollState's "还没有可播放的内容…" call passes clip=null) —
// that call still shows the pill, just without the "🔥 正在换装" label
// (activeLabel only shows when there's an actual clip), same dual-purpose
// trick the old now-playing-box's np-nick span used.
function setNowPlaying(nick, clip) {
  activePill.hidden = !nick;
  activeLabel.hidden = !clip;
  activeNick.textContent = nick || "";
  nowPlayingBox.hidden = !clip;
  likeBtn.hidden = !clip;
  if (clip) {
    likeCount.textContent = clip.likes || 0;
    likeBtn.onclick = async () => {
      // 高清重绘: likes live on the content's root clip (clip.groupId), not
      // whichever resolution variant happens to be playing — otherwise a
      // clip's like count would appear to reset to 0 the moment an HD
      // version starts getting served (see joinClip in server.js).
      const res = await fetch(`/api/like/${clip.groupId || clip.id}`, { method: "POST" });
      if (res.ok) likeCount.textContent = (await res.json()).likes;
    };
  }
}

// A clip whose /lib/video request errors out (e.g. a transient 401/502 from
// the upstream H3 console) would otherwise just sit there frozen until the
// server-clock advanceTimer eventually fires — skip ahead immediately
// instead of leaving the room looking dead.
player.addEventListener("error", () => {
  if (player.currentSrc && currentClipId && player.currentSrc.endsWith(`/lib/video/${currentClipId}`) && upNextCache.length) {
    switchToClip(upNextCache[0], 0, upNextCache[0].requestedBy);
  }
});

// ---- curtain transition: close over the outgoing clip's last frame, swap
// src while hidden, open once the incoming clip actually has a frame ready
// (not just once src is set — that would flash the old frame behind an
// already-open curtain on browsers that keep painting it until new data
// arrives). ----
const curtain = document.getElementById("curtain");
function closeCurtain() {
  return new Promise((resolve) => {
    curtain.classList.add("closed");
    let done = false;
    const finish = () => {
      if (done) return;
      done = true;
      curtain.removeEventListener("transitionend", finish);
      resolve();
    };
    curtain.addEventListener("transitionend", finish, { once: true });
    setTimeout(finish, 700); // ponytail: fallback if transitionend never fires (e.g. backgrounded tab)
  });
}
function openCurtain() {
  curtain.classList.remove("closed");
}
function waitForFrame(video) {
  return new Promise((resolve) => {
    let done = false;
    const finish = () => {
      if (done) return;
      done = true;
      video.removeEventListener("playing", finish);
      video.removeEventListener("loadeddata", finish);
      resolve();
    };
    video.addEventListener("playing", finish, { once: true });
    video.addEventListener("loadeddata", finish, { once: true });
    // ponytail: caps how long the curtain stays shut waiting for a slow/failed
    // load — upgrade path if this fires often: show a spinner behind the curtain.
    setTimeout(finish, 800);
  });
}

let curtainGen = 0; // guards against a stale switch's waitForFrame() reopening a curtain a newer switch just closed
function switchToClip(clip, offsetSec, requestedBy) {
  const isFirstClip = currentClipId === null;
  currentClipId = clip.id;
  const gen = ++curtainGen;
  const applyClip = () => {
    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, clip);
    waitForFrame(player).then(() => {
      if (gen === curtainGen) openCurtain();
    });
  };
  if (isFirstClip) applyClip();
  else closeCurtain().then(applyClip);
}

async function pollState() {
  try {
    const identity = getIdentity();
    const res = await fetch(`/api/dance/live/state?characterId=${characterId}&cid=${clientId}${identity ? `&uid=${encodeURIComponent(identity.uid)}` : ""}`);
    if (res.status === 400) {
      // this character has no room (never had a video, or was removed) —
      // nothing to watch here.
      location.href = "dance-rooms.html";
      return;
    }
    const state = await res.json();
    lastState = state;
    watchingCount.hidden = false;
    watchingCount.textContent = `👀 ${state.watching}`;
    renderPickPanel();
    renderQueueStrip();
    renderQueueTab();
    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) {
      setNowPlaying("还没有可播放的内容,去下面选一件衣服开播吧", null); // T42: 选衣服搬到底部横条了,原来写"右边"过时了
    }
  } catch {
    // transient — next poll retries
  }
}

// ---- T46: dance room 聊天,跟 live.html 的 pollChat/sendChat 同一套轮询
// 节奏(3s),走独立的 /api/dance/chat(按 characterId 隔离,不触发任何
// 生成任务,见 server.js pushDanceChatMessage 的注释)。 ----
function renderDanceChat(messages) {
  const atBottom = chatList.scrollHeight - chatList.scrollTop - chatList.clientHeight < 40;
  chatList.innerHTML = messages
    .map((m) => `<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></div>`)
    .join("");
  if (atBottom) chatList.scrollTop = chatList.scrollHeight;
}

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

async function sendDanceChat() {
  const text = chatInput.value.trim();
  if (!text) return;
  const identity = await ensureIdentity();
  chatSendBtn.disabled = true;
  try {
    const res = await fetch("/api/dance/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ characterId, 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}` : "";
    pollDanceChat();
  } finally {
    chatSendBtn.disabled = false;
  }
}
chatSendBtn.addEventListener("click", sendDanceChat);
chatInput.addEventListener("keydown", (e) => {
  if (e.key === "Enter") sendDanceChat();
});

async function loadRoomInfo() {
  try {
    const rooms = await fetch("/api/dance/rooms").then((r) => r.json());
    const room = rooms.find((r) => r.id === characterId);
    if (room) {
      roomTitle.textContent = room.name;
      document.title = `${room.name} · 换装跳舞直播间`;
    }
  } catch {
    // cosmetic only — leave the generic title if this fails
  }
}

// T42: dance.html 不再有独立的"待播放/选衣服"移动端 tab 切换了——选衣服
// 现在是贴视频底部的横条(跟桌面端同一份 DOM/CSS),"待播放"列表在
// left-col 里常驻,两者在窄屏下都直接堆叠展示(见 live.css 的
// `@media (max-width:768px)` 规则,`.left-col` 本来就会掉到 player-col
// 下面)。移动端具体怎么收纳这条横条留给 T43 细化。
loadRoomInfo();
loadWardrobe();
pollState();
statePollTimer = setInterval(pollState, 4000);
pollDanceChat();
chatPollTimer = setInterval(pollDanceChat, 3000);
</script>
</body>
</html>