app.tsx 56.1 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 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';

import { parsePrelearningAllowedOrigins } from '@single-pages/config';
import type {
  PrelearningActionPayload,
  PrelearningActionResponse,
  PrelearningActionState,
  PrelearningActionType,
  PrelearningBuriedPointPayload,
  PrelearningCompleteActivityPayload,
  PrelearningInitPayload,
  PrelearningInitResponse,
} from '@single-pages/contracts';

import {
  findMissingPrelearningFields,
  fetchPrelearningAction,
  fetchPrelearningBuriedPoint,
  fetchPrelearningSession,
  PrelearningRequestError,
} from './api';
import {
  createMockPrelearningActionResponse,
  createMockPrelearningResponse,
} from './mock';

const REQUIRED_FIELDS: readonly (keyof PrelearningInitPayload)[] = [
  'entrySource',
  'activityId',
  'activityProductId',
  'staffUuid',
  'merchantId',
];

const DEFAULT_DEBUG_PAYLOAD: PrelearningInitPayload = {
  entrySource: 'home_popup',
  activityId: '100001',
  activityProductId: '200001',
  staffName: '调试员工',
  staffUuid: 'debug-staff-001',
  merchantId: 'debug-merchant-001',
  caseId: 'debug-case-001',
};

const STAGE_AVATAR_URL = new URL('./agent-avatar.png', import.meta.url).href;

type SessionMode = 'idle' | 'loading' | 'ready' | 'error';

interface SessionErrorState {
  title: string;
  message: string;
  details: string[];
}

interface SessionState {
  mode: SessionMode;
  source: 'bridge' | 'query' | 'global' | 'mock' | null;
  payload: PrelearningInitPayload | null;
  data: PrelearningInitResponse | null;
  error: SessionErrorState | null;
}

interface FeedbackState {
  tone: 'info' | 'success' | 'error';
  message: string;
  actionLabel?: string;
}

interface ReadGateState {
  countdownRemaining: number;
  countdownDone: boolean;
  countdownUnit: string;
}

interface ReadGateValue extends ReadGateState {
  canShowActions: boolean;
  getElapsedSeconds: () => number;
}

interface BuriedPointContext {
  data: PrelearningInitResponse;
  payload: PrelearningInitPayload;
}

const DEFAULT_READ_GATE_SECONDS = 60;
const READ_GATE_TICK_MS = 1000;
const READ_GATE_CONFIG_URL = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=single-pages-config';
const INIT_MESSAGE_TYPE = 'PRELEARNING_INIT';
const COMPLETE_ACTIVITY_MESSAGE_TYPE = 'completeActivity';
const VITE_BASE_URL = ((import.meta as ImportMeta & { env?: { BASE_URL?: string } }).env?.BASE_URL ?? '/');

interface ReadGateConfig {
  seconds: number;
  unit: string;
}

interface PrelearningAppBridgeMessage {
  source: 'prelearn-h5';
  type: typeof COMPLETE_ACTIVITY_MESSAGE_TYPE;
  payload: PrelearningCompleteActivityPayload;
}

function buildReadGateState(seconds: number, unit = '秒'): ReadGateState {
  const normalizedSeconds = Math.max(0, Math.floor(seconds));

  return {
    countdownRemaining: normalizedSeconds,
    countdownDone: normalizedSeconds === 0,
    countdownUnit: unit,
  };
}

const INITIAL_READ_GATE_STATE: ReadGateState = buildReadGateState(DEFAULT_READ_GATE_SECONDS);

function isTruthy(value: string | null): boolean {
  if (!value) {
    return false;
  }

  return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}

function getReadGateConfigCandidate(value: unknown): Record<string, unknown> | null {
  if (!isRecord(value)) {
    return null;
  }

  if (isRecord(value.data)) {
    return value.data as Record<string, unknown>;
  }

  if (isRecord(value.result)) {
    return value.result as Record<string, unknown>;
  }

  if (isRecord(value.config)) {
    return value.config as Record<string, unknown>;
  }

  return value;
}

function parseReadGateConfig(value: unknown): ReadGateConfig | null {
  const candidate = getReadGateConfigCandidate(value);
  if (!candidate) {
    return null;
  }

  const rawTimeCount = candidate.timeCount;
  const seconds = typeof rawTimeCount === 'number'
    ? rawTimeCount
    : typeof rawTimeCount === 'string'
      ? Number(rawTimeCount)
      : Number.NaN;

  if (!Number.isFinite(seconds) || seconds <= 0) {
    return null;
  }

  const unit = typeof candidate.unit === 'string' && candidate.unit.trim().length > 0
    ? candidate.unit.trim()
    : '秒';

  return {
    seconds: Math.floor(seconds),
    unit,
  };
}

async function fetchReadGateConfig(): Promise<ReadGateConfig> {
  try {
    const response = await fetch(READ_GATE_CONFIG_URL);
    const json = await response.json().catch(() => null);

    if (!response.ok) {
      return { seconds: DEFAULT_READ_GATE_SECONDS, unit: '秒' };
    }

    return parseReadGateConfig(json) ?? { seconds: DEFAULT_READ_GATE_SECONDS, unit: '秒' };
  } catch {
    return { seconds: DEFAULT_READ_GATE_SECONDS, unit: '秒' };
  }
}

function extractQueryPayload(searchParams: URLSearchParams): Partial<PrelearningInitPayload> | null {
  const payload: Partial<PrelearningInitPayload> = {};

  const entrySource = searchParams.get('entrySource');
  if (entrySource !== null) {
    payload.entrySource = entrySource as PrelearningInitPayload['entrySource'];
  }

  const activityId = searchParams.get('activityId');
  if (activityId !== null) {
    payload.activityId = activityId;
  }

  const activityProductId = searchParams.get('activityProductId');
  if (activityProductId !== null) {
    payload.activityProductId = activityProductId;
  }

  const staffUuid = searchParams.get('staffUuid');
  if (staffUuid !== null) {
    payload.staffUuid = staffUuid;
  }

  const staffName = searchParams.get('staffName');
  if (staffName !== null) {
    payload.staffName = staffName;
  }

  const merchantId = searchParams.get('merchantId');
  if (merchantId !== null) {
    payload.merchantId = merchantId;
  }

  const caseId = searchParams.get('caseId');
  if (caseId !== null) {
    payload.caseId = caseId;
  }

  return Object.keys(payload).length > 0 ? payload : null;
}

function buildMockPayload(searchParams: URLSearchParams): PrelearningInitPayload {
  const payload = extractQueryPayload(searchParams);
  return {
    ...DEFAULT_DEBUG_PAYLOAD,
    ...payload,
  };
}

function normalizeBridgePayload(value: unknown): Partial<PrelearningInitPayload> | null {
  if (!isRecord(value)) {
    return null;
  }

  if (value.type !== INIT_MESSAGE_TYPE) {
    return null;
  }

  return isRecord(value.payload) ? (value.payload as Partial<PrelearningInitPayload>) : null;
}

function getAllowedOrigins(): string[] | '*' {
  return parsePrelearningAllowedOrigins(
    (import.meta as ImportMeta & { env: { VITE_PRELEARNING_ALLOWED_ORIGINS?: string } }).env
      .VITE_PRELEARNING_ALLOWED_ORIGINS,
  );
}

function isAllowedOrigin(origin: string, allowedOrigins: string[] | '*'): boolean {
  if (allowedOrigins === '*') {
    return true;
  }

  return allowedOrigins.includes(origin);
}

function getQueryBootContext(): { payload: Partial<PrelearningInitPayload>; useMock: boolean; source: 'query' | 'mock' } | null {
  const searchParams = new URLSearchParams(window.location.search);
  const useMock = isTruthy(searchParams.get('mock')) || isTruthy(searchParams.get('debugMock'));
  const payload = extractQueryPayload(searchParams);

  if (useMock) {
    return {
      payload: buildMockPayload(searchParams),
      useMock: true,
      source: 'mock',
    };
  }

  if (payload) {
    return {
      payload,
      useMock: false,
      source: 'query',
    };
  }

  return null;
}

function formatPrice(value: string): string {
  return value ? `¥${value}` : '-';
}

function buildPrelearningPageTitle(packageName: string): string {
  return `${packageName}实战案例解析`;
}

function toArray(value: readonly string[] | string[] | undefined): string[] {
  return Array.isArray(value) ? [...value] : [];
}

function parseElapsedSeconds(startedAt: number | null): number {
  if (!startedAt) {
    return 0;
  }

  return Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
}

function normalizeDisplayedActionState(
  triggeredActionType: PrelearningActionType,
  responseActionState: PrelearningActionState,
): PrelearningActionState {
  if (triggeredActionType !== 'view_other') {
    return responseActionState;
  }

  return {
    ...responseActionState,
    actionType: 'view_other',
    buttonLabel: '查看其他案例',
  };
}

function formatChinaDateTime(date = new Date()): string {
  const chinaDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  const pad = (value: number) => String(value).padStart(2, '0');

  return [
    `${chinaDate.getUTCFullYear()}-${pad(chinaDate.getUTCMonth() + 1)}-${pad(chinaDate.getUTCDate())}`,
    `${pad(chinaDate.getUTCHours())}:${pad(chinaDate.getUTCMinutes())}:${pad(chinaDate.getUTCSeconds())}`,
  ].join(' ');
}

function buildBuriedPointPayload(
  data: PrelearningInitResponse,
  basePayload: PrelearningInitPayload,
  eventType: 'page_view' | 'intercept_back' | 'task_completed' | 'reroll_case',
  durationSeconds: number,
): PrelearningBuriedPointPayload {
  return {
    entrySource: basePayload.entrySource,
    eventType,
    staffName: basePayload.staffName ?? '',
    staffUuid: basePayload.staffUuid,
    merchantId: basePayload.merchantId,
    activityId: String(data.activityProduct.activityId),
    activityProductId: String(data.activityProduct.activityProductId),
    caseId: data.script.caseId,
    sessionId: data.sessionId,
    durationSeconds,
    eventTime: formatChinaDateTime(),
  };
}

async function safeSendBuriedPoint(
  payload: PrelearningBuriedPointPayload,
): Promise<void> {
  try {
    window.__PRELEARNING_DEBUG_BURIED_POINT__?.(payload);
    await fetchPrelearningBuriedPoint(payload);
  } catch {
    // 埋点失败不阻塞主流程,后端会负责记录失败或可重试线索。
  }
}

function postMessageToApp(message: PrelearningAppBridgeMessage): boolean {
  if (window.parent && window.parent !== window) {
    window.parent.postMessage(message, '*');
    return true;
  }

  if (window.uni?.webView?.postMessage) {
    window.uni.webView.postMessage({ data: message });
    return true;
  }

  if (window.uni?.postMessage) {
    window.uni.postMessage({ data: message });
    return true;
  }

  return false;
}

function hasUniPostMessageBridge(): boolean {
  return Boolean(window.uni?.webView?.postMessage || window.uni?.postMessage);
}

function loadUniWebviewSdk(): Promise<void> {
  if (hasUniPostMessageBridge()) {
    return Promise.resolve();
  }

  return new Promise<void>((resolve) => {
    const existingScript = document.querySelector<HTMLScriptElement>('script[data-uni-webview-sdk]');
    if (existingScript) {
      document.addEventListener('UniAppJSBridgeReady', () => resolve(), { once: true });
      return;
    }

    const script = document.createElement('script');
    script.src = `${VITE_BASE_URL}uni.webview.1.5.5.js`;
    script.async = true;
    script.dataset.uniWebviewSdk = 'true';
    const timer = window.setTimeout(() => resolve(), 300);
    script.onload = () => {
      window.clearTimeout(timer);
      resolve();
    };
    script.onerror = () => {
      window.clearTimeout(timer);
      resolve();
    };
    document.head.appendChild(script);
  });
}

function waitForBridgeReady(timeout = 1800): Promise<boolean> {
  return new Promise<boolean>((resolve) => {
    if (hasUniPostMessageBridge() || window.parent !== window) {
      resolve(true);
      return;
    }

    let settled = false;
    const done = (ready: boolean) => {
      if (settled) {
        return;
      }
      settled = true;
      resolve(ready);
    };

    document.addEventListener(
      'UniAppJSBridgeReady',
      () => {
        done(hasUniPostMessageBridge());
      },
      { once: true },
    );
    window.setTimeout(
      () => done(hasUniPostMessageBridge() || window.parent !== window),
      timeout,
    );
  });
}

function ReadGateFooter({
  state,
  actionState,
  submitting,
  onAction,
}: {
  state: ReadGateState;
  actionState: PrelearningActionState;
  submitting: boolean;
  onAction: (actionType: PrelearningActionType) => void;
}) {
  const canShowActions = state.countdownDone;
  const actionIcon = getReadGateActionIcon(actionState.actionType);
  const actionVisuals = getReadGateActionButtonVisuals(actionState.actionType);

  return (
    <footer
      data-testid="prelearning-read-gate"
      className="mt-5 rounded-[16px] bg-[#F5F7FA]"
    >
      <div className="flex w-full flex-col gap-4">
        {!canShowActions ? (
          <div className="flex h-12 items-center justify-center text-[15px] font-medium leading-6 text-[#717784]">
            距离完成阅读剩余:
            <span className="ml-2 tabular-nums">{state.countdownRemaining} {state.countdownUnit}</span>
          </div>
        ) : (
          <div className="space-y-2">
            <button
              type="button"
              onClick={() => onAction(actionState.actionType)}
              disabled={actionState.disabled || submitting}
              style={actionVisuals.style}
              className={[
                'flex h-12 w-full items-center justify-center gap-1.5 rounded-[16px] px-4 text-[13px] font-semibold transition disabled:cursor-not-allowed disabled:opacity-60',
                actionVisuals.className,
              ].join(' ')}
            >
              {submitting ? null : actionIcon}
              {submitting ? '提交中…' : actionState.buttonLabel}
            </button>
            {actionState.disabledReason ? (
              <p className="px-1 text-[12px] leading-5 text-[#717784]">{actionState.disabledReason}</p>
            ) : null}
          </div>
        )}
      </div>
    </footer>
  );
}

function getReadGateActionButtonVisuals(actionType: PrelearningActionType): {
  className: string;
  style: CSSProperties;
} {
  if (actionType === 'complete') {
    return {
      className: 'bg-[#35C376] text-white hover:bg-[#2EAF68]',
      style: {
        backgroundColor: '#35C376',
        color: '#fff',
      },
    };
  }

  if (actionType === 'learn_next') {
    return {
      className: 'bg-[linear-gradient(180deg,#61C0FF_0%,#2C66F7_100%)] text-white hover:opacity-95',
      style: {
        backgroundImage: 'linear-gradient(180deg, #61C0FF 0%, #2C66F7 100%)',
        color: '#fff',
      },
    };
  }

  return {
    className: 'border border-[#dbe6ff] bg-[#f4f8ff] text-[#2f5fc7] hover:bg-[#eaf1ff]',
    style: {
      backgroundColor: '#f4f8ff',
      color: '#2f5fc7',
    },
  };
}

function usePrelearningReadGate(contentKey: string | null) {
  const contentScrollRef = useRef<HTMLDivElement | null>(null);
  const countdownTimerRef = useRef<number | null>(null);
  const startedAtRef = useRef<number | null>(null);
  const [state, setState] = useState<ReadGateState>(INITIAL_READ_GATE_STATE);
  const [readGateConfig, setReadGateConfig] = useState<ReadGateConfig>({
    seconds: DEFAULT_READ_GATE_SECONDS,
    unit: '秒',
  });

  useEffect(() => {
    let cancelled = false;

    void (async () => {
      const config = await fetchReadGateConfig();

      if (!cancelled) {
        setReadGateConfig(config);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (countdownTimerRef.current !== null) {
      window.clearInterval(countdownTimerRef.current);
      countdownTimerRef.current = null;
    }

    setState(buildReadGateState(readGateConfig.seconds, readGateConfig.unit));
    startedAtRef.current = null;

    if (!contentKey) {
      return;
    }

    const startedAt = Date.now();
    startedAtRef.current = startedAt;

    const syncCountdownState = () => {
      const elapsed = Date.now() - startedAt;
      const remaining = Math.max(0, Math.ceil((readGateConfig.seconds * 1000 - elapsed) / READ_GATE_TICK_MS));

      setState((current) => ({
        ...current,
        countdownRemaining: remaining,
        countdownDone: remaining === 0,
      }));

      if (remaining === 0 && countdownTimerRef.current !== null) {
        window.clearInterval(countdownTimerRef.current);
        countdownTimerRef.current = null;
      }
    };

    syncCountdownState();
    if (contentScrollRef.current) {
      contentScrollRef.current.scrollTop = 0;
    }

    countdownTimerRef.current = window.setInterval(syncCountdownState, READ_GATE_TICK_MS);

    return () => {
      if (countdownTimerRef.current !== null) {
        window.clearInterval(countdownTimerRef.current);
        countdownTimerRef.current = null;
      }
    };
  }, [contentKey, readGateConfig]);

  const getElapsedSeconds = useCallback(() => parseElapsedSeconds(startedAtRef.current), []);

  const readGate = useMemo<ReadGateValue>(
    () => ({
      ...state,
      canShowActions: state.countdownDone,
      getElapsedSeconds,
    }),
    [getElapsedSeconds, state],
  );

  return {
    contentScrollRef,
    readGate,
    getElapsedSeconds,
  };
}

function getReadGateActionIcon(actionType: PrelearningActionType): ReactNode | null {
  if (actionType === 'learn_next' || actionType === 'complete') {
    return <ReadGateActionIcon />;
  }

  return null;
}

function PackageCardIcon({ className = '' }: { className?: string }) {
  return (
    <svg
      data-testid="product-card-icon"
      className={className}
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      viewBox="0 0 12 12"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M1.08526 4.6016C1.01391 4.30433 1.23924 4.01852 1.54496 4.01852H9.80081C10.1065 4.01852 10.3319 4.30433 10.2605 4.6016L9.06917 9.56554C9.01816 9.77812 8.82806 9.92798 8.60946 9.92798H2.73631C2.51771 9.92798 2.32762 9.77812 2.27661 9.56554L1.08526 4.6016Z"
        stroke="white"
        strokeWidth="0.945513"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M4.49112 1.65459H2.6001V4.01837H4.49112V1.65459Z"
        stroke="white"
        strokeWidth="0.945513"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M4.49146 4.01853L6.02791 1.89113L8.98264 4.01853"
        stroke="white"
        strokeWidth="0.945513"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M3.54578 5.90939H5.4368"
        stroke="white"
        strokeWidth="0.945513"
        strokeLinecap="round"
      />
    </svg>
  );
}

function CustomerAvatarIcon({ className = '' }: { className?: string }) {
  return (
    <svg className={className} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12" fill="none" aria-hidden="true">
      <path d="M6 5C6.9665 5 7.75 4.2165 7.75 3.25C7.75 2.2835 6.9665 1.5 6 1.5C5.0335 1.5 4.25 2.2835 4.25 3.25C4.25 4.2165 5.0335 5 6 5Z" fill="white" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M3 1.81372C2.54662 2.12996 2.25 2.65535 2.25 3.25005C2.25 3.88663 2.5899 4.44383 3.0981 4.75005" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M9 1.81372C9.45338 2.12996 9.75 2.65535 9.75 3.25005C9.75 3.84473 9.45338 4.37015 9 4.68638" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M3 10V10.5H9V10C9 9.06813 9 8.60217 8.84775 8.23462C8.64477 7.74457 8.25542 7.35522 7.76538 7.15225C7.39783 7 6.93187 7 6 7C5.06813 7 4.60217 7 4.23462 7.15225C3.74457 7.35522 3.35523 7.74457 3.15225 8.23462C3 8.60217 3 9.06813 3 10Z" fill="white" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M11 10.5V10.2C11 9.07992 11 8.51987 10.782 8.09204C10.5903 7.71572 10.2843 7.40977 9.90796 7.21802" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M1 10.5V10.2C1 9.07992 1 8.51987 1.21799 8.09204C1.40973 7.71572 1.7157 7.40977 2.09202 7.21802" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function AlertCircleIcon({ className = '' }: { className?: string }) {
  return (
    <svg
      className={className}
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      viewBox="0 0 12 12"
      fill="none"
      aria-hidden="true"
    >
      <g clipPath="url(#clip0_2894_950)">
        <path d="M6.00012 10.9999C8.76155 10.9999 11.0001 8.76136 11.0001 5.99994C11.0001 3.23852 8.76155 0.999939 6.00012 0.999939C3.2387 0.999939 1.00012 3.23852 1.00012 5.99994C1.00012 8.76136 3.2387 10.9999 6.00012 10.9999Z" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M6 3.99994V5.99994" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M6 8.00006H6.005" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      </g>
      <defs>
        <clipPath id="clip0_2894_950">
          <rect width="12" height="12" fill="white" />
        </clipPath>
      </defs>
    </svg>
  );
}

function StageTimeIcon({ className = '' }: { className?: string }) {
  return (
    <svg
      className={className}
      xmlns="http://www.w3.org/2000/svg"
      width="16"
      height="16"
      viewBox="0 0 16 16"
      fill="none"
      aria-hidden="true"
    >
      <path d="M13.9893 8.35334C14.0626 7.11285 13.7488 5.88023 13.0914 4.82571C12.434 3.77119 11.4655 2.94679 10.3194 2.46636C9.17343 1.98594 7.90651 1.87319 6.69367 2.14369C5.48082 2.4142 4.38188 3.0546 3.54862 3.97647C2.71535 4.89833 2.18887 6.05618 2.04188 7.2901C1.8949 8.52402 2.13466 9.77314 2.72805 10.865C3.32144 11.9568 4.23919 12.8374 5.35455 13.3852C6.46992 13.9331 7.72786 14.1211 8.95467 13.9233" stroke="#999EA8" strokeWidth="1.33333" strokeLinecap="round" strokeLinejoin="round" />
      <path d="M8 4.66666V7.99999L10 9.99999M12.6667 10.6667L11.3333 12.6667H14L12.6667 14.6667" stroke="#999EA8" strokeWidth="1.33333" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function TargetCircleIcon({ className = '' }: { className?: string }) {
  return (
    <svg
      className={className}
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      viewBox="0 0 12 12"
      fill="none"
      aria-hidden="true"
    >
      <g clipPath="url(#clip0_2894_971)">
        <path d="M6.00012 10.9999C8.76155 10.9999 11.0001 8.76136 11.0001 5.99994C11.0001 3.23852 8.76155 0.999939 6.00012 0.999939C3.2387 0.999939 1.00012 3.23852 1.00012 5.99994C1.00012 8.76136 3.2387 10.9999 6.00012 10.9999Z" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M6 9C7.65685 9 9 7.65685 9 6C9 4.34315 7.65685 3 6 3C4.34315 3 3 4.34315 3 6C3 7.65685 4.34315 9 6 9Z" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M5.99988 7.00006C6.55216 7.00006 6.99988 6.55235 6.99988 6.00006C6.99988 5.44778 6.55216 5.00006 5.99988 5.00006C5.44759 5.00006 4.99988 5.44778 4.99988 6.00006C4.99988 6.55235 5.44759 7.00006 5.99988 7.00006Z" stroke="white" strokeLinecap="round" strokeLinejoin="round" />
      </g>
      <defs>
        <clipPath id="clip0_2894_971">
          <rect width="12" height="12" fill="white" />
        </clipPath>
      </defs>
    </svg>
  );
}

function ReadGateActionIcon({ className = '' }: { className?: string }) {
  return (
    <svg
      data-testid="prelearning-action-icon"
      className={className}
      xmlns="http://www.w3.org/2000/svg"
      width="22"
      height="22"
      viewBox="0 0 22 22"
      fill="none"
      aria-hidden="true"
    >
      <path
        d="M10.4109 2.26299C10.762 2.00705 11.2386 2.00691 11.5896 2.26299L13.1433 3.39678C13.3149 3.52191 13.5218 3.58946 13.7342 3.58916L15.659 3.58526C16.0935 3.58459 16.4786 3.86508 16.6121 4.27862L17.2029 6.10869C17.2681 6.31079 17.3962 6.48706 17.5681 6.61162L19.1267 7.73955C19.4788 7.99433 19.626 8.44756 19.491 8.86065L18.8933 10.6888C18.8273 10.8907 18.8273 11.1089 18.8933 11.3108L19.491 13.139C19.6261 13.5521 19.4788 14.0053 19.1267 14.2601L17.5681 15.388C17.3961 15.5126 17.2681 15.6888 17.2029 15.8909L16.6121 17.722C16.4785 18.1353 16.0933 18.415 15.659 18.4144L13.7342 18.4105C13.5219 18.4102 13.3149 18.4777 13.1433 18.6028L11.5896 19.7366C11.2385 19.9927 10.762 19.9927 10.4109 19.7366L8.85622 18.6028C8.68465 18.4778 8.47773 18.4101 8.2654 18.4105L6.34157 18.4144C5.90703 18.4152 5.52104 18.1355 5.38747 17.722L4.79665 15.8909C4.73137 15.6887 4.60356 15.5126 4.43142 15.388L2.87282 14.2601C2.52079 14.0052 2.37348 13.552 2.50856 13.139L3.10622 11.3108C3.17226 11.1089 3.17226 10.8907 3.10622 10.6888L2.50856 8.86065C2.37358 8.44759 2.52076 7.99431 2.87282 7.73955L4.43142 6.61162C4.60352 6.48705 4.7314 6.31089 4.79665 6.10869L5.38747 4.27862C5.52096 3.86498 5.90693 3.58445 6.34157 3.58526L8.2654 3.58916C8.47779 3.58954 8.68462 3.52192 8.85622 3.39678L10.4109 2.26299ZM15.3152 8.05987C14.9573 7.70192 14.3763 7.70199 14.0183 8.05987L10.0828 11.9954L8.44021 10.3519C8.08226 9.99391 7.50132 9.99398 7.14333 10.3519C6.78562 10.7097 6.78573 11.2898 7.14333 11.6478L9.43532 13.9397C9.79326 14.2976 10.3733 14.2975 10.7312 13.9397L15.3152 9.35674C15.673 8.99879 15.673 8.41782 15.3152 8.05987Z"
        fill="currentColor"
      />
    </svg>
  );
}

const PANEL_CLASS_NAME =
  'rounded-[16px] border-2 border-white bg-[linear-gradient(178deg,rgba(255,255,255,0.40)_0.45%,#F2F7FF_97.68%)]';

function CardIcon({
  tone,
  padded = false,
  children,
}: {
  tone: 'blue' | 'green' | 'orange' | 'purple';
  padded?: boolean;
  children: ReactNode;
}) {
  const toneClasses: Record<typeof tone, string> = {
    blue: 'bg-[linear-gradient(245deg,#51A2FF_7.13%,#3F7BFF_90.2%)]',
    green: 'bg-[linear-gradient(243deg,#06D741_9.26%,#18CE27_92.59%)]',
    orange: 'bg-[linear-gradient(250deg,#FF7903_21.35%,#FF5E3E_81.86%)]',
    purple: 'bg-[linear-gradient(135deg,#1D7BFF_0%,#696BFF_100%)]',
  };

  return (
    <span
      className={`inline-flex shrink-0 items-center justify-center ${padded ? 'rounded-[3.782px] p-[3.78px]' : 'h-[18px] w-[18px] rounded-[6px]'} ${toneClasses[tone]}`}
    >
      {children}
    </span>
  );
}

function CardShell({
  title,
  badge,
  icon,
  children,
}: {
  title: string;
  badge?: ReactNode;
  icon: ReactNode;
  children: ReactNode;
  }) {
  return (
    <section className={`${PANEL_CLASS_NAME} px-4 py-3`}>
      <header className="mb-2.5 flex items-center justify-between gap-2">
        <div className="flex min-w-0 items-center gap-1.5">
          {icon}
          <h2 className="truncate text-[14px] font-semibold leading-5 text-[#14213d]">{title}</h2>
        </div>
        {badge ? <div className="shrink-0">{badge}</div> : null}
      </header>
      {children}
    </section>
  );
}

function DetailRows({ items }: { items: Array<{ label: string; value: string }> }) {
  const visibleItems = items.filter((item) => item.value.trim().length > 0);

  if (visibleItems.length === 0) {
    return null;
  }

  return (
    <dl className="flex flex-col">
      {visibleItems.map((item) => (
        <div
          key={item.label}
          onDoubleClick={(event) => event.preventDefault()}
          className="flex min-w-0 select-none items-center overflow-hidden whitespace-nowrap text-[11px] leading-[18px]"
        >
          <dt className="shrink-0 text-[#999EA8]">{item.label}:</dt>
          <dd className="min-w-0 truncate text-[#999EA8]">{item.value}</dd>
        </div>
      ))}
    </dl>
  );
}

function EmptyState({
  title,
  description,
}: {
  title: string;
  description: string;
}) {
  return (
    <div className="rounded-xl border border-dashed border-[#bfdbfe] bg-white/80 px-5 py-10 text-center">
      <p className="text-base font-semibold text-[#172554]">{title}</p>
      <p className="mt-2 text-sm leading-6 text-[#64748b]">{description}</p>
    </div>
  );
}

function LoadingBlock({ message }: { message: string }) {
  return (
    <div className="rounded-xl border border-[#bfdbfe] bg-white px-5 py-8 text-[#172554]">
      <div className="flex items-center gap-3">
        <span className="inline-flex h-10 w-10 items-center justify-center rounded-full bg-[#2563eb] text-lg text-white">
          ...
        </span>
        <div>
          <p className="text-base font-semibold">{message}</p>
          <p className="mt-1 text-sm text-[#64748b]">正在拉取后端剧本渲染模型,请稍候。</p>
        </div>
      </div>
      <div className="mt-6 grid gap-3">
        <div className="h-4 w-2/3 animate-pulse rounded-full bg-[#bfdbfe]" />
        <div className="h-4 w-full animate-pulse rounded-full bg-[#dbeafe]" />
        <div className="h-4 w-5/6 animate-pulse rounded-full bg-[#bfdbfe]" />
      </div>
    </div>
  );
}

function ErrorState({
  error,
  onRetry,
  retryLabel,
}: {
  error: SessionErrorState;
  onRetry: () => void;
  retryLabel: string;
}) {
  return (
    <div className="rounded-xl border border-[#fecdd3] bg-white px-5 py-6 text-[#881337]">
      <p className="text-base font-semibold">{error.title}</p>
      <p className="mt-2 text-sm leading-6 text-[#be123c]">{error.message}</p>
      {error.details.length > 0 ? (
        <ul className="mt-4 space-y-2 text-sm text-[#be123c]">
          {error.details.map((detail) => (
            <li key={detail} className="rounded-lg border border-[#fecdd3] bg-[#fff1f2] px-3 py-2">
              {detail}
            </li>
          ))}
        </ul>
      ) : null}
      <div className="mt-5 flex flex-wrap gap-3">
        <button
          type="button"
          onClick={onRetry}
          className="rounded-lg bg-[#2563eb] px-4 py-2 text-sm font-semibold text-white transition hover:bg-[#1d4ed8]"
        >
          {retryLabel}
        </button>
      </div>
    </div>
  );
}

function FeedbackToast({
  state,
  onAction,
}: {
  state: FeedbackState | null;
  onAction?: () => void;
}) {
  if (!state) {
    return null;
  }

  return (
    <div
      role="status"
      className="fixed left-1/2 top-1/2 z-40 max-w-[360px] -translate-x-1/2 -translate-y-1/2 rounded-[14px] bg-black/80 px-4 py-3 text-[13px] leading-6 text-white shadow-[0_10px_30px_rgba(0,0,0,0.18)]"
    >
      <div className="flex items-start gap-3">
        <p className="min-w-0 flex-1">{state.message}</p>
        {state.actionLabel && onAction ? (
          <button
            type="button"
            onClick={onAction}
            className="shrink-0 rounded-[10px] border border-current/20 px-2 py-1 text-[12px] font-medium leading-4 transition hover:bg-black/5"
          >
            {state.actionLabel}
          </button>
        ) : null}
      </div>
    </div>
  );
}

function CustomerCard({ data }: { data: PrelearningInitResponse }) {
  const profile = data.script.profile;
  const hasName = profile.name.trim().length > 0;
  const hasProfileType = profile.type.trim().length > 0;
  const detailItems = [
    { label: '品牌车型', value: profile.car },
    { label: '客户职业', value: profile.job },
    { label: '家庭结构', value: profile.family },
    { label: '用车行为', value: profile.behavior },
  ];
  const hasDetails = detailItems.some((item) => item.value.trim().length > 0);

  if (!hasName && !hasProfileType && !hasDetails) {
    return null;
  }

  return (
    <section className={`overflow-hidden ${PANEL_CLASS_NAME}`}>
      <div className="p-4">
        <div className="flex flex-col gap-0.5">
          <div className="flex items-start gap-3">
            <CardIcon tone="blue" padded>
              <CustomerAvatarIcon className="h-[12px] w-[12px]" />
            </CardIcon>
            <div className="min-w-0 flex-1">
              <div className="flex flex-wrap items-center gap-2">
                {hasName ? (
                  <h3 className="truncate text-[16px] font-semibold leading-6 text-[#1f2a44]">
                    {profile.name}
                  </h3>
                ) : null}
                {hasProfileType ? (
                  <span
                    data-testid="profile-type-pill"
                    className="rounded-full bg-[linear-gradient(90deg,#5BA2FF_0%,#56E3F0_100%)] px-2.5 py-0.5 text-[10px] font-medium text-white"
                  >
                    {profile.type}
                  </span>
                ) : null}
              </div>
            </div>
          </div>

          <DetailRows items={detailItems} />
        </div>
      </div>
    </section>
  );
}

function ProductCard({ data }: { data: PrelearningInitResponse }) {
  const product = data.activityProduct;
  const packageInfo = data.script.packageInfo;
  const isPackage = data.productType === 0;
  const displayName = packageInfo.name.replace(/^\[(?:单品|套餐)\]\s*/, '').trim();
  const originalPrice = formatPrice(packageInfo.oldPrice);
  const currentPrice = formatPrice(packageInfo.newPrice);
  const productTypeLabel = isPackage ? '【套餐】' : '【单品】';
  const includes = toArray(packageInfo.includes);

  return (
    <section data-testid="product-card" className={`${PANEL_CLASS_NAME} px-4 py-4`}>
      <div className="flex min-h-[172px] flex-col">
        <div className="flex items-start gap-0">
          <CardIcon tone="green" padded>
            <PackageCardIcon className="h-[12px] w-[12px]" />
          </CardIcon>
          <div className="min-w-0 flex-1">
            <div className="flex min-w-0 items-start gap-1.5">
              <span className="shrink-0 text-[16px] font-medium leading-6 text-[#2f343d]">{productTypeLabel}</span>
              {displayName ? (
                <h3 className="min-w-0 flex-1 truncate text-[16px] font-medium leading-6 text-[#2f343d]">
                  {displayName}
                </h3>
              ) : null}
            </div>
          </div>
        </div>

        {includes.length > 0 ? (
          <div className="flex flex-col gap-2 mt-2">
            <div className="flex flex-col">
              {includes.map((item) => (
                <div key={item} className="flex items-center gap-1.5 text-[12px] leading-5 text-[#516176]">
                  <span data-testid="package-include-bullet" className="h-1 w-1 shrink-0 rounded-full bg-[#7e8aa3]" />
                  <span className="min-w-0 flex-1">{item}</span>
                </div>
              ))}
            </div>
          </div>
        ) : null}

        {!isPackage ? (
          <div className="flex flex-1 items-center justify-center">
            <div className="flex flex-wrap items-center gap-2">
              <span className="inline-flex items-center rounded-tr-[14px] rounded-bl-[14px] rounded-tl-none rounded-br-none bg-[#F24724] px-[14px] py-2 text-[14px] font-medium leading-5 text-white">
                活动价
              </span>
              <div className="flex min-w-0 items-baseline gap-1">
                <span className="text-[16px] font-medium leading-6 text-[#F24724]">{currentPrice}</span>
              </div>
              <span className="text-[10px] font-medium leading-4 text-[#97a0af] line-through">
                原价 ({originalPrice})
              </span>
            </div>
          </div>
        ) : (
          <div className="flex flex-wrap items-center gap-2 pt-4">
            <span className="inline-flex items-center rounded-tr-[14px] rounded-bl-[14px] rounded-tl-none rounded-br-none bg-[#F24724] px-[14px] py-2 text-[14px] font-medium leading-5 text-white">
              活动价
            </span>
            <div className="flex min-w-0 items-baseline gap-1">
              <span className="text-[16px] font-medium leading-6 text-[#F24724]">{currentPrice}</span>
            </div>
            <span className="text-[10px] font-medium leading-4 text-[#97a0af] line-through">
              原价 ({originalPrice})
            </span>
          </div>
        )}
      </div>
    </section>
  );
}

function ObjectionCard({ items }: { items: string[] }) {
  if (items.length === 0) {
    return null;
  }

  return (
    <CardShell
      title="主要异议"
      icon={
        <CardIcon tone="orange">
          <AlertCircleIcon className="h-[12px] w-[12px]" />
        </CardIcon>
      }
    >
      <div className="flex flex-col gap-y-[9px]">
        {items.map((item) => (
          <span
            key={item}
            onDoubleClick={(event) => event.preventDefault()}
            className="inline-block w-fit max-w-full select-none truncate rounded-[4px] border border-[rgba(242,71,36,0.10)] bg-[rgba(242,71,36,0.05)] px-2 py-0 text-[12px] font-normal leading-[24px] text-[#F24724]"
          >
            {item}
          </span>
        ))}
      </div>
    </CardShell>
  );
}

function DemandCard({ items }: { items: string[] }) {
  const pieces = items
    .map((item) => item.trim())
    .filter(Boolean);

  if (pieces.length === 0) {
    return null;
  }

  return (
    <CardShell
      title="需求场景挖掘"
      icon={
        <CardIcon tone="purple">
          <TargetCircleIcon className="h-[12px] w-[12px]" />
        </CardIcon>
      }
    >
      <div className="flex flex-col gap-y-[9px]">
        {pieces.map((item) => (
          <p
            key={item}
            onDoubleClick={(event) => event.preventDefault()}
            className="inline-block w-fit max-w-full select-none truncate rounded-[4px] border border-[rgba(59,115,255,0.10)] bg-[rgba(44,102,247,0.05)] px-2 py-0 text-[12px] font-normal leading-[24px] text-[#3B73FF]"
          >
            {item}
          </p>
        ))}
      </div>
    </CardShell>
  );
}

type ScriptStep = PrelearningInitResponse['script']['gameSteps'][number];

function SectionLabel({
  children,
  variant = 'customer',
}: {
  children: ReactNode;
  variant?: 'customer' | 'sales';
}) {
  const className =
    variant === 'sales'
      ? 'text-[12px] font-normal leading-5 text-[#2C66F7]'
      : 'text-[12px] font-normal leading-5 text-[#292D33]';

  return <p className={className}>{children}</p>;
}

function DialogueBubble({
  align,
  tone,
  children,
}: {
  align: 'left' | 'right';
  tone: 'customer' | 'sales';
  children: ReactNode;
}) {
  const toneClassName =
    tone === 'customer'
      ? 'border border-[rgba(44,102,247,0.10)] bg-white text-[#292D33]'
      : 'bg-[linear-gradient(90deg,#5D8BFF_0%,#5A8CFF_100%)] text-white';

  return (
    <div className={`flex ${align === 'right' ? 'justify-end' : 'justify-start'}`}>
      <div
        className={[
          'max-w-[86%] px-4 py-2 text-[14px] leading-7',
          toneClassName,
          align === 'left'
            ? 'rounded-[0_16px_16px_16px]'
            : 'rounded-[16px_16px_0_16px]',
        ].join(' ')}
      >
        {children}
      </div>
    </div>
  );
}

function SummaryCallout({
  variant,
  children,
}: {
  variant: 'blue' | 'amber';
  children: ReactNode;
}) {
  const className =
    variant === 'blue'
      ? 'bg-[#EAF1FF] text-[#292D33]'
      : 'border border-[rgba(255,157,10,0.20)] bg-[rgba(255,157,10,0.05)] text-[#4b3d22]';

  return (
    <div className={`rounded-[8px] px-4 py-2 text-[14px] leading-7 ${className}`}>
      <div>{children}</div>
    </div>
  );
}

function ConversationStep({ step }: { step: ScriptStep }) {
  const isHighlight = step.kind === 'highlight';
  const hasTime = step.audioStartTime || step.audioEndTime;
  const stageTitle = isHighlight && step.highlightTitle.trim().length > 0
    ? step.highlightTitle
    : step.stageName;
  const hasStageTitle = stageTitle.trim().length > 0;
  const hasStageSummary = step.stageSummary.trim().length > 0;

  return (
    <div className="space-y-4">
      {hasTime ? (
        <div className="flex items-center gap-2 text-[14px] font-normal leading-5 text-[#999EA8]">
          <StageTimeIcon className="h-4 w-4 shrink-0" />
          <span>
            {[step.audioStartTime, step.audioEndTime].filter(Boolean).join(' - ')}
          </span>
        </div>
      ) : null}

      {hasStageTitle ? (
        <div data-testid="prelearning-stage-title-row" className="flex items-center gap-3">
          <img src={STAGE_AVATAR_URL} alt="阶段头像" className="h-8 w-8 shrink-0 object-contain" />
          <div className="min-w-0 flex-1">
            <h3 className="text-[16px] font-semibold leading-6 text-[#1f2a44]">{stageTitle}</h3>
          </div>
        </div>
      ) : null}

      {hasStageSummary ? (
        <SummaryCallout variant={isHighlight ? 'amber' : 'blue'}>
          <p>{step.stageSummary}</p>
        </SummaryCallout>
      ) : null}

      {isHighlight ? (
        <div className="space-y-4">
          {step.prompt ? <SectionLabel>客户问题</SectionLabel> : null}
          {step.dialogue ? (
            <DialogueBubble align="left" tone="customer">
              {step.dialogue}
            </DialogueBubble>
          ) : null}

          {step.salesPitch ? (
            <>
              <div className="flex justify-end">
                <SectionLabel variant="sales">销冠回复</SectionLabel>
              </div>
              <DialogueBubble align="right" tone="sales">
                {step.salesPitch}
              </DialogueBubble>
            </>
          ) : null}

          {step.analysis ? (
            <SummaryCallout variant="amber">
              <p className="text-[#6C6F75]">{step.analysis}</p>
            </SummaryCallout>
          ) : null}
        </div>
      ) : null}
    </div>
  );
}

function ScriptTimelineCard({ data }: { data: PrelearningInitResponse }) {
  const steps = data.script.gameSteps.filter((step) => (
    step.stageName.trim().length > 0
    || step.stageSummary.trim().length > 0
    || step.audioStartTime.trim().length > 0
    || step.audioEndTime.trim().length > 0
    || (step.kind === 'highlight' && (
      step.highlightTitle.trim().length > 0
      || step.prompt.trim().length > 0
      || step.dialogue.trim().length > 0
      || step.salesPitch.trim().length > 0
      || step.analysis.trim().length > 0
    ))
  ));

  if (steps.length === 0) {
    return null;
  }

  return (
    <section className="space-y-6">
      {steps.map((step, index) => (
        <ConversationStep
          key={`${index}`}
          step={step}
        />
      ))}
    </section>
  );
}

export function PrelearningApp() {
  const [state, setState] = useState<SessionState>({
    mode: 'idle',
    source: null,
    payload: null,
    data: null,
    error: null,
  });
  const [feedback, setFeedback] = useState<FeedbackState | null>(null);
  const [actionSubmitting, setActionSubmitting] = useState<PrelearningActionType | null>(null);
  const requestIdRef = useRef(0);
  const actionRequestIdRef = useRef(0);
  const actionSubmittingRef = useRef(false);
  const lastPayloadRef = useRef<PrelearningInitPayload | null>(null);
  const pageViewTrackedRef = useRef(false);
  const completionBridgePayloadRef = useRef<PrelearningCompleteActivityPayload | null>(null);
  const buriedPointContextRef = useRef<BuriedPointContext | null>(null);
  const bootStartedRef = useRef(false);
  const debugBootContextRef = useRef(getQueryBootContext());
  const globalDebugSessionRef = useRef(window.__PRELEARNING_DEBUG_SESSION__ ?? null);
  const sidebarScrollRef = useRef<HTMLElement | null>(null);
  const allowedOrigins = useMemo(() => getAllowedOrigins(), []);
  const readGateContentKey = state.mode === 'ready' && state.data
    ? `${state.data.sessionId}-${state.data.activityProduct.activityProductId}-${state.data.script.caseId}`
    : null;
  const { contentScrollRef, readGate, getElapsedSeconds } = usePrelearningReadGate(readGateContentKey);

  useEffect(() => {
    buriedPointContextRef.current = state.mode === 'ready' && state.data && state.payload
      ? { data: state.data, payload: state.payload }
      : null;
  }, [state.data, state.mode, state.payload]);

  useEffect(() => {
    if (state.mode !== 'ready' || !state.data || !state.payload || pageViewTrackedRef.current) {
      return;
    }

    pageViewTrackedRef.current = true;
    void safeSendBuriedPoint(
      buildBuriedPointPayload(
        state.data,
        state.payload,
        'page_view',
        getElapsedSeconds(),
      ),
    );
  }, [getElapsedSeconds, state.data, state.mode, state.payload]);

  useEffect(() => {
    if (!readGateContentKey || !sidebarScrollRef.current) {
      return;
    }

    sidebarScrollRef.current.scrollTop = 0;
  }, [readGateContentKey]);

  useEffect(() => {
    if (!feedback) {
      return;
    }

    const timer = window.setTimeout(() => {
      setFeedback(null);
    }, 2800);

    return () => {
      window.clearTimeout(timer);
    };
  }, [feedback]);

  const notifyCompleteActivity = useCallback(async (payload: PrelearningCompleteActivityPayload) => {
    completionBridgePayloadRef.current = payload;

    await loadUniWebviewSdk();
    await waitForBridgeReady();

    const message: PrelearningAppBridgeMessage = {
      source: 'prelearn-h5',
      type: COMPLETE_ACTIVITY_MESSAGE_TYPE,
      payload,
    };
    const sent = postMessageToApp(message);

    if (sent) {
      completionBridgePayloadRef.current = null;
      return true;
    }

    setFeedback({
      tone: 'error',
      message: '学习已保存,但通知 APP 失败,请重试。',
      actionLabel: '重试通知 APP',
    });
    return false;
  }, []);

  const retryCompleteActivity = useCallback(() => {
    const payload = completionBridgePayloadRef.current;
    if (!payload) {
      return;
    }

    void notifyCompleteActivity(payload);
  }, [notifyCompleteActivity]);

  const runInitialization = useCallback(
    async (candidate: Partial<PrelearningInitPayload>, source: SessionState['source'], useMock = false) => {
      const missingFields = findMissingPrelearningFields(candidate);
      if (missingFields.length > 0) {
        setState({
          mode: 'error',
          source,
          payload: null,
          data: null,
          error: {
            title: '初始化参数缺失',
            message: '页面无法继续初始化,请补齐必填字段后重试。',
            details: missingFields.map((field) => `缺少字段:${field}`),
          },
        });
        return;
      }

      const payload = candidate as PrelearningInitPayload;
      const requestId = requestIdRef.current + 1;
      requestIdRef.current = requestId;
      lastPayloadRef.current = payload;
      setFeedback(null);
      setActionSubmitting(null);

      setState({
        mode: 'loading',
        source,
        payload,
        data: null,
        error: null,
      });

      try {
        const response = useMock ? createMockPrelearningResponse(payload) : await fetchPrelearningSession(payload);
        if (requestIdRef.current !== requestId) {
          return;
        }

        setState({
          mode: 'ready',
          source,
          payload,
          data: response,
          error: null,
        });

      } catch (error) {
        if (requestIdRef.current !== requestId) {
          return;
        }

        if (error instanceof PrelearningRequestError) {
          const details = Array.isArray(error.details)
            ? error.details.map((item) => String(item))
            : typeof error.details === 'string'
              ? [error.details]
              : [];

          setState({
            mode: 'error',
            source,
            payload,
            data: null,
            error: {
              title: '初始化失败',
              message: error.message,
              details,
            },
          });
          setFeedback({
            tone: 'error',
            message: error.message,
          });
          return;
        }

        setState({
          mode: 'error',
          source,
          payload,
          data: null,
          error: {
            title: '初始化失败',
            message: '初始化请求失败,请稍后重试。',
            details: [],
          },
        });
        setFeedback({
          tone: 'error',
          message: '初始化请求失败,请稍后重试。',
        });
      }
    },
    [],
  );

  const handleAction = useCallback(
    async (actionType: PrelearningActionType) => {
      if (state.mode !== 'ready' || !state.data || !state.payload || actionSubmittingRef.current) {
        return;
      }

      actionSubmittingRef.current = true;
      const requestId = actionRequestIdRef.current + 1;
      actionRequestIdRef.current = requestId;
      setActionSubmitting(actionType);
      setFeedback(null);

      const payload: PrelearningActionPayload = {
        ...state.payload,
        activityId: String(state.data.activityProduct.activityId),
        activityProductId: String(state.data.activityProduct.activityProductId),
        caseId: state.data.script.caseId,
        sessionId: state.data.sessionId,
      };

      void safeSendBuriedPoint(
        buildBuriedPointPayload(
          state.data,
          state.payload,
          'task_completed',
          getElapsedSeconds(),
        ),
      );

      try {
        const response: PrelearningActionResponse =
          state.source === 'mock'
            ? createMockPrelearningActionResponse(state.data, actionType)
            : await fetchPrelearningAction(actionType, payload);

        if (actionRequestIdRef.current !== requestId) {
          return;
        }

        setState((current) => {
          if (current.mode !== 'ready' || !current.data) {
            return current;
          }

          return {
            ...current,
            payload: {
              ...payload,
              activityId: String(response.activityProduct.activityId),
              activityProductId: String(response.activityProduct.activityProductId),
              caseId: response.script.caseId,
              sessionId: response.sessionId,
            },
            data: {
              ...response,
              actionState: normalizeDisplayedActionState(actionType, response.actionState),
            },
            error: null,
          };
        });

        if (actionType === 'view_other') {
          void safeSendBuriedPoint(
            buildBuriedPointPayload(
              state.data,
              state.payload,
              'reroll_case',
              getElapsedSeconds(),
            ),
          );
        }

        if (actionType === 'complete') {
          const completionPayload: PrelearningCompleteActivityPayload = {
            entrySource: state.payload.entrySource,
            staffUuid: state.payload.staffUuid,
            merchantId: state.payload.merchantId,
            activityId: String(response.activityProduct.activityId),
            activityProductId: String(response.activityProduct.activityProductId),
            caseId: response.script.caseId,
            sessionId: response.sessionId,
          };

          const bridged = await notifyCompleteActivity(completionPayload);
          if (!bridged) {
            return;
          }
        }

        const toastMessage = actionType === 'complete'
          ? undefined
          : response.notice ?? response.actionState.toastMessage;
        if (toastMessage) {
          setFeedback({
            tone: response.actionState.actionType === 'view_other' ? 'info' : 'success',
            message: toastMessage,
          });
        }
      } catch (error) {
        if (actionRequestIdRef.current !== requestId) {
          return;
        }

        const message = error instanceof PrelearningRequestError
          ? error.message
          : '学习动作失败,请稍后重试。';

        setFeedback({
          tone: 'error',
          message,
        });
      } finally {
        if (actionRequestIdRef.current === requestId) {
          actionSubmittingRef.current = false;
          setActionSubmitting(null);
        }
      }
    },
    [state.data, state.mode, state.payload, state.source],
  );

  const retry = useCallback(() => {
    if (state.payload) {
      void runInitialization(state.payload, state.source ?? 'bridge', state.source === 'mock');
      return;
    }

    const queryContext = debugBootContextRef.current;
    if (queryContext) {
      void runInitialization(queryContext.payload, queryContext.source, queryContext.useMock);
      return;
    }

    if (globalDebugSessionRef.current) {
      void runInitialization(globalDebugSessionRef.current, 'global', false);
    }
  }, [runInitialization, state.payload, state.source]);

  useEffect(() => {
    const previousInitializer = window.initPrelearningSession;
    const previousBackIntercepted = window.onPrelearnBackIntercepted;
    window.initPrelearningSession = (payload: PrelearningInitPayload) => {
      void runInitialization(payload, 'bridge', false);
    };
    window.onPrelearnBackIntercepted = () => {
      const context = buriedPointContextRef.current;
      if (!context) {
        return;
      }

      void safeSendBuriedPoint(
        buildBuriedPointPayload(
          context.data,
          context.payload,
          'intercept_back',
          getElapsedSeconds(),
        ),
      );
    };

    return () => {
      window.initPrelearningSession = previousInitializer;
      window.onPrelearnBackIntercepted = previousBackIntercepted;
    };
  }, [getElapsedSeconds, runInitialization]);

  useEffect(() => {
    if (bootStartedRef.current) {
      return;
    }

    bootStartedRef.current = true;

    const bootContext = debugBootContextRef.current;
    if (bootContext) {
      void runInitialization(bootContext.payload, bootContext.source, bootContext.useMock);
      return;
    }

    if (globalDebugSessionRef.current) {
      void runInitialization(globalDebugSessionRef.current, 'global', false);
    }
  }, [runInitialization]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent<unknown>) => {
      if (!isAllowedOrigin(event.origin, allowedOrigins)) {
        return;
      }

      const payload = normalizeBridgePayload(event.data);
      if (!payload) {
        return;
      }

      void runInitialization(payload, 'bridge', false);
    };

    window.addEventListener('message', handleMessage);
    return () => {
      window.removeEventListener('message', handleMessage);
    };
  }, [allowedOrigins, runInitialization]);

  const pageTitle = state.mode === 'ready' && state.data && state.data.script.packageInfo.name.trim().length > 0
    ? buildPrelearningPageTitle(state.data.script.packageInfo.name)
    : null;

  return (
    <main className="h-screen overflow-hidden bg-[#edf4ff] text-[#14213d]">
      <div className="flex h-full w-full flex-col bg-[#edf4ff]">
        <FeedbackToast state={feedback} onAction={retryCompleteActivity} />
        <header
          data-testid="app-header-slot"
          className="flex h-12 pt-8 shrink-0 items-center justify-center px-12"
        >
          {pageTitle ? (
            <h1 className="max-w-full truncate text-[17px] font-semibold leading-6 text-[#14213d]">
              {pageTitle}
            </h1>
          ) : null}
        </header>

        <section className="min-h-0 flex-1 overflow-hidden px-8 pb-8 pt-4">
          {state.mode === 'idle' ? (
            <EmptyState
              title="等待 APP 或调试上下文初始化"
              description="可以在控制台调用 window.initPrelearningSession(payload),或通过 query / mock 启用浏览器调试模式。"
            />
          ) : null}

          {state.mode === 'loading' ? <LoadingBlock message="正在初始化预学习会话" /> : null}

          {state.mode === 'error' && state.error ? (
            <ErrorState error={state.error} onRetry={retry} retryLabel="重试初始化" />
          ) : null}

          {state.mode === 'ready' && state.data ? (
            <div className="flex h-full min-h-0 gap-[30px]">
              <aside
                ref={sidebarScrollRef}
                aria-label="预学习基础信息"
                className="min-h-0 w-[300px] shrink-0 overflow-y-auto pr-1"
                data-testid="prelearning-sidebar-scroll"
              >
                <div className="space-y-3">
                  <CustomerCard data={state.data} />
                  <ProductCard data={state.data} />
                  <ObjectionCard items={toArray(state.data.script.profile.objections)} />
                  <DemandCard items={state.data.script.profile.needs} />
                </div>
              </aside>

              <div
                ref={contentScrollRef}
                data-testid="prelearning-content-scroll"
                className="min-h-0 flex-1 overflow-y-auto pr-1"
              >
                <div className="min-h-full rounded-[var(--3,16px)] border-2 border-white bg-[linear-gradient(180deg,rgba(255,255,255,0.80)_0%,#F2F7FF_100%)] p-6">
                  <div data-testid="prelearning-layout-grid" className="space-y-5">
                    <div aria-label="预学习剧本内容" className="min-w-0 space-y-3">
                      <ScriptTimelineCard data={state.data} />
                    </div>

                    <ReadGateFooter
                      state={readGate}
                      actionState={state.data?.actionState ?? {
                        actionType: 'view_other',
                        buttonLabel: '查看其他案例',
                        disabled: true,
                        disabledReason: '当前没有可执行的学习动作',
                      }}
                      submitting={Boolean(actionSubmitting)}
                      onAction={handleAction}
                    />
                  </div>
                </div>
              </div>
            </div>
          ) : null}

        </section>

      </div>
    </main>
  );
}