index.html 32.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
<!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="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📉</text></svg>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Sans+SC:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
  *{ box-sizing:border-box; }
  html{ color-scheme: light; }
  body{ margin: 0; }
  :root{
    color-scheme: light;
    --page:      #f9f9f7;
    --surface:   #fcfcfb;
    --ink:       #0b0b0b;
    --ink-2:     #52514e;
    --muted:     #898781;
    --grid:      #e1e0d9;
    --border:    rgba(11,11,11,0.10);
    --good:      #0ca30c;
    --critical:  #d03b3b;
    --accent:    #2a78d6;
    --spout:     #0d366b;
    --alert-red:    #d03b3b;
    --alert-yellow: #eda100;
    --alert-blue:   #2a78d6;
    --alert-green:  #008300;
    --shadow:    0 1px 2px rgba(11,11,11,0.05), 0 8px 24px -12px rgba(11,11,11,0.18);
  }
  @media (prefers-color-scheme: dark){
    :root:not([data-theme="light"]){
      color-scheme: dark;
      --page:      #0d0d0d;
      --surface:   #1a1a19;
      --ink:       #ffffff;
      --ink-2:     #c3c2b7;
      --muted:     #898781;
      --grid:      #2c2c2a;
      --border:    rgba(255,255,255,0.10);
      --good:      #0ca30c;
      --critical:  #d03b3b;
      --accent:    #3987e5;
      --spout:     #cde2fb;
      --alert-red:    #d03b3b;
      --alert-yellow: #c98500;
      --alert-blue:   #3987e5;
      --alert-green:  #008300;
      --shadow:    0 1px 2px rgba(0,0,0,0.4), 0 8px 28px -12px rgba(0,0,0,0.6);
    }
  }
  :root[data-theme="dark"]{
    color-scheme: dark;
    --page:      #0d0d0d;
    --surface:   #1a1a19;
    --ink:       #ffffff;
    --ink-2:     #c3c2b7;
    --muted:     #898781;
    --grid:      #2c2c2a;
    --border:    rgba(255,255,255,0.10);
    --good:      #0ca30c;
    --critical:  #d03b3b;
    --accent:    #3987e5;
    --spout:     #cde2fb;
    --alert-red:    #d03b3b;
    --alert-yellow: #c98500;
    --alert-blue:   #3987e5;
    --alert-green:  #008300;
    --shadow:    0 1px 2px rgba(0,0,0,0.4), 0 8px 28px -12px rgba(0,0,0,0.6);
  }

  body{
    background: var(--page);
    color: var(--ink);
    font-family: "IBM Plex Sans", "IBM Plex Sans SC", system-ui, -apple-system, "Segoe UI", sans-serif;
  }
  .wrap{
    max-width: 1220px;
    margin: 0 auto;
    padding-inline: clamp(16px, 4vw, 32px);
    padding-block: clamp(20px, 4vw, 40px);
  }
  .mono{ font-family: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace; }
  .tab{ font-variant-numeric: tabular-nums; }

  header{
    display:flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-end;
    gap: 16px;
    margin-bottom: 28px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border);
  }
  header h1{
    margin:0;
    font-size: clamp(22px, 3vw, 28px);
    font-weight: 700;
    letter-spacing: -0.01em;
    text-wrap: balance;
  }
  header p{
    margin: 6px 0 0;
    color: var(--ink-2);
    font-size: 13.5px;
    max-width: 60ch;
    line-height: 1.5;
  }
  .eyebrow{
    display:block;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: var(--accent);
    margin-bottom: 6px;
  }
  .reset-btn{
    appearance:none;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--ink-2);
    font: inherit;
    font-size: 13px;
    font-weight: 500;
    padding: 9px 14px;
    border-radius: 8px;
    cursor: pointer;
    white-space: nowrap;
  }
  .reset-btn:hover{ color: var(--ink); border-color: var(--ink-2); }
  .reset-btn:focus-visible{ outline: 2px solid var(--accent); outline-offset: 2px; }

  .stats{
    display:grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    margin-bottom: 24px;
  }
  @media (max-width: 720px){ .stats{ grid-template-columns: repeat(2, 1fr); } }
  .stat{
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 14px 16px;
  }
  .stat .label{
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    color: var(--muted);
    margin-bottom: 8px;
  }
  .stat .value{
    font-size: 21px;
    font-weight: 600;
    letter-spacing: -0.01em;
  }
  .stat .sub{
    margin-top: 4px;
    font-size: 12px;
    color: var(--ink-2);
  }
  .badge{
    display:inline-flex;
    align-items:center;
    gap: 4px;
    font-size: 11.5px;
    font-weight: 600;
    padding: 2px 7px;
    border-radius: 999px;
  }
  .badge.red{ color: var(--alert-red); background: color-mix(in srgb, var(--alert-red) 14%, transparent); }
  .badge.yellow{ color: var(--alert-yellow); background: color-mix(in srgb, var(--alert-yellow) 18%, transparent); }
  .badge.blue{ color: var(--alert-blue); background: color-mix(in srgb, var(--alert-blue) 14%, transparent); }
  .badge.green{ color: var(--alert-green); background: color-mix(in srgb, var(--alert-green) 14%, transparent); }

  .alert-legend{
    display:flex;
    flex-wrap: wrap;
    gap: 16px;
    margin: -10px 0 20px;
    font-size: 11.5px;
    color: var(--ink-2);
  }
  .alert-legend .item{ display:flex; align-items:center; gap:6px; }

  .status-line{
    font-size: 11.5px;
    font-weight: 600;
    margin: 0 12px 10px 0;
  }

  .board{
    display:grid;
    grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr);
    gap: 20px;
    align-items: start;
  }
  @media (max-width: 900px){ .board{ grid-template-columns: 1fr; } }

  .panel{
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 14px;
    box-shadow: var(--shadow);
    overflow: hidden;
  }
  .panel-head{
    display:flex;
    justify-content: space-between;
    align-items: baseline;
    gap: 10px;
    padding: 16px 18px 0;
  }
  .panel-head h2{
    margin:0;
    font-size: 14px;
    font-weight: 600;
  }
  .panel-head span{
    font-size: 11.5px;
    color: var(--muted);
  }

  .funnel-stage{
    position: relative;
    aspect-ratio: 4 / 4.4;
    max-width: 100%;
    cursor: grab;
  }
  .funnel-stage canvas{ display:block; width:100%; height:100%; touch-action: none; }
  .labels{
    position: absolute;
    inset: 0;
    pointer-events: none;
  }
  .flabel{
    position:absolute;
    transform: translate(0, -50%);
    display:flex;
    flex-direction: column;
    gap: 2px;
    padding: 4px 8px;
    border-radius: 8px;
    background: color-mix(in srgb, var(--surface) 82%, transparent);
    border: 1px solid var(--border);
    backdrop-filter: blur(2px);
    font-size: 11px;
    line-height: 1.3;
    white-space: nowrap;
    transition: opacity 120ms linear;
  }
  .flabel.left{ transform: translate(-100%, -50%); }
  .flabel .name{ font-weight: 600; color: var(--ink); }
  .flabel .val{ color: var(--ink-2); }
  .flabel .conv{ font-weight: 600; }
  .funnel-hint{
    padding: 8px 18px 14px;
    font-size: 11.5px;
    color: var(--muted);
  }

  .tree{
    max-height: 620px;
    overflow-y: auto;
    padding: 6px 6px 14px;
  }
  .tnode{ position: relative; }
  .trow{
    display:flex;
    align-items:center;
    gap: 8px;
    padding: 7px 12px 7px 0;
    border-radius: 8px;
    font-size: 13px;
  }
  .trow.flash{ animation: flashBg 900ms ease; }
  @keyframes flashBg{
    0%{ background: color-mix(in srgb, var(--accent) 22%, transparent); }
    100%{ background: transparent; }
  }
  .trow-toggle{
    appearance:none;
    border:none;
    background:none;
    color: var(--muted);
    width: 16px;
    height: 16px;
    flex-shrink:0;
    font-size: 10px;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
  }
  .trow-toggle:focus-visible{ outline: 2px solid var(--accent); border-radius: 4px; }
  .trow-toggle-spacer{ width:16px; height:16px; flex-shrink:0; display:inline-block; }
  .dot{
    width: 9px; height: 9px;
    border-radius: 3px;
    flex-shrink:0;
  }
  .dot-muted{ background: var(--grid); border: 1px solid var(--border); }
  .trow-name{
    flex: 1 1 auto;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-weight: 500;
  }
  .tnode[data-depth="0"] > .trow .trow-name{ font-weight: 600; }
  .trow-right{
    display:flex;
    align-items:center;
    gap: 10px;
    flex-shrink:0;
  }
  .trow-val{ font-size: 13px; }
  .trow-val.strong{ font-weight: 600; }
  .trow-pct{
    font-size: 11.5px;
    color: var(--muted);
    width: 34px;
    text-align: right;
  }
  input.val-input{
    width: 96px;
    text-align: right;
    border: 1px solid var(--border);
    background: var(--page);
    color: var(--ink);
    border-radius: 6px;
    padding: 5px 7px;
    font: inherit;
    font-family: "IBM Plex Mono", ui-monospace, monospace;
    font-size: 12.5px;
    font-variant-numeric: tabular-nums;
  }
  input.val-input:focus-visible{ outline: 2px solid var(--accent); outline-offset: 1px; }
  .trow-bar-track{
    height: 3px;
    border-radius: 2px;
    background: var(--grid);
    margin: 0 12px 2px 0;
    overflow: hidden;
  }
  .trow-bar-fill{ height: 100%; border-radius: 2px; }
  .notes-row{
    display:flex;
    flex-wrap:wrap;
    gap: 6px;
    margin: 0 12px 8px 0;
  }
  .chip{
    font-size: 11px;
    color: var(--ink-2);
    background: var(--page);
    border: 1px solid var(--border);
    border-radius: 999px;
    padding: 2px 9px;
  }
  .loop-note{
    font-size: 11.5px;
    color: var(--accent);
    margin: 0 12px 10px 0;
  }
  .tchildren{ position: relative; }

  footer{
    margin-top: 22px;
    font-size: 12px;
    color: var(--muted);
    line-height: 1.6;
  }
</style>
</head>
<body>
<div class="wrap">
  <header>
    <div>
      <span class="eyebrow">产品增长漏斗模型</span>
      <h1>转化漏斗建模台</h1>
      <p>流量入口 → 网站访问 → 注册 → 使用 → 付费点 → 选购积分 → 订单支付 → 支付状态 → 传播裂变。点击右侧箭头展开各级渠道明细,数值可编辑。</p>
    </div>
    <button class="reset-btn" id="resetBtn" type="button">重置为示例数据</button>
  </header>

  <div class="stats" id="statsRow"></div>
  <div class="alert-legend" id="alertLegend"></div>

  <div class="board">
    <section class="panel">
      <div class="panel-head">
        <h2>漏斗模型(3D)</h2>
        <span>拖动旋转 · 滚轮缩放 · 点击定位明细</span>
      </div>
      <div class="funnel-stage" id="funnelStage">
        <canvas id="funnelCanvas"></canvas>
        <div class="labels" id="labelLayer"></div>
      </div>
      <p class="funnel-hint">柱体宽度按各级流量的平方根缩放,颜色按本级转化率相对目标值分级:低于目标一半为红色,低于目标为黄色,达到目标为蓝色,达到 2 倍目标为绿色。支付状态一级以「支付成功」延续漏斗,「支付失败」计为本级流失。</p>
    </section>

    <section class="panel">
      <div class="panel-head">
        <h2>各级明细</h2>
        <span>可编辑</span>
      </div>
      <div class="tree" id="treeLayer"></div>
    </section>
  </div>

  <footer>数值为示例数据,可编辑替换为真实业务口径;带子项的行为下级之和,仅末级数值可编辑;灰色标签为该环节涉及的配置维度(非独立计数)。</footer>
</div>

<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script>
(function(){
  "use strict";

  // ---------- data model ----------
  // A node is either a leaf ({name, value[, notes, status]}) or a branch
  // ({name, children[...]}) whose value is the sum of its children.
  var TREE = [
    { name: "流量入口", children: [
        { name: "自有社媒平台", children: [
            { name: "TikTok",    value: 28000 },
            { name: "YouTube",   value: 21000 },
            { name: "Instagram", value: 9000  },
            { name: "Facebook",  value: 6000  },
            { name: "Trea",      value: 3000  },
            { name: "Discord",   value: 4000  },
            { name: "Reddit",    value: 5000  }
          ]
        },
        { name: "广告投放", value: 55000 },
        { name: "邮件投放", children: [
            { name: "LemonAI 邮件列表", value: 18000 }
          ]
        },
        { name: "KOL / KOC 社媒平台", value: 30000 },
        { name: "SEO / GEO", value: 15000 },
        { name: "榜单平台", children: [
            { name: "Product Hunt", value: 4000 },
            { name: "产品集合站",    value: 2000 }
          ]
        }
      ]
    },
    { name: "网站访问(看视频)", value: 96000 },
    { name: "网站注册", value: 38400 },
    { name: "网站使用(游玩游戏)", children: [
        { name: "文字输入",         value: 10000 },
        { name: "语音输入",         value: 4200  },
        { name: "视频生成(切片)", value: 6800  },
        { name: "视频生成(全局)", value: 3880  },
        { name: "游戏生成(Free)", value: 2000  }
      ]
    },
    { name: "网站付费点", children: [
        { name: "剧情改写费", value: 5200 },
        { name: "视频生成费", value: 2864 }
      ]
    },
    { name: "选购积分", children: [
        { name: "每日登录领取积分", value: 2000 },
        { name: "购买积分页面", value: 3645,
          notes: ["多个档位", "多种订阅方式", "自动充值开关"] }
      ]
    },
    { name: "订单支付", value: 3200,
      notes: ["支付方式选择", "支付银行卡选择", "优惠券输入"] },
    { name: "支付状态", children: [
        { name: "支付失败", value: 640, status: "critical" },
        { name: "支付成功", status: "good", children: [
            { name: "订阅成功(首次)", value: 1400 },
            { name: "订阅续费",       value: 900  },
            { name: "自动充值",       value: 260  }
          ]
        }
      ]
    },
    { name: "用户传播裂变", children: [
        { name: "分享按钮", children: [
            { name: "X",         value: 300 },
            { name: "YouTube",   value: 150 },
            { name: "TikTok",    value: 220 },
            { name: "Instagram", value: 180 },
            { name: "Facebook",  value: 130 }
          ]
        },
        { name: "下载视频",       value: 640 },
        { name: "新用户邀请积分", value: 410 }
      ]
    }
  ];

  var nf = new Intl.NumberFormat("zh-CN");
  var pf = new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 1, minimumFractionDigits: 1 });
  function fmtPct(x){ return pf.format(x * 100) + "%"; }

  function isLeaf(node){ return !(node.children && node.children.length); }
  function getValue(node){
    if (isLeaf(node)) return node.value || 0;
    return node.children.reduce(function(sum, c){ return sum + getValue(c); }, 0);
  }
  function forEachNode(nodes, fn){
    nodes.forEach(function(n){ fn(n); if (n.children) forEachNode(n.children, fn); });
  }

  var idIndex = {};
  (function walk(nodes, prefix, depth, parent){
    nodes.forEach(function(node, i){
      var id = prefix ? prefix + "-" + i : String(i);
      node.__id = id;
      node.__depth = depth;
      node.__parent = parent || null;
      if (isLeaf(node)) node.__defaultValue = node.value;
      idIndex[id] = node;
      if (node.children) walk(node.children, id, depth + 1, node);
    });
  })(TREE, "", 0, null);

  var payStatusNode = TREE[7];
  var paySuccessNode = payStatusNode.children.filter(function(c){ return c.name === "支付成功"; })[0];
  var payFailNode = payStatusNode.children.filter(function(c){ return c.name === "支付失败"; })[0];

  function funnelValues(){
    return TREE.map(function(node){
      return node === payStatusNode ? getValue(paySuccessNode) : getValue(node);
    });
  }

  // ---------- target-based alert levels ----------
  // Estimated target conversion rate INTO each stage (index aligned to TREE);
  // index 0 (流量入口) has no incoming rate. Replace with real business targets
  // once available.
  var TARGETS = [null, 0.50, 0.25, 0.60, 0.20, 0.50, 0.40, 0.90, 0.20];
  var ALERT_TEXT = {
    red:    "红色 · 低于目标一半",
    yellow: "黄色 · 低于目标",
    blue:   "蓝色 · 已达标",
    green:  "绿色 · 超额达标(≥2×目标)"
  };
  var ALERT_SHORT = { red: "警戒", yellow: "待改善", blue: "达标", green: "超额" };

  function stageStatus(i, vals){
    var target = TARGETS[i];
    if (target == null) return { rate: null, target: null, level: null };
    var rate = vals[i - 1] > 0 ? vals[i] / vals[i - 1] : 0;
    var level;
    if (rate < target / 2) level = "red";
    else if (rate < target) level = "yellow";
    else if (rate < target * 2) level = "blue";
    else level = "green";
    return { rate: rate, target: target, level: level };
  }

  function alertVar(level){
    return level === "red" ? "--alert-red"
      : level === "yellow" ? "--alert-yellow"
      : level === "green" ? "--alert-green"
      : level === "blue" ? "--alert-blue"
      : "--muted";
  }

  function renderLegend(){
    document.getElementById("alertLegend").innerHTML =
      '<span class="item"><span class="dot" style="background:var(--alert-red)"></span>低于目标一半</span>' +
      '<span class="item"><span class="dot" style="background:var(--alert-yellow)"></span>低于目标</span>' +
      '<span class="item"><span class="dot" style="background:var(--alert-blue)"></span>达到目标</span>' +
      '<span class="item"><span class="dot" style="background:var(--alert-green)"></span>达到 2 倍目标</span>';
  }

  var expanded = {};
  TREE.forEach(function(n){ expanded[n.__id] = true; });

  function resetToDefaults(){
    forEachNode(TREE, function(n){ if (isLeaf(n)) n.value = n.__defaultValue; });
    renderAll();
  }
  document.getElementById("resetBtn").addEventListener("click", resetToDefaults);

  // ---------- stats row ----------
  var statsRow = document.getElementById("statsRow");

  function renderStats(){
    var vals = funnelValues();
    var top = vals[0];
    var overall = top > 0 ? vals[vals.length - 1] / top : 0;

    var steps = [];
    for (var i = 1; i < vals.length; i++){
      var st = stageStatus(i, vals);
      steps.push({
        label: TREE[i - 1].name + " → " + TREE[i].name,
        st: st,
        ratio: st.target > 0 ? st.rate / st.target : 0
      });
    }
    var passCount = steps.filter(function(s){ return s.st.level === "blue" || s.st.level === "green"; }).length;
    var worst = steps.reduce(function(a, b){ return b.ratio < a.ratio ? b : a; });

    statsRow.innerHTML =
      '<div class="stat"><div class="label">顶部流量</div>' +
        '<div class="value mono tab">' + nf.format(top) + "</div>" +
        '<div class="sub">' + TREE[0].name + "</div></div>" +
      '<div class="stat"><div class="label">整体转化率</div>' +
        '<div class="value mono tab">' + fmtPct(overall) + "</div>" +
        '<div class="sub">' + TREE[0].name + " → " + TREE[TREE.length - 1].name + "</div></div>" +
      '<div class="stat"><div class="label">达标环节</div>' +
        '<div class="value mono tab">' + passCount + " / " + steps.length + "</div>" +
        '<div class="sub">蓝色或绿色(≥目标)环节数</div></div>' +
      '<div class="stat"><div class="label">最需关注</div>' +
        '<div class="value mono tab" style="color:var(' + alertVar(worst.st.level) + ')">' + fmtPct(worst.st.rate) + "</div>" +
        '<div class="sub"><span class="badge ' + worst.st.level + '">● ' + ALERT_SHORT[worst.st.level] + "</span>&nbsp;" + worst.label + "</div></div>";
  }

  function tokenHex(name){
    return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
  }

  function stageColorHex(i, vals){
    if (i === 0) return tokenHex("--muted");
    return tokenHex(alertVar(stageStatus(i, vals).level));
  }

  // ---------- editable tree panel ----------
  var treeLayer = document.getElementById("treeLayer");

  function renderNode(node, topIndex, vals){
    var depth = node.__depth;
    var hasChildren = !isLeaf(node);
    var wrapper = document.createElement("div");
    wrapper.className = "tnode";
    wrapper.setAttribute("data-depth", depth);

    var row = document.createElement("div");
    row.className = "trow";
    row.style.paddingLeft = (14 + depth * 18) + "px";
    if (depth === 0) row.id = "stage-row-" + topIndex;

    var toggleHtml = hasChildren
      ? '<button class="trow-toggle" type="button" aria-label="展开或收起' + node.name + '" data-id="' + node.__id + '">' + (expanded[node.__id] ? "▾" : "▸") + "</button>"
      : '<span class="trow-toggle-spacer"></span>';

    var dotHtml;
    if (depth === 0){
      dotHtml = '<span class="dot" style="background:' + stageColorHex(topIndex, vals) + '"></span>';
    } else if (node.status === "critical"){
      dotHtml = '<span class="dot" style="background:var(--critical)"></span>';
    } else if (node.status === "good"){
      dotHtml = '<span class="dot" style="background:var(--good)"></span>';
    } else {
      dotHtml = '<span class="dot dot-muted"></span>';
    }

    var val = getValue(node);
    var parentVal = node.__parent ? getValue(node.__parent) : null;
    var pct = parentVal ? (val / parentVal * 100) : null;

    var valueHtml = hasChildren
      ? '<span class="trow-val mono tab strong">' + nf.format(val) + "</span>"
      : '<input class="val-input mono" type="number" min="0" step="1" value="' + val + '" data-id="' + node.__id + '" aria-label="' + node.name + ' 数值">';

    row.innerHTML = toggleHtml + dotHtml +
      '<span class="trow-name">' + node.name + "</span>" +
      '<span class="trow-right">' + valueHtml +
        (pct !== null ? '<span class="trow-pct mono tab">' + pct.toFixed(0) + "%</span>" : "") +
      "</span>";
    wrapper.appendChild(row);

    if (pct !== null){
      var bar = document.createElement("div");
      bar.className = "trow-bar-track";
      bar.style.marginLeft = (14 + depth * 18 + 22) + "px";
      bar.innerHTML = '<div class="trow-bar-fill" style="width:' + Math.min(100, pct) + '%; background:var(--muted)"></div>';
      wrapper.appendChild(bar);
    }

    if (node.notes && node.notes.length){
      var notesRow = document.createElement("div");
      notesRow.className = "notes-row";
      notesRow.style.marginLeft = (14 + depth * 18 + 22) + "px";
      notesRow.innerHTML = node.notes.map(function(t){ return '<span class="chip">' + t + "</span>"; }).join("");
      wrapper.appendChild(notesRow);
    }

    if (node === payStatusNode){
      var failVal = getValue(payFailNode);
      var note = document.createElement("div");
      note.className = "loop-note";
      note.style.color = "var(--critical)";
      note.style.marginLeft = (14 + depth * 18 + 22) + "px";
      note.textContent = "本级流失(支付失败):" + nf.format(failVal) + ",漏斗以「支付成功」延续";
      wrapper.appendChild(note);
    }
    if (node.name === "用户传播裂变"){
      var loop = document.createElement("div");
      loop.className = "loop-note";
      loop.style.marginLeft = (14 + depth * 18 + 22) + "px";
      loop.textContent = "↻ 邀请奖励反哺「流量入口」,形成增长闭环";
      wrapper.appendChild(loop);
    }

    if (depth === 0 && topIndex >= 1){
      var st = stageStatus(topIndex, vals);
      var statusLine = document.createElement("div");
      statusLine.className = "status-line";
      statusLine.style.marginLeft = (14 + depth * 18 + 22) + "px";
      statusLine.style.color = "var(" + alertVar(st.level) + ")";
      statusLine.textContent = "目标 " + fmtPct(st.target) + " · 实际 " + fmtPct(st.rate) + " · " + ALERT_TEXT[st.level];
      wrapper.appendChild(statusLine);
    }

    if (hasChildren && expanded[node.__id]){
      var childWrap = document.createElement("div");
      childWrap.className = "tchildren";
      node.children.forEach(function(c){ childWrap.appendChild(renderNode(c, topIndex, vals)); });
      wrapper.appendChild(childWrap);
    }

    return wrapper;
  }

  function renderTree(){
    var vals = funnelValues();
    treeLayer.innerHTML = "";
    TREE.forEach(function(node, i){ treeLayer.appendChild(renderNode(node, i, vals)); });
  }

  treeLayer.addEventListener("click", function(e){
    var btn = e.target.closest(".trow-toggle");
    if (!btn) return;
    var id = btn.getAttribute("data-id");
    expanded[id] = !expanded[id];
    renderTree();
  });

  treeLayer.addEventListener("input", function(e){
    if (!e.target.classList.contains("val-input")) return;
    var id = e.target.getAttribute("data-id");
    var node = idIndex[id];
    var caret = e.target.selectionStart;
    var v = parseFloat(e.target.value);
    if (isNaN(v) || v < 0) v = 0;
    node.value = v;
    renderStats();
    renderTree();
    rebuildFunnel();
    var again = treeLayer.querySelector('[data-id="' + id + '"]');
    if (again){
      again.focus();
      try { again.setSelectionRange(caret, caret); } catch (err) {}
    }
  });

  function highlightStage(idx){
    var row = document.getElementById("stage-row-" + idx);
    if (!row) return;
    row.scrollIntoView({ behavior: "smooth", block: "center" });
    row.classList.remove("flash");
    void row.offsetWidth;
    row.classList.add("flash");
  }

  // ---------- three.js funnel ----------
  var stageEl = document.getElementById("funnelStage");
  var canvas = document.getElementById("funnelCanvas");
  var labelLayer = document.getElementById("labelLayer");

  var renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true, alpha: true });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));

  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
  camera.position.set(0.3, 1.6, 13.5);

  var controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.08;
  controls.enablePan = false;
  controls.minDistance = 8;
  controls.maxDistance = 19;
  controls.target.set(0, 0.2, 0);
  controls.update();

  scene.add(new THREE.AmbientLight(0xffffff, 0.65));
  var key = new THREE.DirectionalLight(0xffffff, 0.9);
  key.position.set(4, 6, 6);
  scene.add(key);
  var fill = new THREE.DirectionalLight(0xffffff, 0.35);
  fill.position.set(-5, -2, 3);
  scene.add(fill);

  var funnelGroup = new THREE.Group();
  scene.add(funnelGroup);

  var TOTAL_HEIGHT = 8.6;
  var MIN_R = 0.26;
  var MAX_R = 2.7;
  var SPOUT_H = 0.7;

  var segments = [];

  function radiusFor(v, maxV){
    if (maxV <= 0) return MIN_R;
    var frac = Math.max(0, v) / maxV;
    return MIN_R + (MAX_R - MIN_R) * Math.sqrt(Math.min(1, frac));
  }

  function buildFunnel(){
    while (funnelGroup.children.length) funnelGroup.remove(funnelGroup.children[0]);
    segments = [];

    var vals = funnelValues();
    var n = vals.length;
    var maxV = Math.max.apply(null, vals);
    var segH = TOTAL_HEIGHT / n;
    var topY = TOTAL_HEIGHT / 2;

    for (var i = 0; i < n; i++){
      var rTop = radiusFor(vals[i], maxV);
      var rBottom = (i < n - 1) ? radiusFor(vals[i + 1], maxV) : rTop * 0.6;
      var y0 = topY - i * segH;
      var yc = y0 - segH / 2;

      var geo = new THREE.CylinderGeometry(rTop, rBottom, segH, 48, 1, true);
      var mat = new THREE.MeshStandardMaterial({
        color: new THREE.Color(stageColorHex(i, vals)),
        metalness: 0.12,
        roughness: 0.55,
        side: THREE.DoubleSide
      });
      var mesh = new THREE.Mesh(geo, mat);
      mesh.position.y = yc;
      funnelGroup.add(mesh);

      var edgeGeo = new THREE.EdgesGeometry(geo, 25);
      var edgeMat = new THREE.LineBasicMaterial({ color: 0x000000, transparent: true, opacity: 0.18 });
      var edges = new THREE.LineSegments(edgeGeo, edgeMat);
      edges.position.y = yc;
      funnelGroup.add(edges);

      var side = i % 2 === 0 ? 1 : -1;
      var anchor = new THREE.Object3D();
      var rMid = (rTop + rBottom) / 2;
      anchor.position.set(side * (rMid + 0.4), yc, 0);
      anchor.userData.side = side;
      funnelGroup.add(anchor);

      segments.push({ mesh: mesh, mat: mat, anchor: anchor, side: side });
    }

    var lastR = radiusFor(vals[n - 1], maxV) * 0.6;
    var spoutGeo = new THREE.CylinderGeometry(lastR, lastR * 0.85, SPOUT_H, 32, 1, true);
    var spoutMat = new THREE.MeshStandardMaterial({
      color: new THREE.Color(tokenHex("--spout") || "#0d366b"),
      metalness: 0.2,
      roughness: 0.4,
      side: THREE.DoubleSide
    });
    var spout = new THREE.Mesh(spoutGeo, spoutMat);
    spout.position.y = -TOTAL_HEIGHT / 2 - SPOUT_H / 2;
    funnelGroup.add(spout);

    buildLabels(vals);
  }

  function updateFunnelColors(){
    var vals = funnelValues();
    segments.forEach(function(seg, i){ seg.mat.color.set(stageColorHex(i, vals)); });
  }

  // ---------- projected HTML labels ----------
  var labelEls = [];

  function buildLabels(vals){
    labelLayer.innerHTML = "";
    labelEls = [];
    TREE.forEach(function(node, i){
      var el = document.createElement("div");
      el.className = "flabel" + (segments[i] && segments[i].side < 0 ? " left" : "");
      var st = i === 0 ? null : stageStatus(i, vals);
      var convHtml = st === null
        ? '<span class="conv" style="color:var(--muted)">起点</span>'
        : '<span class="conv" style="color:var(' + alertVar(st.level) + ')">' + fmtPct(st.rate) + " / 目标 " + fmtPct(st.target) + "</span>";
      var extra = node === payStatusNode ? ' <span style="color:var(--critical)">(失败 ' + nf.format(getValue(payFailNode)) + ")</span>" : "";
      el.innerHTML =
        '<span class="name">' + node.name + "</span>" +
        '<span class="val mono tab">' + nf.format(vals[i]) + extra + "</span>" +
        convHtml;
      labelLayer.appendChild(el);
      labelEls.push(el);
    });
  }

  var _v = new THREE.Vector3();
  function updateLabelPositions(){
    if (!segments.length) return;
    var rect = stageEl.getBoundingClientRect();
    var w = rect.width, h = rect.height;
    segments.forEach(function(seg, i){
      var el = labelEls[i];
      if (!el) return;
      seg.anchor.getWorldPosition(_v);
      _v.project(camera);
      var visible = _v.z < 1;
      var x = (_v.x * 0.5 + 0.5) * w;
      var y = (-_v.y * 0.5 + 0.5) * h;
      el.style.left = x + "px";
      el.style.top = y + "px";
      el.style.opacity = visible ? "1" : "0";
    });
  }

  function rebuildFunnel(){ buildFunnel(); }

  function resizeRenderer(){
    var rect = stageEl.getBoundingClientRect();
    var w = Math.max(1, rect.width);
    var h = Math.max(1, rect.height);
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
  }

  var ro = new ResizeObserver(resizeRenderer);
  ro.observe(stageEl);

  var raycaster = new THREE.Raycaster();
  var downPos = null;
  canvas.addEventListener("pointerdown", function(e){ downPos = { x: e.clientX, y: e.clientY }; });
  canvas.addEventListener("pointerup", function(e){
    if (!downPos) return;
    var dx = e.clientX - downPos.x, dy = e.clientY - downPos.y;
    downPos = null;
    if (Math.hypot(dx, dy) > 4) return;
    var rect = canvas.getBoundingClientRect();
    var ndc = new THREE.Vector2(
      ((e.clientX - rect.left) / rect.width) * 2 - 1,
      -((e.clientY - rect.top) / rect.height) * 2 + 1
    );
    raycaster.setFromCamera(ndc, camera);
    var meshes = segments.map(function(s){ return s.mesh; });
    var hits = raycaster.intersectObjects(meshes);
    if (hits.length) highlightStage(meshes.indexOf(hits[0].object));
  });

  function tick(){
    controls.update();
    renderer.render(scene, camera);
    updateLabelPositions();
    requestAnimationFrame(tick);
  }

  var media = window.matchMedia("(prefers-color-scheme: dark)");
  function onThemeChange(){ updateFunnelColors(); }
  if (media.addEventListener) media.addEventListener("change", onThemeChange);
  new MutationObserver(onThemeChange).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });

  function renderAll(){
    renderStats();
    renderTree();
    rebuildFunnel();
  }

  renderLegend();
  resizeRenderer();
  renderAll();
  requestAnimationFrame(tick);
  window.addEventListener("resize", resizeRenderer);
})();
</script>
</body>
</html>