redesign-v2.html 57.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>深圳市道路风险监测看板 · 重构原型 v2(交管局领导视角)</title>
<style>
/* ==========================================================================
   令牌(替换 design.css:11-88)
   语义色收敛到 4 种;热力色阶 5 段、明度单调递减;字阶 4 档比值 ≥1.5;
   圆角 3 档;阴影 2 档;栅格 8px 基准。
   ========================================================================== */
:root{
  --ink:#141A2E; --ink-2:#4A5268; --ink-3:#858D9E;
  --line:#E4E7EC; --line-2:#EEF0F4;
  --surface:#FFFFFF; --surface-2:#F7F8FA; --bg:#F2F4F7;
  --brand:#4653A2; --brand-wash:#EEF0F8; --brand-ink:#33407F;
  --link:#0E7FB0; --link-wash:#E6F1F8;
  --danger:#B42318; --warn:#B54708;
  --ok:#1F7A46;

  /* 热力色阶 5 段:黄→橙→红,明度单调递减(L* 96→88→70→55→38) */
  --heat-1:#FFEFD0; --heat-2:#FFD08A; --heat-3:#FF9A4D; --heat-4:#E8590C; --heat-5:#B42318;

  --fs-1:34px; --fs-2:22px; --fs-3:14px; --fs-4:11.5px;
  --r-panel:12px; --r-ctl:6px; --r-pill:999px;
  --sh-1:0 1px 2px rgba(16,24,40,.04), 0 8px 24px -12px rgba(16,24,40,.14);
  --sh-2:0 12px 32px -8px rgba(16,24,40,.26);
  --sp-1:8px; --sp-2:12px; --sp-3:16px; --sp-4:24px;

  --top-h:56px; --bot-h:132px; --left-w:320px; --right-w:360px;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{
  background:var(--bg); color:var(--ink);
  font-family:'PingFang SC','Microsoft YaHei',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
  font-size:var(--fs-3); line-height:1.5; -webkit-font-smoothing:antialiased;
  font-variant-numeric:tabular-nums;
}
button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}
.tnum{font-variant-numeric:tabular-nums}

/* ───────────────── A 顶栏:品牌 + 口径带(常驻)+ 动作 ───────────────── */
.app{display:grid;height:100vh;
  grid-template-columns:var(--left-w) 1fr var(--right-w);
  grid-template-rows:var(--top-h) 1fr var(--bot-h);
  gap:1px;background:var(--line);
}
.topbar{grid-column:1/-1;display:flex;align-items:center;gap:var(--sp-3);
  padding:0 var(--sp-3);background:#1B2450;color:#fff;overflow:hidden}
.brand{display:flex;align-items:center;gap:10px;flex:0 0 auto}
.brand__mark{width:24px;height:24px;border-radius:var(--r-ctl);background:#5C6FB4;
  display:grid;place-items:center;font-size:11px;font-weight:700;letter-spacing:.5px}
.brand__t{font-size:15px;font-weight:700;letter-spacing:.6px;white-space:nowrap}
.brand__s{font-size:10.5px;color:rgba(226,232,255,.6);letter-spacing:.8px;white-space:nowrap}

/* 口径带:任何时刻都看得见「我在看什么」 */
.ctx{flex:1 1 auto;display:flex;align-items:center;gap:6px;min-width:0;overflow:hidden}
.ctx__seg{display:inline-flex;align-items:baseline;gap:5px;padding:4px 10px;border-radius:var(--r-ctl);
  background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.16);white-space:nowrap}
.ctx__seg.is-on{background:rgba(255,255,255,.20);border-color:rgba(255,255,255,.34)}
.ctx__k{font-size:10.5px;color:rgba(226,232,255,.62)}
.ctx__v{font-size:12.5px;font-weight:600;color:#fff}
.ctx__x{font-size:10.5px;color:rgba(226,232,255,.62);margin-left:2px}
.ctx__clear{width:18px;height:18px;border-radius:50%;display:grid;place-items:center;
  background:rgba(255,255,255,.22);font-size:11px;line-height:1;margin-left:2px}
.ctx__clear:hover{background:#fff;color:#1B2450}

.acts{flex:0 0 auto;display:flex;align-items:center;gap:var(--sp-1)}
.abtn{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 11px;border-radius:var(--r-ctl);
  background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.18);
  color:rgba(232,237,255,.9);font-size:12px;white-space:nowrap}
.abtn:hover{background:rgba(255,255,255,.20);color:#fff}
.abtn.is-on{background:#fff;color:#1B2450;border-color:#fff;font-weight:600}

/* ───────────────── B 左栏:结论 + 主排行 ───────────────── */
.left{background:var(--surface);display:flex;flex-direction:column;min-height:0;overflow:hidden}
.sec{padding:var(--sp-3);border-bottom:1px solid var(--line-2)}
.sec:last-child{border-bottom:0}
.sec__t{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px}
.sec__h{font-size:var(--fs-3);font-weight:600;letter-spacing:.2px}
.sec__note{font-size:10.5px;color:var(--ink-3)}

/* 结论卡:首屏唯一的视觉焦点 */
.verdict__num{display:flex;align-items:baseline;gap:8px}
.verdict__num b{font-size:var(--fs-1);font-weight:700;line-height:1;letter-spacing:-.5px}
.verdict__num span{font-size:var(--fs-4);color:var(--ink-2)}
.verdict__delta{display:inline-flex;align-items:center;gap:4px;margin-left:auto;padding:2px 8px;
  border-radius:var(--r-pill);font-size:var(--fs-4);font-weight:600}
.verdict__delta.is-down{color:var(--ok);background:#E7F4EC}
.verdict__delta.is-up{color:var(--danger);background:#FDECEA}
/* 无基准:不许借涨跌的色。虚线边框 + 灰底,读起来就是「这里是空的」 */
.verdict__delta.is-na{color:var(--ink-3);background:transparent;
  border:1px dashed var(--line);font-weight:500}
.verdict__txt{margin-top:10px;font-size:12.5px;line-height:1.7;color:var(--ink-2)}
.verdict__txt b{color:var(--ink);font-weight:600}
.verdict__txt em{font-style:normal;color:var(--brand-ink);font-weight:600}

.kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;margin-top:var(--sp-2);
  background:var(--line-2);border:1px solid var(--line-2);border-radius:var(--r-ctl);overflow:hidden}
.kpi{background:var(--surface);padding:8px 9px}
.kpi__l{font-size:10.5px;color:var(--ink-3)}
.kpi__v{font-size:19px;font-weight:700;line-height:1.2;letter-spacing:-.3px}
.kpi__v i{font-style:normal;font-size:11px;font-weight:500;color:var(--ink-3);margin-left:2px}

/* 主排行 */
.sortbar{display:flex;gap:4px;margin-bottom:10px}
.sortbtn{padding:3px 9px;border-radius:var(--r-pill);font-size:11.5px;color:var(--ink-2);
  border:1px solid var(--line)}
.sortbtn:hover{border-color:var(--brand);color:var(--brand)}
.sortbtn.is-on{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:600}

.rank{display:flex;flex-direction:column;gap:2px}
.rank__row{display:grid;grid-template-columns:18px 1fr 40px;gap:8px;align-items:center;
  width:100%;padding:7px 8px;margin:0 -8px;border-radius:var(--r-ctl);text-align:left;
  transition:background .14s ease}
.rank__row:hover{background:var(--brand-wash)}
.rank__row.is-focus{background:var(--brand);color:#fff}
.rank__no{font-size:11px;color:var(--ink-3)}
.rank__row.is-focus .rank__no{color:rgba(255,255,255,.72)}
.rank__name{font-size:13px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.rank__val{font-size:13px;font-weight:700;text-align:right}
.rank__bar{grid-column:2/-1;height:4px;border-radius:2px;background:var(--line-2);
  overflow:hidden;display:flex;margin-top:-2px}
.rank__bar i{height:100%;display:block}
.rank__row.is-focus .rank__bar{background:rgba(255,255,255,.24)}

/* 成分条图例 */
.cmp{margin-top:var(--sp-2);display:flex;flex-direction:column;gap:5px}
.cmp__row{display:grid;grid-template-columns:52px 1fr auto;gap:8px;align-items:center;font-size:11px}
.cmp__n{color:var(--ink-2)}
.cmp__t{height:6px;border-radius:3px;background:var(--line-2);overflow:hidden}
.cmp__t i{height:100%;display:block;border-radius:3px}
.cmp__v{color:var(--ink-3);font-size:10.5px}

.formula{margin-top:10px;padding-top:9px;border-top:1px dashed var(--line);
  font-size:10.5px;line-height:1.6;color:var(--ink-3)}
.formula b{color:var(--ink-2);font-weight:600}

/* ───────────────── C 地图 ───────────────── */
.map{position:relative;background:#E8EAF0;overflow:hidden;min-height:0}
.map svg{position:absolute;inset:0;width:100%;height:100%;display:block}
.hud{position:absolute;z-index:3}
.hud--tl{left:var(--sp-2);top:var(--sp-2);display:flex;gap:4px;flex-wrap:wrap;max-width:calc(100% - 24px)}
.mchip{padding:5px 11px;border-radius:var(--r-pill);font-size:12px;color:var(--ink-2);
  background:rgba(255,255,255,.94);border:1px solid var(--line);box-shadow:var(--sh-1);white-space:nowrap}
.mchip:hover{border-color:var(--brand);color:var(--brand)}
.mchip.is-on{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:600}
.hud--tr{right:var(--sp-2);top:var(--sp-2);display:flex;gap:var(--sp-1);align-items:center}
.hud--bl{left:var(--sp-2);bottom:var(--sp-2)}
.hud--br{right:var(--sp-2);bottom:var(--sp-2);display:flex;gap:var(--sp-1)}
.gcard{background:rgba(255,255,255,.94);border:1px solid var(--line);border-radius:var(--r-ctl);
  box-shadow:var(--sh-1);padding:8px 11px}
.readout{display:flex;align-items:center;gap:var(--sp-2);font-size:12px;color:var(--ink-2)}
.readout b{font-size:14px;font-weight:700;color:var(--ink)}
.readout__sep{width:1px;height:12px;background:var(--line)}

.legend__t{font-size:10.5px;font-weight:600;color:var(--ink-2);margin-bottom:5px;letter-spacing:.3px}
.legend__ramp{display:flex;height:9px;border-radius:5px;overflow:hidden;width:172px}
.legend__ramp i{flex:1;display:block}
.legend__sc{display:flex;justify-content:space-between;width:172px;font-size:10px;color:var(--ink-3);margin-top:2px}
.legend__hint{font-size:10px;color:var(--ink-3);line-height:1.5;max-width:172px;margin-top:5px}

.mapbtn{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 12px;border-radius:var(--r-ctl);
  background:rgba(255,255,255,.94);border:1px solid var(--line);box-shadow:var(--sh-1);
  font-size:12px;color:var(--ink-2)}
.mapbtn:hover{border-color:var(--brand);color:var(--brand)}
.mapbtn.is-on{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:600}

/* 地图上的区名:白描边保证在任何底色上都可读 */
.dlabel{font-size:12px;font-weight:600;fill:var(--ink);stroke:#fff;stroke-width:3px;
  paint-order:stroke;pointer-events:none;text-anchor:middle}
.dlabel--sm{font-size:10.5px;font-weight:500}
.dlabel--on{fill:#fff;stroke:var(--brand-ink);stroke-width:3.5px}

/* ───────────────── D 右栏:归因 ───────────────── */
.right{background:var(--surface);display:flex;flex-direction:column;min-height:0;overflow-y:auto}
.focus{display:flex;align-items:center;gap:10px;padding:var(--sp-3);
  border-bottom:1px solid var(--line-2);position:sticky;top:0;background:var(--surface);z-index:2}
.focus__n{font-size:17px;font-weight:700;letter-spacing:.2px}
.focus__s{font-size:11px;color:var(--ink-3);margin-top:1px}
.focus__btn{margin-left:auto;flex:0 0 auto;padding:4px 10px;border-radius:var(--r-ctl);
  border:1px solid var(--link);color:var(--link);font-size:11.5px;font-weight:600;white-space:nowrap}
.focus__btn:hover{background:var(--link-wash)}
.focus__back{padding:4px 9px;border-radius:var(--r-ctl);border:1px solid var(--line);
  color:var(--ink-2);font-size:11.5px;white-space:nowrap}
.focus__back:hover{border-color:var(--brand);color:var(--brand)}

.hist{display:flex;align-items:baseline;gap:6px;margin-bottom:8px}
.hist__v{font-size:var(--fs-2);font-weight:700;line-height:1}
.hist__l{font-size:var(--fs-4);color:var(--ink-2)}
.hist__cmp{margin-left:auto;font-size:10.5px;color:var(--ink-3)}
.hist__cmp b{color:var(--ink-2);font-weight:600}

.chart{width:100%;display:block;overflow:visible}
.chart .grid{stroke:var(--line-2);stroke-width:1}
.chart .axis{fill:var(--ink-3);font-size:9.5px}
.chart .bar{fill:var(--brand-soft, #B8BDDC)}
.chart .bar.is-peak{fill:var(--brand)}
.chart .bar.is-sel{fill:var(--link)}
.chart .hit{fill:transparent;cursor:pointer}
.chart .hit:hover{fill:rgba(70,83,162,.08)}
.chart .area{fill:rgba(70,83,162,.10)}
.chart .line{fill:none;stroke:var(--brand);stroke-width:1.8;stroke-linejoin:round}
.chart .peakdot{fill:var(--danger)}

/* 车种构成:本批 vs 全市基准 */
.vc{display:flex;flex-direction:column;gap:7px}
.vc__row{display:grid;grid-template-columns:1fr 46px 46px;gap:6px;align-items:center;font-size:11.5px}
.vc__name{display:flex;align-items:center;gap:6px;min-width:0}
.vc__dot{width:8px;height:8px;border-radius:2px;flex:0 0 auto}
.vc__n{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink-2)}
.vc__v{text-align:right;font-weight:600}
.vc__b{text-align:right;color:var(--ink-3);font-size:11px}
.vc__d{text-align:right;font-weight:600;font-size:11px}
.vc__d.is-up{color:var(--danger)}
.vc__d.is-down{color:var(--link)}
.vc__d.is-flat{color:var(--ink-3);font-weight:500}
.vc__stack{grid-column:1/-1;height:8px;border-radius:4px;overflow:hidden;display:flex;background:var(--line-2)}
.vc__stack i{height:100%;display:block}
.vc__stack.is-base{opacity:.42;height:5px;border-radius:3px;margin-top:1px}
.vc__cap{grid-column:1/-1;display:grid;grid-template-columns:1fr 46px 46px;gap:6px;
  font-size:10px;color:var(--ink-3)}
.vc__cap span+span{text-align:right}

/* 夜间与时段 */
.night{display:flex;align-items:baseline;gap:10px;margin-bottom:9px}
.night__v{font-size:26px;font-weight:700;line-height:1}
.night__l{font-size:var(--fs-4);color:var(--ink-2)}
.night__c{margin-left:auto;font-size:10.5px;color:var(--ink-3)}
.bands{display:grid;grid-template-columns:repeat(6,1fr);gap:3px}
.band{text-align:center}
.band__t{height:34px;display:flex;align-items:flex-end;justify-content:center}
.band__f{width:100%;max-width:26px;background:#C6CCE4;border-radius:3px 3px 0 0;min-height:2px}
.band.is-peak .band__f{background:var(--brand)}
.band__n{font-size:10px;color:var(--ink);font-weight:600;margin-top:3px}
.band__l{font-size:9.5px;color:var(--ink-3);white-space:nowrap}

/* 反复出险点位 */
.place{display:flex;flex-direction:column;gap:2px}
.place__row{display:flex;align-items:baseline;gap:8px;width:100%;padding:6px 8px;margin:0 -8px;
  border-radius:var(--r-ctl);text-align:left;transition:background .14s ease}
.place__row:hover{background:var(--brand-wash)}
.place__row.is-focus{background:var(--brand);color:#fff}
.place__d{flex:0 0 auto;font-size:11px;font-weight:700;color:var(--brand);min-width:34px}
.place__row.is-focus .place__d{color:#fff}
.place__m{flex:1 1 auto;min-width:0}
.place__a{font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.place__s{font-size:10.5px;color:var(--ink-3);margin-top:1px}
.place__row.is-focus .place__s{color:rgba(255,255,255,.72)}
.place__last{flex:0 0 auto;text-align:right;font-size:10.5px;color:var(--ink-2)}
.place__row.is-focus .place__last{color:rgba(255,255,255,.85)}
.place__last em{display:block;font-style:normal;font-size:9.5px;color:var(--ink-3)}
.place__row.is-focus .place__last em{color:rgba(255,255,255,.6)}

/* ───────────────── E 底栏:30 天趋势 ───────────────── */
.bottom{grid-column:1/-1;background:var(--surface);display:flex;flex-direction:column;
  padding:10px var(--sp-3) 8px;min-height:0;overflow:hidden}
.bot__h{display:flex;align-items:center;gap:var(--sp-2);margin-bottom:6px}
.bot__t{font-size:var(--fs-3);font-weight:600}
.bot__sub{font-size:10.5px;color:var(--ink-3)}
.bot__seg{margin-left:auto;display:flex;gap:3px}
.segbtn{padding:3px 10px;border-radius:var(--r-pill);font-size:11.5px;color:var(--ink-2);border:1px solid var(--line)}
.segbtn:hover{border-color:var(--brand);color:var(--brand)}
.segbtn.is-on{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:600}
.bot__chart{flex:1 1 auto;min-height:0}
.trend{width:100%;height:100%;display:block;overflow:visible}
.trend .grid{stroke:var(--line-2);stroke-width:1}
.trend .axis{fill:var(--ink-3);font-size:9.5px}
.trend .area{fill:rgba(70,83,162,.10)}
.trend .line{fill:none;stroke:var(--brand);stroke-width:1.8;stroke-linejoin:round}
.trend .cursor{stroke:var(--link);stroke-width:1.5}
.trend .hit{fill:transparent;cursor:pointer}
.trend .hit:hover{fill:rgba(70,83,162,.07)}
.trend .peak{fill:var(--danger)}
.trend .peaklab{fill:var(--ink-2);font-size:10px;font-weight:600}

.empty{font-size:12px;color:var(--ink-3);text-align:center;padding:16px 0}
.hr{height:1px;background:var(--line-2);margin:0 -0px}
</style>
</head>
<body>
<div class="app">

  <!-- ══ A 顶栏 ══ -->
  <header class="topbar">
    <div class="brand">
      <div class="brand__mark">SZ</div>
      <div>
        <div class="brand__t">深圳市道路风险监测看板</div>
        <div class="brand__s">SHENZHEN ROAD RISK MONITOR</div>
      </div>
    </div>

    <!-- 口径带:BI 第一公理 —— 我在看什么,任何时刻可见 -->
    <div class="ctx" id="ctx"></div>

    <div class="acts">
      <button class="abtn" id="btnFull">全屏</button>
      <button class="abtn" id="btnImport">导入数据</button>
    </div>
  </header>

  <!-- ══ B 左栏 ══ -->
  <aside class="left">
    <div class="sec">
      <div class="sec__t"><div class="sec__h" id="verdictTitle">全市风险结论</div></div>
      <div id="verdict"></div>
    </div>
    <div class="sec" style="flex:1 1 auto;min-height:0;overflow-y:auto">
      <div class="sec__t">
        <div class="sec__h">区域风险排行</div>
        <div class="sec__note" id="rankNote"></div>
      </div>
      <div class="sortbar" id="sortbar"></div>
      <div class="rank" id="rank"></div>
    </div>
    <div class="sec" id="cmpSec">
      <div class="sec__t"><div class="sec__h">风险构成</div><div class="sec__note" id="cmpWho"></div></div>
      <div class="cmp" id="cmp"></div>
      <div class="formula" id="formula"></div>
    </div>
  </aside>

  <!-- ══ C 地图 ══ -->
  <main class="map" id="mapWrap">
    <svg id="map" viewBox="0 0 1000 760" preserveAspectRatio="xMidYMid meet"></svg>

    <div class="hud hud--tl" id="metricBar"></div>

    <div class="hud hud--tr">
      <div class="gcard readout">
        <span>命中 <b id="rMatched">—</b> 起</span>
        <span class="readout__sep"></span>
        <span>点位 <b id="rBuckets">—</b> 处</span>
        <span class="readout__sep"></span>
        <span>耗时 <b id="rMs">—</b></span>
      </div>
    </div>

    <div class="hud hud--bl">
      <div class="gcard" id="legend"></div>
    </div>

    <div class="hud hud--br">
      <button class="mapbtn" id="btnRecenter">回到全市</button>
      <button class="mapbtn" id="btnHot">重点风险点</button>
    </div>
  </main>

  <!-- ══ D 右栏 ══ -->
  <aside class="right">
    <div class="focus" id="focusHead"></div>
    <div class="sec">
      <div class="sec__t"><div class="sec__h">24 小时形态</div><div class="sec__note">点一格 = 只看该小时</div></div>
      <div id="hourBox"></div>
    </div>
    <div class="sec">
      <div class="sec__t"><div class="sec__h">车种构成</div><div class="sec__note">对比全市基准</div></div>
      <div class="vc" id="vcBox"></div>
    </div>
    <div class="sec">
      <div class="sec__t"><div class="sec__h">夜间与时段</div></div>
      <div id="nightBox"></div>
    </div>
    <div class="sec">
      <div class="sec__t"><div class="sec__h">反复出险点位</div><div class="sec__note">点一行 = 地图定位</div></div>
      <div class="place" id="placeBox"></div>
    </div>
  </aside>

  <!-- ══ E 底栏 ══ -->
  <section class="bottom">
    <div class="bot__h">
      <div class="bot__t">近 30 天趋势</div>
      <div class="bot__sub" id="trendSub"></div>
      <div class="bot__seg" id="winBar"></div>
    </div>
    <div class="bot__chart"><svg class="trend" id="trend" preserveAspectRatio="none"></svg></div>
  </section>
</div>

<script>
/* ============================================================================
 * 原型数据(结构与 StatsResult / RegionRiskScore 对齐,数值为示意)
 * 综合风险 = 0.3×密度 + 0.3×反复占比 + 0.2×车型聚集度 + 0.2×夜间占比  —— 与
 * src/features/heatmap/aggregate/aggregate.worker.ts:924 的权重一致
 * ========================================================================== */
const RAMP = ['#FFEFD0','#FFD08A','#FF9A4D','#E8590C','#B42318'];
const VC_CLASSES = ['小型客车','货车','摩托车','大型客车','特种车'];
const VC_BASE   = [0.62, 0.18, 0.09, 0.07, 0.04];
const VC_COLOR  = ['#4653A2','#0E7FB0','#7A8BB8','#B54708','#B42318'];
const BANDS = ['凌晨','清晨','上午','下午','傍晚','夜间']; // 每档 4 小时

/* 11 个行政区:多边形(1000×760 视图)、起数、四项成分、车种偏移、点位、30 天趋势 */
const RAW = [
  {n:'宝安区', p:[[60,320],[175,262],[305,235],[435,225],[448,340],[425,445],[300,478],[150,462],[62,395]],
   c:8940, rec:.38, hhi:.31, nit:.21, tilt:[.02,-.03,.05,-.01,-.03], nightT:.20,
   pl:[['宝安大道 · 新安五路口',31,86],['创业路 · 建安一路',24,63],['广深公路 · 西乡段',22,58],['松岗大道 · 塘下涌',18,44],['沙井中心路',15,37]]},
  {n:'龙岗区', p:[[590,68],[790,60],[815,190],[800,320],[700,395],[600,340],[585,230],[590,150]],
   c:8320, rec:.52, hhi:.28, nit:.29, tilt:[-.04,.06,.03,.01,-.06], nightT:.30,
   pl:[['龙岗大道 · 龙城广场',44,118],['布吉大道 · 布吉关口',38,95],['深惠路 · 坪地段',29,71],['坂雪岗大道',25,60],['平湖大街',21,52]]},
  {n:'福田区', p:[[350,490],[470,495],[480,570],[465,625],[355,620],[340,555]],
   c:5610, rec:.44, hhi:.35, nit:.24, tilt:[.05,-.04,-.02,.03,-.02], nightT:.22,
   pl:[['深南大道 · 车公庙',29,78],['华强北路',26,66],['福田口岸 · 落马洲',20,48],['彩田路 · 莲花山',17,41],['滨河大道 · 赤尾',15,36]]},
  {n:'南山区', p:[[165,470],[320,485],[345,560],[330,640],[240,660],[150,600]],
   c:4880, rec:.41, hhi:.33, nit:.22, tilt:[.06,-.02,-.03,.02,-.03], nightT:.20,
   pl:[['南海大道 · 蛇口',27,70],['科技园 · 科苑路',23,58],['前海路 · 桂湾',19,46],['沙河西路',16,39],['留仙大道',13,31]]},
  {n:'龙华区', p:[[470,60],[585,72],[600,175],[578,250],[465,240],[452,150]],
   c:4320, rec:.47, hhi:.26, nit:.26, tilt:[-.02,.05,.02,-.01,-.04], nightT:.27,
   pl:[['龙华大道 · 人民路',26,64],['观澜大道',22,53],['民治大道',19,45],['大浪南路',16,37],['和平东路',13,30]]},
  {n:'罗湖区', p:[[485,500],[590,510],[600,580],[585,630],[490,625],[480,560]],
   c:3190, rec:.51, hhi:.37, nit:.27, tilt:[.03,-.05,-.02,.05,-.01], nightT:.25,
   pl:[['深南东路 · 黄贝岭',24,58],['文锦渡口岸',20,47],['布心路',17,40],['东门中路',15,34],['笋岗东路',12,27]]},
  {n:'光明区', p:[[300,60],[445,55],[468,150],[440,220],[315,230],[288,145]],
   c:2760, rec:.33, hhi:.24, nit:.31, tilt:[-.03,.07,.01,-.02,-.03], nightT:.34,
   pl:[['光明大道 · 凤凰城',19,44],['公明广场',16,36],['松白路',13,30],['马田北路',11,25],['观光路',9,20]]},
  {n:'坪山区', p:[[805,195],[935,215],[950,330],[900,420],[790,400],[795,300]],
   c:1930, rec:.36, hhi:.29, nit:.33, tilt:[-.05,.08,.02,-.02,-.03], nightT:.36,
   pl:[['坪山大道 · 中心公园',16,37],['坑梓丹梓大道',13,29],['比亚迪路',11,24],['龙坪路',9,19],['江岭路',7,15]]},
  {n:'盐田区', p:[[605,520],[700,540],[710,610],[660,650],[600,630]],
   c:1240, rec:.29, hhi:.41, nit:.19, tilt:[.01,-.06,.06,.02,-.03], nightT:.17,
   pl:[['盐田港 · 进港路',14,31],['深盐路',11,24],['盐田路',9,18],['北山道',7,14],['海山路',5,11]]},
  {n:'大鹏新区', p:[[700,585],[800,600],[860,660],[830,730],[720,720],[690,650]],
   c:880, rec:.24, hhi:.38, nit:.35, tilt:[.02,-.02,-.04,.05,-.01], nightT:.38,
   pl:[['大鹏所城 · 鹏飞路',11,23],['南澳海滨路',9,18],['葵涌金葵路',7,13],['坝光新村',5,10],['杨梅坑',4,8]]},
  {n:'深汕合作区', p:[[940,40],[995,55],[990,140],[930,130]],
   c:736, rec:.18, hhi:.22, nit:.38, tilt:[-.04,.06,-.01,-.01,.00], nightT:.42,
   pl:[['鹅埠镇 · 深汕大道',9,17],['鲘门高铁站',7,12],['小漠港区',5,9],['赤石镇',4,7],['圆墩村',3,5]]},
];

/* 确定性伪随机(保证每次刷新同一份数) */
function rnd(seed){ let s = seed >>> 0; return () => (s = (s*1664525+1013904223)>>>0) / 4294967296; }

/* 24 小时形态:早高峰 8-9、晚高峰 17-19、夜间底噪由 nit 决定 */
function hourHist(nit, seed){
  const r = rnd(seed), a = new Array(24).fill(0);
  const shape = [.9,.6,.4,.3,.35,.7,1.8,3.6,5.2,3.9,3.2,3.4,3.6,3.3,3.5,4.1,5.4,6.3,5.1,3.6,2.6,2.0,1.5,1.2];
  for(let h=0;h<24;h++){
    const night = (h>=22 || h<=5) ? 1 : 0;
    a[h] = shape[h] * (1 + (r()-.5)*.22) * (night ? 1 + nit*2.6 : 1);
  }
  const s = a.reduce((x,y)=>x+y,0);
  return a.map(v=>v/s);
}

/* 30 天逐日:周末抬升 + 缓慢下行趋势(月末比月初低) + 噪声 */
function trend(base, seed){
  const r = rnd(seed), out = [];
  for(let d=0; d<30; d++){
    const wd = (d + 3) % 7;                 // 0=周日
    const wk = (wd===0||wd===6) ? 1.18 : 1;
    const drift = 1 - d * 0.0022;           // 30 天累计 -6.4%
    out.push(base * wk * drift * (1 + (r()-.5)*.16) / 30);
  }
  return out;
}

/* 建区模型 */
const DISTRICTS = RAW.map((d, i) => {
  const vcShare = VC_BASE.map((b, k) => Math.max(0.008, b + (d.tilt[k] ?? 0)));
  const s = vcShare.reduce((a,b)=>a+b,0);
  return {
    ...d, idx:i,
    hour: hourHist(d.nit, 1000+i*7),
    vc: vcShare.map(v=>v/s),
    days: trend(d.c, 2000+i*13),
  };
});
const TOTAL_FULL = DISTRICTS.reduce((a,d)=>a+d.c, 0);   // 42,806
const CITY_HOUR = (()=>{ const a=new Array(24).fill(0);
  DISTRICTS.forEach(d=>d.hour.forEach((v,h)=>a[h]+=v*d.c));
  const s=a.reduce((x,y)=>x+y,0); return a.map(v=>v/s); })();
const CITY_DAYS = (()=>{ const a=new Array(30).fill(0);
  DISTRICTS.forEach(d=>d.days.forEach((v,i)=>a[i]+=v)); return a; })();
const CITY_VC = (()=>{ const a=new Array(VC_CLASSES.length).fill(0);
  DISTRICTS.forEach(d=>d.vc.forEach((v,k)=>a[k]+=v*d.c));
  const s=a.reduce((x,y)=>x+y,0); return a.map(v=>v/s); })();

/* 重点风险点(黑点)示意:位置取自各区点位榜首 */
const HOTSPOTS = [
  {x:640,y:150,r:52,rank:1,cnt:412,d:1,name:'龙岗大道 · 龙城广场'},
  {x:250,y:330,r:44,rank:2,cnt:337,d:0,name:'宝安大道 · 新安五路口'},
  {x:400,y:530,r:38,rank:3,cnt:268,d:2,name:'深南大道 · 车公庙'},
  {x:230,y:520,r:34,rank:4,cnt:231,d:3,name:'南海大道 · 蛇口'},
  {x:520,y:150,r:30,rank:5,cnt:196,d:4,name:'龙华大道 · 人民路'},
];

/* ── 状态:三个量决定全屏(focus + filter + metric) ── */
const S = {
  metric: 'density',                 // 地图着色度量
  focus: { kind:'city' },            // 焦点:city / district / place(hotspot 为预留态,本原型未产出该焦点)
  win: 30,                           // 时间窗天数(近 N 日)
  hours: null,                       // 小时筛选(null = 全天)
  dayCursor: null,                   // 趋势游标
  hotOn: true,                       // 重点风险点层
  sort: 'score',                     // 主排行口径
  hover: null,
};

const METRICS = [
  {id:'density', label:'案件密度', type:'heat',  hint:'屏幕方格内的案件数,随缩放变化'},
  {id:'score',   label:'综合风险', type:'choro', hint:'0–100 分,颜色越深风险越高'},
  {id:'night',   label:'夜间占比', type:'choro', hint:'22–05 点案件占本区比'},
  {id:'recur',   label:'反复出险', type:'choro', hint:'落在「同格≥2天」方格的案件占本区比'},
];
const SORTS = [
  {id:'score', label:'综合风险'}, {id:'count', label:'案件数'},
  {id:'recur', label:'反复出险'}, {id:'night', label:'夜间占比'},
];

/* ============================================================================
 * 计算层:由 S 派生全屏视图模型(单一口径,任何一处改动都走这里)
 * ========================================================================== */
function hourShare(sel){
  if(!sel || !sel.length) return 1;
  return sel.reduce((a,h)=>a + CITY_HOUR[h], 0);
}
function view(){
  const from = 30 - S.win;
  const winDays = [];
  for(let d=from; d<30; d++) winDays.push(d);
  const hs = hourShare(S.hours);

  const rows = DISTRICTS.map(d=>{
    let count = d.days.reduce((a,_,i)=> winDays.includes(i) ? a + d.days[i] : a, 0) * hs;
    count = Math.round(count);
    return { d, count, hour:d.hour, vc:d.vc, rec:d.rec, hhi:d.hhi, nit:d.nit };
  });
  const total = rows.reduce((a,r)=>a+r.count,0);
  const maxCount = Math.max(1, ...rows.map(r=>r.count));

  // 综合风险:与 worker 同一把尺(密度按最大区归一)
  rows.forEach(r=>{
    r.density = r.count / maxCount;
    r.score = Math.round((0.3*r.density + 0.3*r.rec + 0.2*r.hhi + 0.2*r.nit) * 100);
  });

  // 全市聚合(口径与区一致,便于对照)
  const city = {
    count: total,
    hour: mixHour(rows), vc: mixVc(rows),
    rec: weight(rows, r=>r.rec), nit: weight(rows, r=>r.nit), hhi: weight(rows, r=>r.hhi),
    score: Math.round((0.3*1 + 0.3*weight(rows,r=>r.rec) + 0.2*weight(rows,r=>r.hhi) + 0.2*weight(rows,r=>r.nit))*100),
  };

  /* 环比:近 N 天 vs 前 N 天。
   *
   * 铁律:**没有前一个窗口,就不给环比**。
   * 数据总共只有 30 天,S.win=30 时 prevTo=0,前窗口是个空集 —— 此时任何"下降 6.4%"
   * 都是编的。原版在这里硬塞了一个 -0.064 兜底,结果首屏最醒目的那个数字是假数,
   * 这类东西一旦被追问一次,整块板子就不可信了。所以 delta 允许为 null,
   * 由渲染层明说"无对比基准",并指出去哪儿才能看到(缩短时间窗到 14 / 7 天)。
   */
  const prevFrom = Math.max(0, 30 - S.win*2), prevTo = 30 - S.win;
  let cur = 0, prev = 0;
  for(let i=0;i<30;i++){ const v = CITY_DAYS[i]*hs; if(i>=30-S.win) cur += v; else if(i>=prevFrom && i<prevTo) prev += v; }
  const delta = prev > 0 ? (cur-prev)/prev : null;

  // 各区环比:与全市同一把尺 —— 焦点切换后结论卡才能跟着换口径。
  // 区一级更容易凑不出基准(小区在 7 天窗口里可能前一天一起都没有),同样给 null。
  rows.forEach(r=>{
    let c=0, p=0;
    for(let i=0;i<30;i++){
      const x = r.d.days[i]*hs;
      if(i>=30-S.win) c+=x; else if(i>=prevFrom && i<prevTo) p+=x;
    }
    r.cur=c; r.prev=p; r.delta = p>0 ? (c-p)/p : null;
  });

  // 趋势曲线(焦点跟随)
  const series = S.focus.kind==='district'
    ? rows[S.focus.idx].d.days.map(v=>v*hs)
    : CITY_DAYS.map(v=>v*hs);

  const sorted = [...rows].sort((a,b)=> S.sort==='count' ? b.count-a.count
    : S.sort==='recur' ? b.rec-a.rec : S.sort==='night' ? b.nit-a.nit : b.score-a.score);

  return { rows, total, maxCount, city, cur, prev, delta, series, sorted, winDays, from };
}
function mixHour(rows){ const a=new Array(24).fill(0);
  rows.forEach(r=>r.hour.forEach((v,h)=>a[h]+=v*r.count));
  const s=a.reduce((x,y)=>x+y,0)||1; return a.map(v=>v/s); }
function mixVc(rows){ const a=new Array(VC_CLASSES.length).fill(0);
  rows.forEach(r=>r.vc.forEach((v,k)=>a[k]+=v*r.count));
  const s=a.reduce((x,y)=>x+y,0)||1; return a.map(v=>v/s); }
function weight(rows, f){ const t=rows.reduce((a,r)=>a+r.count,0)||1;
  return rows.reduce((a,r)=>a+f(r)*r.count,0)/t; }

const V = () => view();
const fmt = n => Math.round(n).toLocaleString('zh-CN');
const pct = (n, d=1) => (n*100).toFixed(d) + '%';
const rampAt = t => RAMP[Math.min(4, Math.max(0, Math.floor(t*5)))];
function heatColor(v, max){ return rampAt(Math.pow(v/max, .62)); }

/* ============================================================================
 * 渲染
 * ========================================================================== */
function render(){ const v = V(); renderCtx(v); renderVerdict(v); renderRank(v);
  renderCmp(v); renderMap(v); renderFocus(v); renderHour(v); renderVc(v);
  renderNight(v); renderPlace(v); renderTrend(v); }

/* —— A 口径带 —— */
function renderCtx(v){
  const el = document.getElementById('ctx');
  const ds = v.winDays;
  const dayLab = (()=>{ const s=ds[0], e=ds[ds.length-1];
    return `10-${String(s+1).padStart(2,'0')} 至 10-${String(e+1).padStart(2,'0')}`; })();
  const segs = [];
  segs.push(seg('时间', `近 ${S.win} 天`, dayLab));
  segs.push(seg('区域', S.focus.kind==='district' ? DISTRICTS[S.focus.idx].n : '全市', null));
  const hl = S.hours && S.hours.length
    ? (S.hours.length===1 ? `${S.hours[0]} 时` : `${S.hours.length} 个时段`)
    : null;
  segs.push(seg('时段', hl || '全天', null));
  const hit = v.total, all = TOTAL_FULL;
  segs.push(seg('命中', fmt(hit), hit<all ? `占全量 ${pct(hit/all)}` : '全量'));
  el.innerHTML = segs.join('');
  el.querySelectorAll('[data-clear]').forEach(b=>{
    b.onclick = () => { const k=b.dataset.clear;
      if(k==='time'){ S.win=30; }
      if(k==='region'){ S.focus={kind:'city'}; }
      if(k==='hour'){ S.hours=null; }
      render(); };
  });
  function seg(k, val, extra){
    const on = (k==='时间'&&S.win!==30)||(k==='区域'&&S.focus.kind!=='city')||(k==='时段'&&S.hours);
    const cl = (k==='时间'&&S.win!==30)||(k==='区域'&&S.focus.kind!=='city')||(k==='时段'&&S.hours)
      ? `<i class="ctx__clear" data-clear="${k==='时间'?'time':k==='区域'?'region':'hour'}">×</i>` : '';
    return `<span class="ctx__seg${on?' is-on':''}"><span class="ctx__k">${k}</span><span class="ctx__v">${val}</span>${extra?`<span class="ctx__x">${extra}</span>`:''}${cl}</span>`;
  }
}

/* —— B 结论卡 —— */
function renderVerdict(v){
  const isP = S.focus.kind==='place';
  const isD = S.focus.kind==='district' || isP;   // 点位归属于所在区,结论口径跟随该区
  const top = v.sorted[0];
  const cityRec = v.city.rec, cityNit = v.city.nit;
  const r = isD ? v.rows[S.focus.idx] : null;

  const scope = isD ? DISTRICTS[S.focus.idx].n : '全市';
  const num   = isD ? r.count : v.total;
  const dlt   = isD ? r.delta : v.delta;
  const rec   = isD ? r.rec   : v.city.rec;
  const nit   = isD ? r.nit   : v.city.nit;
  /* 有没有可比的前窗口,是这一整块读数成不成立的前提。dlt === null 表示凑不出来。 */
  const hasBase = dlt !== null && Number.isFinite(dlt);
  const up    = hasBase && dlt >= 0;
  const heavy = v.rows.filter(x=>x.score>=50).length;
  const rankNo = isD ? v.sorted.findIndex(x=>x.d.idx===S.focus.idx)+1 : 0;
  const share  = isD ? r.count/Math.max(1, v.total) : 1;

  document.getElementById('verdictTitle').textContent =
    isP ? `${scope} · 点位结论` : isD ? `${scope} · 风险结论` : '全市风险结论';

  /* 没基准时的替代句:不解释成"持平",也不留空 —— 空着会被读成 0%。
     一句话说清三件事:为什么没有、这个数在哪儿还能看见、怎么才能看到环比。

     但「为什么没有」有两种,不能共用一句话:
       (a) 窗口把 30 天占满 —— 前一个窗口压根不存在,这是数据长度决定的,
           解法是缩短窗口(去看 14 / 7 天);
       (b) 前窗口里零起(只有区级可能遇到,小区在 7 天窗口里前一段可能一起都没有)——
           窗口是有的,是分母为 0,缩短窗口反而更容易碰上,解法是看绝对数。
     用 (a) 的说法去解释 (b),等于把人指向一个解决不了问题的开关。 */
  const noWindow = 30 - S.win*2 <= 0;   // prevTo = 30-S.win,<=0 即前窗口不存在(UI 只有 7/14/30,故等价于 win===30)
  const naWhy = noWindow
    ? `当前只有 <b>30</b> 天数据,选中的 ${S.win} 天窗口占了全部,凑不出「前 ${S.win} 天」做比较`
    : `前 ${S.win} 天${isD?'本区':'全市'}零起,分母是 <b>0</b>,算不出增减比例`;
  const naHint = noWindow
    ? `把底部时间窗切到 <b>近 14 天</b> 或 <b>近 7 天</b> 即可看到环比。`
    : `这一项看绝对起数即可,不必追比例。`;
  const naTitle = noWindow
    ? `${S.win} 天窗口已占满全部 30 天数据,没有前一个窗口可比`
    : `前 ${S.win} 天零起,无法计算比例`;
  const noBase = `${naWhy} —— 本卡不给环比。${naHint}`;

  const txt = isD
    ? (hasBase
        ? `本区较前 ${S.win} 天${up?'上升':'下降'} <b>${pct(Math.abs(dlt))}</b>,`
        : `${noBase}`)
      + `占全市 <b>${pct(share)}</b>、风险排名 <b>第 ${rankNo}</b>;`
      + `反复出险 <b>${pct(rec)}</b>${rec>cityRec?'高于':'低于'}全市 <b>${pct(cityRec)}</b>、`
      + `夜间 <b>${pct(nit)}</b>${nit>cityNit?'高于':'低于'}全市 <b>${pct(cityNit)}</b>。`
      + `综合风险 <b>${r.score}</b> 分${isP?`;当前点位 <em>${DISTRICTS[S.focus.idx].pl[S.focus.p][0]}</em>`:''}`
      + `,全市 <b>${heavy}</b> 个区超 50 分。`
    : (hasBase
        ? `较前 ${S.win} 天${up?'上升':'下降'} <b>${pct(Math.abs(dlt))}</b>;`
        : `${noBase}`)
      + `风险最集中的是 <em>${top.d.n}(综合风险 ${top.score} 分)</em>,`
      + `其反复出险占比 <b>${pct(top.rec)}</b>${top.rec>cityRec?'高于':'低于'}全市 <b>${pct(cityRec)}</b>、`
      + `夜间占比 <b>${pct(top.nit)}</b>${top.nit>cityNit?'高于':'低于'}全市 <b>${pct(cityNit)}</b>。`
      + `全市共 <b>${heavy}</b> 个区综合风险超过 50 分。`;

  document.getElementById('verdict').innerHTML = `
    <div class="verdict__num">
      <b>${fmt(num)}</b><span>起出险</span>
      ${hasBase
        ? `<span class="verdict__delta ${up?'is-up':'is-down'}" title="与前 ${S.win} 天相比">${up?'▲':'▼'} ${pct(Math.abs(dlt))}</span>`
        : `<span class="verdict__delta is-na" title="${naTitle}">无对比基准</span>`}
    </div>
    <div class="verdict__txt">${txt}</div>
    <div class="kpis">
      <div class="kpi"><div class="kpi__l">日均</div><div class="kpi__v">${fmt(num/S.win)}<i>起</i></div></div>
      <div class="kpi"><div class="kpi__l">夜间占比</div><div class="kpi__v">${pct(nit,0)}</div></div>
      <div class="kpi"><div class="kpi__l">反复出险</div><div class="kpi__v">${pct(rec,0)}</div></div>
    </div>`;
}

/* —— B 主排行 —— */
function renderRank(v){
  document.getElementById('sortbar').innerHTML = SORTS.map(s=>
    `<button class="sortbtn${S.sort===s.id?' is-on':''}" data-sort="${s.id}">${s.label}</button>`).join('');
  document.querySelectorAll('[data-sort]').forEach(b=>b.onclick=()=>{S.sort=b.dataset.sort;render();});

  const note = {score:'按综合风险指数(0–100)',count:'按案件起数',recur:'按反复出险占比',night:'按夜间占比'}[S.sort];
  document.getElementById('rankNote').textContent = note;

  const max = Math.max(...v.sorted.map(r=>({score:r.score,count:r.count,recur:r.rec,night:r.nit})[S.sort]));
  document.getElementById('rank').innerHTML = v.sorted.map((r,i)=>{
    const key = {score:r.score,count:r.count,recur:r.rec,night:r.nit}[S.sort];
    const val = S.sort==='count' ? fmt(r.count) : S.sort==='score' ? r.score : pct(key,0);
    const isF = S.focus.kind==='district' && S.focus.idx===r.d.idx;
    const w = max>0 ? Math.max(4, key/max*100) : 0;
    return `<button class="rank__row${isF?' is-focus':''}" data-d="${r.d.idx}">
      <span class="rank__no">${i+1}</span>
      <span class="rank__name">${r.d.n}</span>
      <span class="rank__val">${val}</span>
      <span class="rank__bar"><i style="width:${w}%;background:${isF?'#fff':'var(--brand)'}"></i></span>
    </button>`;
  }).join('');
  document.querySelectorAll('[data-d]').forEach(b=>{
    const idx = +b.dataset.d;
    b.onclick = ()=>{ S.focus = {kind:'district', idx}; render(); };
    b.onmouseenter = ()=>{ S.hover = idx; paintMap(V()); };
    b.onmouseleave = ()=>{ S.hover = null; paintMap(V()); };
  });
}

/* —— B 风险构成(焦点跟随) —— */
function renderCmp(v){
  const isD = S.focus.kind==='district';
  const r = isD ? v.rows[S.focus.idx] : null;
  const g = r ? {density:r.density, rec:r.rec, hhi:r.hhi, nit:r.nit} : {density:1, rec:v.city.rec, hhi:v.city.hhi, nit:v.city.nit};
  document.getElementById('cmpWho').textContent = isD ? DISTRICTS[S.focus.idx].n : '全市';
  const items = [
    ['密度',     g.density, 'var(--brand)',   pct(g.density,0)],
    ['反复出险', g.rec,     '#0E7FB0',        pct(g.rec,0)],
    ['车型聚集', g.hhi,     '#B54708',        pct(g.hhi,0)],
    ['夜间',     g.nit,     '#4653A2',        pct(g.nit,0)],
  ];
  document.getElementById('cmp').innerHTML = items.map(([n,val,c,t])=>
    `<div class="cmp__row"><span class="cmp__n">${n}</span>
      <span class="cmp__t"><i style="width:${Math.max(2,val*100)}%;background:${c}"></i></span>
      <span class="cmp__v">${t}</span></div>`).join('');
  document.getElementById('formula').innerHTML =
    `综合风险 = <b>0.3×密度</b> + <b>0.3×反复出险</b> + <b>0.2×车型聚集</b> + <b>0.2×夜间</b>,满分 100。
     密度按当前窗口内案件最多的区归一;车型聚集为该区车种大类的 HHI。`;
}

/* —— C 地图 —— */
const svg = document.getElementById('map');
const NS = 'http://www.w3.org/2000/svg';
function el(tag, attrs, parent){ const e=document.createElementNS(NS,tag);
  for(const k in attrs) e.setAttribute(k, attrs[k]); if(parent) parent.appendChild(e); return e; }

document.getElementById('metricBar').innerHTML = METRICS.map(m=>
  `<button class="mchip${S.metric===m.id?' is-on':''}" data-m="${m.id}">${m.label}</button>`).join('');
document.querySelectorAll('[data-m]').forEach(b=>b.onclick=()=>{S.metric=b.dataset.m;render();});

function polyPoints(p){ return p.map(([x,y])=>`${x},${y}`).join(' '); }
function centroid(p){ let x=0,y=0; p.forEach(([a,b])=>{x+=a;y+=b;}); return [x/p.length, y/p.length]; }

function buildMap(){
  svg.innerHTML = '';
  const defs = el('defs',{},svg);
  const clip = el('clipPath',{id:'landClip'},defs);
  DISTRICTS.forEach(d=> el('polygon',{points:polyPoints(d.p)},clip));
  el('g',{id:'gBase'},svg); el('g',{id:'gHeat'},svg);
  el('g',{id:'gChoro'},svg); el('g',{id:'gHot'},svg); el('g',{id:'gLabel'},svg);
}

/* 热力栅格:格子值来自若干「种子」,种子密度按各区起数分配 */
let CELLS = null;
function buildCells(){
  if(CELLS) return CELLS;
  const seeds = [];
  const r = rnd(777);
  DISTRICTS.forEach((d,i)=>{
    const [cx,cy] = centroid(d.p);
    const k = Math.max(2, Math.round(d.c/1400));
    for(let j=0;j<k;j++){
      const a = r()*Math.PI*2, rad = r()*70;
      seeds.push({x:cx+Math.cos(a)*rad, y:cy+Math.sin(a)*rad*.8, w:d.c/42000*(0.6+r()*0.8)});
    }
  });
  const S_ = 46, cells = [];
  for(let y=40; y<745; y+=26){
    for(let x=45; x<970; x+=26){
      let v = 0;
      for(const s of seeds){ const dx=x-s.x, dy=y-s.y; v += s.w*Math.exp(-(dx*dx+dy*dy)/(2*S_*S_)); }
      if(v>0.035) cells.push({x,y,v});
    }
  }
  const vals = cells.map(c=>c.v).sort((a,b)=>a-b);
  const q = t => vals[Math.floor(vals.length*t)] || 1;
  const hi = q(0.985);
  CELLS = cells.map(c=>({...c, t:Math.min(1, c.v/hi)}));
  return CELLS;
}

function paintMap(v){
  const m = METRICS.find(x=>x.id===S.metric);
  const gB=svg.querySelector('#gBase'), gH=svg.querySelector('#gHeat'),
        gC=svg.querySelector('#gChoro'), gP=svg.querySelector('#gHot'), gL=svg.querySelector('#gLabel');
  [gB,gH,gC,gP,gL].forEach(g=>g.innerHTML='');
  const clip = 'url(#landClip)';
  const focusIdx = S.focus.kind==='district' ? S.focus.idx : null;

  // 底:陆地
  DISTRICTS.forEach(d=>{
    const isF = focusIdx===d.idx, dim = focusIdx!==null && !isF;
    el('polygon',{points:polyPoints(d.p), fill:'#FDFDFE', stroke:'#C9CFDD','stroke-width':1},gB);
  });

  if(m.type==='heat'){
    const wrap = el('g',{'clip-path':clip},gH);
    const cells = buildCells();
    cells.forEach(c=>{
      const fill = heatColor(c.t, 1);
      const op = focusIdx!==null ? (c.t>0.5?0.62:0.42) : 0.78;
      el('rect',{x:c.x-13,y:c.y-13,width:26,height:26,rx:7,fill,opacity:op},wrap);
    });
  }else{
    DISTRICTS.forEach(d=>{
      const r = v.rows[d.idx];
      const val = m.id==='score' ? r.score/100 : m.id==='night' ? r.nit : r.rec;
      const norm = m.id==='score' ? val : Math.min(1, val/0.55);
      el('polygon',{points:polyPoints(d.p), fill:heatColor(norm,1),
        opacity: focusIdx!==null && focusIdx!==d.idx ? .34 : .92,
        stroke: focusIdx===d.idx ? '#33407F' : 'rgba(255,255,255,.7)',
        'stroke-width': focusIdx===d.idx ? 2.5 : 1},gC);
    });
  }

  // 焦点区:外沿高亮
  if(focusIdx!==null){
    el('polygon',{points:polyPoints(DISTRICTS[focusIdx].p), fill:'none',
      stroke:'#33407F','stroke-width':2.5},gP);
  }else if(S.hover!==null){
    el('polygon',{points:polyPoints(DISTRICTS[S.hover].p), fill:'none',
      stroke:'#33407F','stroke-width':2,'stroke-dasharray':'6 4','opacity':.75},gP);
  }

  // 重点风险点
  if(S.hotOn){
    HOTSPOTS.forEach(h=>{
      const dim = focusIdx!==null && focusIdx!==h.d;
      const g = el('g',{opacity: dim?.34:1, style:'cursor:pointer'},gP);
      el('circle',{cx:h.x,cy:h.y,r:h.r,fill:'#B42318','fill-opacity':.12,
        stroke:'#B42318','stroke-width':1.4,'stroke-dasharray':'4 3'},g);
      el('circle',{cx:h.x,cy:h.y,r:12,fill:'#B42318'},g);
      const t=el('text',{x:h.x,y:h.y+4,'text-anchor':'middle',fill:'#fff',
        'font-size':11,'font-weight':700},g); t.textContent = h.rank;
      g.onclick = ()=>{ S.focus={kind:'district', idx:h.d}; render(); };
    });
  }

  // 区名(白描边保证任何底色可读)
  DISTRICTS.forEach(d=>{
    const [cx,cy] = centroid(d.p);
    const small = d.n==='深汕合作区' || d.n==='大鹏新区' || d.n==='盐田区';
    const t = el('text',{x:cx,y:cy+4,class:'dlabel'+(small?' dlabel--sm':'')+
      (focusIdx===d.idx?' dlabel--on':'')},gL);
    t.textContent = d.n.replace('合作区','');
    const t2 = el('text',{x:cx,y:cy+18,'text-anchor':'middle','font-size':10,'font-weight':600,
      fill: focusIdx===d.idx ? 'rgba(255,255,255,.9)' : '#4A5268',
      stroke:'#fff','stroke-width':2.6,'paint-order':'stroke'},gL);
    t2.textContent = fmt(v.rows[d.idx].count) + ' 起';
  });

  // 图例
  const lg = document.getElementById('legend');
  if(m.type==='heat'){
    lg.innerHTML = `<div class="legend__t">${m.label}</div>
      <div class="legend__ramp">${RAMP.map(c=>`<i style="background:${c}"></i>`).join('')}</div>
      <div class="legend__sc"><span>低</span><span>高</span></div>
      <div class="legend__hint">${m.hint};方格约 26 像素,随缩放变化。</div>`;
  }else{
    lg.innerHTML = `<div class="legend__t">${m.label}</div>
      <div class="legend__ramp">${RAMP.map(c=>`<i style="background:${c}"></i>`).join('')}</div>
      <div class="legend__sc"><span>低</span><span>高</span></div>
      <div class="legend__hint">${m.hint};按行政区边界分级着色。</div>`;
  }
}

function renderMap(v){
  document.querySelectorAll('[data-m]').forEach(b=>b.classList.toggle('is-on', b.dataset.m===S.metric));
  document.getElementById('rMatched').textContent = fmt(v.total);
  document.getElementById('rBuckets').textContent = fmt(380 + Math.round(v.total/140));
  document.getElementById('rMs').textContent = (28 + Math.round(v.total/9000)) + 'ms';
  document.getElementById('btnHot').classList.toggle('is-on', S.hotOn);
  paintMap(v);
}

/* —— D 焦点头 —— */
function renderFocus(v){
  const isD = S.focus.kind==='district';
  const name = isD ? DISTRICTS[S.focus.idx].n : '全市';
  const count = isD ? v.rows[S.focus.idx].count : v.total;
  const score = isD ? v.rows[S.focus.idx].score : Math.round(
    (0.3*1+0.3*v.city.rec+0.2*v.city.hhi+0.2*v.city.nit)*100);
  document.getElementById('focusHead').innerHTML = isD
    ? `<div><div class="focus__n">${name}</div>
         <div class="focus__s">${fmt(count)} 起 · 综合风险 ${score} 分 · 占全市 ${pct(count/Math.max(1,v.total))}</div></div>
       <button class="focus__btn" id="fMap">在地图上看</button>
       <button class="focus__back" id="fBack">回全市</button>`
    : `<div><div class="focus__n">全市</div>
         <div class="focus__s">${fmt(count)} 起 · 综合风险 ${score} 分 · ${DISTRICTS.length} 个区</div></div>
       <button class="focus__btn" id="fMap" style="visibility:hidden">—</button>`;
  const b1=document.getElementById('fMap'), b2=document.getElementById('fBack');
  if(b1) b1.onclick = ()=>{ S.metric='score'; if(!isD) S.focus={kind:'district',idx:v.sorted[0].d.idx}; render(); };
  if(b2) b2.onclick = ()=>{ S.focus={kind:'city'}; render(); };
}

/* —— D 24 小时形态 —— */
function renderHour(v){
  const isD = S.focus.kind==='district';
  const hist = isD ? v.rows[S.focus.idx].hour : v.city.hour;
  const cnt  = isD ? v.rows[S.focus.idx].count : v.total;
  const peak = hist.indexOf(Math.max(...hist));
  const sel = S.hours || [];
  const cur = sel.length ? sel.reduce((a,h)=>a+hist[h],0) : null;

  const W=328, H=96, pad=16, bh=(W-pad)/24;
  const max = Math.max(...hist);
  const bars = hist.map((v2,h)=>{
    const hh = Math.max(2, v2/max*(H-24));
    const on = sel.includes(h);
    return `<rect x="${pad+h*bh+1}" y="${H-18-hh}" width="${bh-2}" height="${hh}" rx="2"
      class="bar${h===peak?' is-peak':''}${on?' is-sel':''}"/>
      <rect x="${pad+h*bh}" y="0" width="${bh}" height="${H-14}" class="hit" data-h="${h}"/>`;
  }).join('');
  const labs = [0,4,8,12,16,20].map(h=>
    `<text x="${pad+h*bh+bh/2}" y="${H-4}" class="axis" text-anchor="middle">${h}</text>`).join('');

  document.getElementById('hourBox').innerHTML = `
    <div class="hist">
      <span class="hist__v">${String(peak).padStart(2,'0')}:00</span>
      <span class="hist__l">为峰值时段</span>
      <span class="hist__cmp">该时段 <b>${fmt((hist[peak]*(cnt||1)))}</b> 起 · 占 <b>${pct(hist[peak])}</b></span>
    </div>
    <svg class="chart" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" style="height:${H}px">
      ${bars}${labs}
    </svg>
    ${cur!==null ? `<div class="sec__note" style="margin-top:6px">已选 ${sel.length} 个时段 · 占本范围 <b>${pct(cur)}</b> · <button style="color:var(--link);text-decoration:underline" id="hClr">清除</button></div>` : ''}`;

  document.querySelectorAll('[data-h]').forEach(b=>b.onclick=()=>{
    const h=+b.dataset.h;
    S.hours = (S.hours && S.hours.includes(h)) ? S.hours.filter(x=>x!==h) : [...(S.hours||[]), h];
    if(S.hours && S.hours.length===0) S.hours=null;
    render();
  });
  const c=document.getElementById('hClr'); if(c) c.onclick=()=>{S.hours=null;render();};
}

/* —— D 车种构成 —— */
function renderVc(v){
  const isD = S.focus.kind==='district';
  const cur = isD ? v.rows[S.focus.idx].vc : v.city.vc;
  const base = VC_BASE;
  const rows = VC_CLASSES.map((n,k)=>({n, v:cur[k], b:base[k], d:cur[k]-base[k], c:VC_COLOR[k]}))
    .sort((a,b)=>b.v-a.v);
  const stack = (arr)=>arr.map(r=>`<i style="width:${r*100}%;background:${r.c}"></i>`).join('');
  const ordered = rows.map(r=>({...r, c:VC_COLOR[VC_CLASSES.indexOf(r.n)]}));
  document.getElementById('vcBox').innerHTML = `
    <div class="vc__cap" style="grid-column:1/-1"><span>本范围构成</span><span></span><span></span></div>
    <div class="vc__stack">${ordered.map(r=>`<i style="width:${r.v*100}%;background:${VC_COLOR[VC_CLASSES.indexOf(r.n)]}"></i>`).join('')}</div>
    <div class="vc__cap" style="grid-column:1/-1"><span>全市基准(参照)</span><span></span><span></span></div>
    <div class="vc__stack is-base">${VC_CLASSES.map((n,k)=>`<i style="width:${base[k]*100}%;background:${VC_COLOR[k]}"></i>`).join('')}</div>
    <div class="vc__cap" style="margin-top:2px"><span>车种</span><span>本范围</span><span>偏离</span></div>
    ${ordered.map(r=>`<div class="vc__row">
        <span class="vc__name"><i class="vc__dot" style="background:${r.c}"></i><span class="vc__n">${r.n}</span></span>
        <span class="vc__v">${pct(r.v)}</span>
        <span class="vc__d ${Math.abs(r.d)<0.01?'is-flat':r.d>0?'is-up':'is-down'}">${r.d>0?'+':''}${(r.d*100).toFixed(1)}</span>
      </div>`).join('')}
    <div class="sec__note" style="margin-top:6px">「偏离」= 本范围占比 − 全市基准占比;<span style="color:var(--danger)">红</span>为更集中,<span style="color:var(--link)">青</span>为偏少。</div>`;
}

/* —— D 夜间与时段 —— */
function renderNight(v){
  const isD = S.focus.kind==='district';
  const r = isD ? v.rows[S.focus.idx] : null;
  const hist = isD ? r.hour : v.city.hour;
  const cnt = isD ? r.count : v.total;
  const nightShare = hist.reduce((a,_,h)=> (h>=22||h<=5) ? a+hist[h] : a, 0);
  const bands = BANDS.map((_,b)=> hist.slice(b*4,b*4+4).reduce((a,x)=>a+x,0));
  const bm = Math.max(...bands);
  const peakB = bands.indexOf(bm);
  document.getElementById('nightBox').innerHTML = `
    <div class="night">
      <span class="night__v">${pct(nightShare,0)}</span>
      <span class="night__l">夜间(22–05 点)<b>${fmt(nightShare*cnt)}</b> 起</span>
      <span class="night__c">全市 ${pct(v.city.nit,0)}</span>
    </div>
    <div class="bands">
      ${bands.map((x,i)=>`<div class="band${i===peakB?' is-peak':''}">
        <div class="band__t"><i class="band__f" style="height:${Math.max(3,x/bm*100)}%"></i></div>
        <div class="band__n">${pct(x,0)}</div>
        <div class="band__l">${BANDS[i]}</div>
      </div>`).join('')}
    </div>
    <div class="sec__note" style="margin-top:8px">高峰时段:<b>${BANDS[peakB]}</b>(占 ${pct(bm)})</div>`;
}

/* —— D 反复出险点位 —— */
function renderPlace(v){
  const box = document.getElementById('placeBox');
  if(S.focus.kind!=='district'){
    box.innerHTML = `<div class="empty">在左侧排行或地图上选一个区,查看该区的反复出险点位</div>`;
    return;
  }
  const idx = S.focus.idx;
  const scale = v.rows[idx].count / DISTRICTS[idx].c;
  const rows = DISTRICTS[idx].pl.map(([addr,days,cnt],i)=>({addr,days,cnt:Math.round(cnt*scale),i}));
  box.innerHTML = rows.map(r=>`
    <button class="place__row" data-p="${r.i}">
      <span class="place__d">${r.days}天</span>
      <span class="place__m">
        <span class="place__a">${r.addr}</span>
        <span class="place__s">${fmt(r.cnt)} 起 · 跨度 ${Math.round(r.days*1.6)} 天</span>
      </span>
      <span class="place__last">10-${String(28-(r.i*3)).padStart(2,'0')}<em>末案</em></span>
    </button>`).join('');
  document.querySelectorAll('[data-p]').forEach(b=>b.onclick=()=>{
    S.focus={kind:'place', idx, p:+b.dataset.p}; render();
    flashMarker(idx, +b.dataset.p);
  });
}
function flashMarker(idx, p){
  const d = DISTRICTS[idx];
  const [cx,cy] = centroid(d.p);
  const g = svg.querySelector('#gHot');
  const c = el('circle',{cx:cx+(p-2)*14, cy:cy+(p-1)*12, r:9, fill:'none',
    stroke:'#0E7FB0','stroke-width':2.5},g);
  let t=0; const iv=setInterval(()=>{ t++; c.setAttribute('r', 9+t*3);
    c.setAttribute('opacity', Math.max(0,1-t/8)); if(t>=8){clearInterval(iv); c.remove();} },40);
}

/* —— E 30 天趋势 —— */
function renderTrend(v){
  document.getElementById('winBar').innerHTML = [7,14,30].map(w=>
    `<button class="segbtn${S.win===w?' is-on':''}" data-w="${w}">近 ${w} 天</button>`).join('');
  document.querySelectorAll('[data-w]').forEach(b=>b.onclick=()=>{S.win=+b.dataset.w;S.dayCursor=null;render();});

  const all = v.series;
  const n = all.length, from = 30 - S.win;
  const ser = all.slice(from);
  const max = Math.max(...ser), min = Math.min(...ser);
  const pk = ser.indexOf(max) + from, lo = ser.indexOf(min) + from;
  const isD = S.focus.kind==='district';
  document.getElementById('trendSub').innerHTML =
    `${isD?DISTRICTS[S.focus.idx].n:'全市'} · 峰值 10-${String(pk+1).padStart(2,'0')}(${fmt(max)} 起)· 谷值 10-${String(lo+1).padStart(2,'0')}(${fmt(min)} 起)`;

  const svgT = document.getElementById('trend');
  const W = 1000, H = 100, L = 44, R = 12, T = 10, B = 20;
  const X = i => L + (i-from)/(ser.length-1) * (W-L-R);
  const Y = val => T + (1 - (val-min)/((max-min)||1)) * (H-T-B);
  const pts = ser.map((v2,i)=>`${X(i+from).toFixed(1)},${Y(v2).toFixed(1)}`).join(' ');
  const area = `${L},${H-B} ${pts} ${X(29)},${H-B}`;
  const gridY = [0,.5,1].map(t=>{ const y=T+t*(H-T-B);
    return `<line class="grid" x1="${L}" y1="${y}" x2="${W-R}" y2="${y}"/>
            <text class="axis" x="${L-8}" y="${y+3}" text-anchor="end">${fmt(max - t*(max-min))}</text>`;}).join('');
  const xlab = ser.map((_,i)=> (i%Math.ceil(ser.length/10)===0 || i===ser.length-1)
    ? `<text class="axis" x="${X(i+from)}" y="${H-5}" text-anchor="middle">10-${String(i+from+1).padStart(2,'0')}</text>` : '').join('');
  const hit = ser.map((_,i)=>`<rect class="hit" x="${X(i+from)-(W-L-R)/ser.length/2}" y="${T}"
      width="${(W-L-R)/ser.length}" height="${H-T-B}" data-day="${i+from}"/>`).join('');
  const cur = S.dayCursor!==null && S.dayCursor>=from
    ? `<line class="cursor" x1="${X(S.dayCursor)}" y1="${T}" x2="${X(S.dayCursor)}" y2="${H-B}"/>
       <circle cx="${X(S.dayCursor)}" cy="${Y(ser[S.dayCursor-from])}" r="3.5" fill="#0E7FB0"/>
       <text x="${X(S.dayCursor)}" y="${T-1}" text-anchor="middle" class="peaklab">${fmt(ser[S.dayCursor-from])} 起</text>` : '';

  svgT.setAttribute('viewBox', `0 0 ${W} ${H}`);
  svgT.innerHTML = `${gridY}
    <polygon class="area" points="${area}"/>
    <polyline class="line" points="${pts}"/>
    <circle class="peak" cx="${X(pk)}" cy="${Y(max)}" r="3.5"/>
    ${cur}${hit}${xlab}`;
  svgT.querySelectorAll('[data-day]').forEach(b=>b.onclick=()=>{
    S.dayCursor = +b.dataset.day; render();
  });
}

/* —— 顶栏 / 地图按钮 —— */
document.getElementById('btnRecenter').onclick = ()=>{ S.focus={kind:'city'}; S.hours=null; S.win=30; render(); };
document.getElementById('btnHot').onclick = ()=>{ S.hotOn=!S.hotOn; render(); };
document.getElementById('btnFull').onclick = ()=>{ document.documentElement.requestFullscreen?.(); };
document.getElementById('btnImport').onclick = ()=>{ alert('原型:此处接入真实导入流程(顶栏 → 导入数据)'); };

/* —— 地图点击:点区即设焦点(双向联动的那一半) —— */
svg.addEventListener('click', (e)=>{
  const pt = svg.createSVGPoint(); pt.x = e.offsetX; pt.y = e.offsetY;
  // 用命中测试:直接对每个多边形做 point-in-poly(视图坐标换算略,用 clientRect 比例近似)
  const r = svg.getBoundingClientRect();
  const sx = (e.clientX - r.left) / r.width * 1000;
  const sy = (e.clientY - r.top) / r.height * 760;
  for(const d of DISTRICTS){ if(inPoly(sx, sy, d.p)){ S.focus={kind:'district', idx:d.idx}; render(); return; } }
  S.focus={kind:'city'}; render();
});
function inPoly(x,y,p){
  let c=false;
  for(let i=0,j=p.length-1;i<p.length;j=i++){
    const [xi,yi]=p[i],[xj,yj]=p[j];
    if(((yi>y)!==(yj>y)) && (x < (xj-xi)*(y-yi)/(yj-yi)+xi)) c=!c;
  }
  return c;
}

/* 初始化 */
buildMap();
render();
</script>
</body>
</html>