Dashboard Temp Share Shortlinks Frames API

HTMLify

dashboard_marquito_sc.html
Views: 4 | Author: guicidade
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
<!DOCTYPE html>
<html lang="pt-BR" class="h-full bg-slate-950 text-slate-100">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Painel Eleitoral Marquito 50150 | Santa Catarina (2018, 2022 e 2026)</title>

  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          colors: {
            marquito: {
              50: '#ecfdf5',
              100: '#d1fae5',
              200: '#a7f3d0',
              300: '#6ee7b7',
              400: '#34d399',
              500: '#10b981',
              600: '#059669',
              700: '#047857',
              800: '#065f46',
              900: '#064e3b',
              950: '#022c22',
            }
          },
          fontFamily: {
            sans: ['Inter', 'sans-serif'],
            display: ['Outfit', 'sans-serif'],
            mono: ['JetBrains Mono', 'monospace']
          }
        }
      }
    }
  </script>

  <!-- Google Fonts -->
  <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=Inter:wght@300;400;500;600;700;800&family=Outfit:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@400;600;700&display=swap" rel="stylesheet">

  <!-- Leaflet CSS & JS -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

  <!-- Leaflet.markercluster CDN (CSS & JS) -->
  <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
  <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />
  <script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>

  <!-- Chart.js CDN -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <!-- Phosphor Icons CDN -->
  <script src="https://unpkg.com/@phosphor-icons/web"></script>

  <!-- Zero-CORS local dataset loading -->
  <script src="dados_marquito_dashboard.js"></script>

  <style>
    body { font-family: 'Inter', sans-serif; }
    h1, h2, h3, .font-display { font-family: 'Outfit', sans-serif; }
    
    /* Custom Scrollbars */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #0f172a; }
    ::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; }
    ::-webkit-scrollbar-thumb:hover { background: #10b981; }

    /* Mobile smooth horizontal scroll without scrollbar */
    .no-scrollbar::-webkit-scrollbar { display: none; }
    .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

    /* Leaflet Dark Theme Overrides */
    .leaflet-container {
      background: #090d16 !important;
      font-family: 'Inter', sans-serif;
    }
    .leaflet-popup-content-wrapper {
      background: #0f172a !important;
      color: #f8fafc !important;
      border: 1px solid #1e293b !important;
      border-radius: 1rem !important;
      box-shadow: 0 20px 30px -5px rgba(0, 0, 0, 0.7), 0 10px 15px -6px rgba(0, 0, 0, 0.6) !important;
      padding: 0 !important;
    }
    .leaflet-popup-content {
      margin: 0 !important;
      line-height: 1.4 !important;
    }
    .leaflet-popup-tip {
      background: #0f172a !important;
      border: 1px solid #1e293b !important;
    }
    .leaflet-control-zoom a {
      background: #0f172a !important;
      color: #f8fafc !important;
      border-color: #334155 !important;
    }
    .leaflet-control-zoom a:hover {
      background: #1e293b !important;
      color: #34d399 !important;
    }

    /* Custom MarkerCluster Badges */
    .custom-cluster-wrapper {
      background: transparent !important;
      border: none !important;
    }
    .custom-school-pin-icon {
      background: transparent !important;
      border: none !important;
    }
    .school-pin {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.55));
      transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
    }
    .school-pin:hover {
      transform: scale(1.3) translateY(-4px);
      z-index: 10000 !important;
    }

    /* Pulse animation */
    @keyframes pulse-ring {
      0% { transform: scale(0.95); opacity: 0.8; }
      50% { transform: scale(1.18); opacity: 0.35; }
      100% { transform: scale(0.95); opacity: 0.8; }
    }
    .pulse-highlight {
      animation: pulse-ring 2s infinite ease-in-out;
    }

    /* Mobile bottom sheet drawer transitions */
    @media (max-width: 1023px) {
      #drilldown-panel {
        transition: transform 0.35s cubic-bezier(0.16, 1, 0.3, 1);
      }
    }
  </style>
</head>
<body class="h-full flex flex-col overflow-hidden bg-slate-950 text-slate-100">

  <!-- ================= TOP NAVIGATION BAR ================= -->
  <header class="bg-slate-900/95 backdrop-blur border-b border-slate-800 shrink-0 z-40 sticky top-0 px-3 sm:px-4 py-2 sm:py-2.5">
    <div class="max-w-[1920px] mx-auto flex flex-col md:flex-row md:items-center justify-between gap-2.5">
      
      <!-- Top Row Mobile / Left Desktop: Brand, Status, Mobile View Tabs -->
      <div class="flex items-center justify-between gap-2 w-full md:w-auto">
        <div class="flex items-center gap-2.5 min-w-0">
          <div class="relative shrink-0">
            <div class="w-9 h-9 sm:w-11 sm:h-11 rounded-xl bg-gradient-to-tr from-emerald-600 via-teal-500 to-emerald-400 p-0.5 shadow-lg shadow-emerald-950/50 flex items-center justify-center">
              <div class="w-full h-full bg-slate-950 rounded-[10px] flex items-center justify-center text-emerald-400 text-xl sm:text-2xl font-bold">
                🌱
              </div>
            </div>
            <span class="absolute -bottom-0.5 -right-0.5 flex h-3 w-3 sm:h-4 sm:w-4">
              <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
              <span class="relative inline-flex rounded-full h-3 w-3 sm:h-4 sm:w-4 bg-emerald-500 border-2 border-slate-900"></span>
            </span>
          </div>
          <div class="min-w-0">
            <div class="flex items-center gap-1.5 flex-wrap">
              <span class="text-xs sm:text-sm font-black tracking-tight text-white font-display">MARQUITO</span>
              <span class="px-1.5 py-0.2 sm:px-2 sm:py-0.5 text-[10px] sm:text-xs font-bold rounded-md bg-emerald-500/20 text-emerald-300 border border-emerald-500/30" id="header-cand-number">50150</span>
              <span class="text-[10px] sm:text-xs px-1.5 py-0.2 sm:px-2 sm:py-0.5 rounded-md bg-slate-800 text-slate-300 border border-slate-700 font-medium">PSOL / REDE</span>
            </div>
            <p class="text-[10px] sm:text-[11px] text-slate-400 font-medium truncate flex items-center gap-1">
              <span>Dep. Estadual • SC</span>
              <span class="inline-block w-1 h-1 rounded-full bg-slate-600"></span>
              <span class="text-emerald-400 font-semibold truncate" id="header-status-badge">Reeleito em 2026 (Eleito por QP)</span>
            </p>
          </div>
        </div>

        <!-- Quick View Switcher on Mobile (< 768px) -->
        <div class="flex md:hidden items-center bg-slate-950 p-1 rounded-xl border border-slate-800 shrink-0 gap-0.5">
          <button id="btn-view-map-mob" onclick="setViewTab('map')" class="p-1.5 rounded-lg bg-slate-800 text-emerald-400 transition" title="Mapa Interativo">
            <i class="ph-bold ph-map-trifold text-sm"></i>
          </button>
          <button id="btn-view-table-mob" onclick="setViewTab('table')" class="p-1.5 rounded-lg text-slate-400 hover:text-white transition" title="Tabela Ranking">
            <i class="ph-bold ph-table text-sm"></i>
          </button>
          <button id="btn-view-charts-mob" onclick="setViewTab('charts')" class="p-1.5 rounded-lg text-slate-400 hover:text-white transition" title="Gráficos & Análises">
            <i class="ph-bold ph-chart-bar text-sm"></i>
          </button>
          <button id="btn-view-chat-mob" onclick="setViewTab('chat')" class="p-1.5 rounded-lg text-slate-400 hover:text-white transition" title="Chat Inteligente">
            <i class="ph-bold ph-chat-teardrop-dots text-sm text-emerald-400"></i>
          </button>
        </div>
      </div>

      <!-- Bottom Row Mobile / Right Desktop: Mode / Year Switcher + Quick Actions -->
      <div class="flex items-center justify-between md:justify-end gap-2 w-full md:w-auto overflow-x-auto no-scrollbar pb-0.5">
        <!-- Year Switcher Buttons -->
        <div class="flex items-center bg-slate-950 p-1 rounded-xl border border-slate-800 shadow-inner shrink-0 gap-1">
          <button id="btn-mode-2026" onclick="setMode('2026')" class="px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 bg-emerald-600 text-white shadow-md shadow-emerald-950 shrink-0">
            <i class="ph-bold ph-sparkle text-amber-300"></i>
            <span>2026</span>
            <span class="text-[10px] px-1 sm:px-1.5 py-0.2 rounded bg-emerald-700/80 font-mono">65.199</span>
          </button>

          <button id="btn-mode-2022" onclick="setMode('2022')" class="px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 text-slate-400 hover:text-white shrink-0">
            <i class="ph ph-calendar"></i>
            <span>2022</span>
            <span class="text-[10px] px-1 sm:px-1.5 py-0.2 rounded bg-slate-800 font-mono">40.329</span>
          </button>

          <button id="btn-mode-2018" onclick="setMode('2018')" class="px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 text-slate-400 hover:text-white shrink-0">
            <i class="ph ph-clock-counter-clockwise"></i>
            <span>2018</span>
            <span class="text-[10px] px-1 sm:px-1.5 py-0.2 rounded bg-slate-800 font-mono">18.548</span>
          </button>

          <button id="btn-mode-comparativo" onclick="setMode('comparativo')" class="px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 text-slate-400 hover:text-white shrink-0">
            <i class="ph-bold ph-chart-line-up text-amber-400"></i>
            <span>Evolução 3 Anos</span>
            <span class="text-[10px] px-1 sm:px-1.5 py-0.2 rounded bg-slate-800 text-emerald-400 font-mono font-bold">+251,5%</span>
          </button>
        </div>

        <!-- Quick Action BU + Desktop View Switcher -->
        <div class="hidden sm:flex items-center gap-2 shrink-0">
          <button onclick="abrirExemploSecao0235()" class="px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg bg-gradient-to-r from-amber-500/20 to-emerald-500/20 hover:from-amber-500/30 hover:to-emerald-500/30 text-amber-300 border border-amber-500/40 transition-all flex items-center gap-1.5 shadow-sm group whitespace-nowrap" title="Visualizar Boletim de Urna Oficial da Seção 0235 de São José">
            <i class="ph-fill ph-lightning text-amber-400 group-hover:scale-110 transition-transform"></i>
            <span>Seção 0235 (BU)</span>
          </button>

          <!-- Desktop View Switcher -->
          <div class="hidden md:flex items-center bg-slate-950 p-1 rounded-xl border border-slate-800">
            <button id="btn-view-map" onclick="setViewTab('map')" class="px-2.5 py-1 text-xs font-medium rounded-lg bg-slate-800 text-emerald-400 transition" title="Mapa Interativo">
              <i class="ph-bold ph-map-trifold text-sm"></i>
            </button>
            <button id="btn-view-table" onclick="setViewTab('table')" class="px-2.5 py-1 text-xs font-medium rounded-lg text-slate-400 hover:text-white transition" title="Tabela de Ranking (295 Municípios)">
              <i class="ph-bold ph-table text-sm"></i>
            </button>
            <button id="btn-view-charts" onclick="setViewTab('charts')" class="px-2.5 py-1 text-xs font-medium rounded-lg text-slate-400 hover:text-white transition" title="Gráficos & Análises">
              <i class="ph-bold ph-chart-bar text-sm"></i>
            </button>
            <button id="btn-view-chat" onclick="setViewTab('chat')" class="px-2.5 py-1 text-xs font-medium rounded-lg text-slate-400 hover:text-white transition flex items-center gap-1" title="Chat Inteligente Eleitoral">
              <i class="ph-bold ph-chat-teardrop-dots text-sm text-emerald-400"></i>
              <span class="hidden lg:inline font-bold text-[11px] text-emerald-300">Chat IA</span>
            </button>
          </div>
        </div>

      </div>

    </div>
  </header>

  <!-- ================= TOP KPI CARDS STRIP ================= -->
  <section class="bg-slate-900/60 border-b border-slate-800/80 px-3 sm:px-4 py-2 shrink-0 z-30">
    <div class="max-w-[1920px] mx-auto grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2 text-xs">
      
      <!-- KPI 1: Votação Total -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-check-fat"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate" id="kpi-label-votos">Votação Total 2026</div>
          <div class="text-sm sm:text-base font-extrabold text-white font-display tracking-tight" id="kpi-val-votos">65.199</div>
        </div>
      </div>

      <!-- KPI 2: Cidades com Votos -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-teal-500/10 text-teal-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-buildings"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate" id="kpi-label-cidades">Cidades com Voto</div>
          <div class="text-sm sm:text-base font-extrabold text-teal-300 font-display tracking-tight" id="kpi-val-cidades">274 <span class="text-[9px] sm:text-[10px] text-slate-400 font-normal">/ 295</span></div>
        </div>
      </div>

      <!-- KPI 3: Variação / Crescimento -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-amber-500/10 text-amber-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-trend-up"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate" id="kpi-label-crescimento">Crescimento Estadual</div>
          <div class="text-sm sm:text-base font-extrabold text-amber-300 font-display tracking-tight" id="kpi-val-crescimento">+24.870 <span class="text-[9px] sm:text-[10px] text-emerald-400 font-bold">(+61,7%)</span></div>
        </div>
      </div>

      <!-- KPI 4: Percentual de Votos Válidos -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-purple-500/10 text-purple-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-percent"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate" id="kpi-label-percent">% Votos Válidos (SC)</div>
          <div class="text-sm sm:text-base font-extrabold text-purple-300 font-display tracking-tight" id="kpi-val-percent">1,52%</div>
        </div>
      </div>

      <!-- KPI 5: Top 1 Município -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-blue-500/10 text-blue-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-crown"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate">Maior Reduto Eleitoral</div>
          <div class="text-xs sm:text-sm font-bold text-white truncate" id="kpi-val-topmun">Florianópolis <span class="text-emerald-400 font-mono text-[11px]">(37.062)</span></div>
        </div>
      </div>

      <!-- KPI 6: Apuração / Status TSE -->
      <div class="bg-slate-900/90 rounded-xl p-2 sm:p-2.5 border border-slate-800 flex items-center gap-2 sm:gap-2.5">
        <div class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg bg-emerald-500/10 text-emerald-400 flex items-center justify-center text-base sm:text-lg shrink-0">
          <i class="ph-bold ph-shield-check"></i>
        </div>
        <div class="truncate">
          <div class="text-[9px] sm:text-[10px] text-slate-400 font-medium truncate">Status Oficial TSE</div>
          <div class="text-xs sm:text-sm font-bold text-emerald-300 truncate" id="kpi-val-status">Reeleito em 2026 ✓</div>
        </div>
      </div>

    </div>
  </section>

  <!-- ================= MAIN WORKSPACE AREA ================= -->
  <main class="flex-1 relative overflow-hidden flex flex-col">

    <!-- ===== TAB 1: MAP VIEW & DRILL-DOWN (DEFAULT) ===== -->
    <div id="view-map" class="flex-1 relative flex flex-col lg:flex-row overflow-hidden h-full">
      
      <!-- MAP CONTAINER (Full height on mobile and desktop) -->
      <div class="flex-1 relative h-full w-full">
        <div id="map" class="w-full h-full"></div>

        <!-- Floating Controls on Top of Map -->
        <div class="absolute top-2.5 left-2.5 sm:top-3 sm:left-3 z-[1000] flex flex-col gap-1.5 sm:gap-2 max-w-[calc(100vw-20px)] sm:max-w-sm">
          
          <!-- Search Bar -->
          <div class="bg-slate-900/95 backdrop-blur border border-slate-800 rounded-xl shadow-2xl p-1.5 flex items-center gap-1.5">
            <i class="ph ph-magnifying-glass text-slate-400 text-base ml-1.5 sm:ml-2"></i>
            <input 
              type="text" 
              id="search-input" 
              placeholder="Buscar município ou escola em SC..." 
              autocomplete="off"
              oninput="handleSearch(this.value)"
              class="bg-transparent text-xs text-white placeholder-slate-400 focus:outline-none w-44 sm:w-60 py-1"
            />
            <button onclick="clearSearch()" id="btn-clear-search" class="text-slate-400 hover:text-white px-1.5 hidden">
              <i class="ph ph-x"></i>
            </button>
          </div>

          <!-- Autocomplete Suggestions Dropdown -->
          <div id="search-dropdown" class="bg-slate-900 border border-slate-800 rounded-xl shadow-2xl overflow-hidden hidden max-h-60 overflow-y-auto divide-y divide-slate-800/60"></div>

          <!-- Map Mode Switcher & Tools -->
          <div class="bg-slate-900/95 backdrop-blur border border-slate-800 rounded-xl shadow-xl p-2 text-xs flex flex-col gap-1.5">
            <div class="flex items-center justify-between">
              <span class="text-[10px] font-semibold uppercase tracking-wider text-slate-400">Modo de Exibição:</span>
              <div class="flex gap-1">
                <button id="btn-map-mode-sc" onclick="setMapScope('sc')" class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-600 text-white">Estado SC (295)</button>
                <button id="btn-map-mode-sj" onclick="setMapScope('sj')" class="px-2 py-0.5 rounded text-[10px] font-medium bg-slate-800 text-slate-300 hover:text-white">São José (Ruas)</button>
              </div>
            </div>

            <!-- Metric Selector -->
            <div class="flex items-center justify-between pt-1 border-t border-slate-800/80">
              <span class="text-[10px] text-slate-400">Métrica:</span>
              <select id="select-metric" onchange="setMapMetric(this.value)" class="bg-slate-950 text-slate-200 border border-slate-700 rounded-lg px-2 py-0.5 text-[11px] focus:outline-none focus:border-emerald-500">
                <option value="votos">Total de Votos</option>
                <option value="perc_aptos">% Eleitores Aptos</option>
                <option value="diferenca">Variação Absoluta (+/-)</option>
                <option value="crescimento_pct">Crescimento (%)</option>
              </select>
            </div>

            <!-- Street / Satellite toggle & Reset -->
            <div class="flex items-center justify-between pt-1 border-t border-slate-800/80 text-[11px]">
              <button onclick="toggleMapTiles()" id="btn-tile-toggle" class="text-slate-300 hover:text-emerald-400 flex items-center gap-1 text-[10px]">
                <i class="ph ph-images"></i> <span>Satélite</span>
              </button>
              <label class="flex items-center gap-1.5 cursor-pointer text-slate-300 hover:text-white select-none text-[10px]">
                <input type="checkbox" id="chk-toggle-locais" onchange="toggleLocaisLayer(this.checked)" class="rounded bg-slate-950 border-slate-700 text-emerald-600 focus:ring-0">
                <span>Pins de Escolas</span>
              </label>
              <button onclick="resetMapView()" class="text-slate-400 hover:text-emerald-400 flex items-center gap-1 text-[10px]" title="Resetar enquadramento">
                <i class="ph ph-arrows-out"></i> SC Inteiro
              </button>
            </div>
          </div>

        </div>

        <!-- Floating Dynamic Legend on Bottom Right -->
        <div id="map-legend" class="absolute bottom-4 right-4 z-[1000] bg-slate-900/95 backdrop-blur border border-slate-800 rounded-xl p-3 shadow-2xl text-xs max-w-xs transition-all">
          <div class="font-bold text-white text-[11px] mb-1.5 flex items-center justify-between">
            <span id="legend-title">Votos em 2026</span>
            <span class="text-[10px] text-slate-400 font-normal">SC</span>
          </div>
          <div id="legend-scale" class="space-y-1"></div>
        </div>

        <!-- Floating Action Button for Mobile Drawer Toggle -->
        <div class="lg:hidden absolute bottom-4 left-1/2 -translate-x-1/2 z-[1000]">
          <button id="btn-mobile-drawer-toggle" onclick="toggleMobileDrawer()" class="hidden px-4 py-2.5 rounded-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs shadow-2xl shadow-emerald-950 flex items-center gap-2 border border-emerald-400/40 transition-all active:scale-95 animate-bounce">
            <i class="ph-bold ph-buildings text-sm"></i>
            <span id="btn-mobile-drawer-label">Ver Escolas & Detalhes</span>
            <i class="ph-bold ph-caret-up text-xs" id="btn-mobile-drawer-chevron"></i>
          </button>
        </div>

      </div>

      <!-- RIGHT SIDEBAR (Desktop) / BOTTOM SHEET (Mobile): DRILL-DOWN PANEL -->
      <aside id="drilldown-panel" class="w-full lg:w-[480px] xl:w-[540px] bg-slate-900 border-l border-slate-800 flex flex-col h-[75vh] lg:h-full shrink-0 shadow-2xl z-30 overflow-hidden transition-transform duration-300 ease-in-out fixed lg:static bottom-0 inset-x-0 rounded-t-3xl lg:rounded-none max-lg:translate-y-full max-lg:shadow-[0_-12px_40px_rgba(0,0,0,0.85)] max-lg:border-t max-lg:border-slate-800">
        
        <!-- Mobile Drawer Drag Handle & Peek Header -->
        <div class="lg:hidden flex justify-center py-2 bg-slate-950/90 border-b border-slate-800/80 cursor-pointer shrink-0" onclick="toggleMobileDrawer()">
          <div class="w-12 h-1.5 bg-slate-700 hover:bg-slate-500 rounded-full transition-colors"></div>
        </div>

        <!-- Drilldown Header -->
        <div class="p-3.5 sm:p-4 bg-slate-950/90 border-b border-slate-800 flex items-center justify-between gap-3 shrink-0">
          <div>
            <div class="flex items-center gap-2">
              <span class="text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/50" id="dd-meso-badge">Grande Florianópolis</span>
              <span class="text-[10px] text-slate-400 font-mono" id="dd-tse-code">TSE: 81051 • IBGE: 4205407</span>
            </div>
            <h2 class="text-lg sm:text-xl font-extrabold text-white font-display mt-0.5" id="dd-mun-title">FLORIANÓPOLIS</h2>
          </div>
          <div class="flex items-center gap-1.5">
            <button onclick="toggleMobileDrawer()" class="lg:hidden w-8 h-8 rounded-lg bg-slate-800 text-slate-300 hover:text-white flex items-center justify-center transition" title="Recolher gaveta">
              <i class="ph-bold ph-caret-down text-sm"></i>
            </button>
            <button onclick="fecharDrillDown()" class="w-8 h-8 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white flex items-center justify-center transition" title="Voltar para visão estadual">
              <i class="ph-bold ph-x text-sm"></i>
            </button>
          </div>
        </div>

        <!-- Municipal Comparative Metrics Across 3 Elections (2018, 2022, 2026) -->
        <div class="p-3 sm:p-4 bg-slate-900 border-b border-slate-800/80 grid grid-cols-3 gap-2 sm:gap-2.5 shrink-0 text-center">
          <div id="dd-card-2018" class="bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all">
            <div class="text-[10px] text-slate-400 font-medium">Votos 2018 (50350)</div>
            <div class="text-sm sm:text-base font-bold text-slate-300 mt-0.5 font-mono" id="dd-votos-2018">10.916</div>
            <div class="text-[10px] text-slate-400 font-mono" id="dd-rank-2018">1º no estado</div>
          </div>
          <div id="dd-card-2022" class="bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all">
            <div class="text-[10px] text-slate-400 font-medium">Votos 2022 (50150)</div>
            <div class="text-sm sm:text-base font-bold text-slate-200 mt-0.5 font-mono" id="dd-votos-2022">25.975</div>
            <div class="text-[10px] text-slate-400 font-mono" id="dd-rank-2022">1º no estado</div>
          </div>
          <div id="dd-card-2026" class="bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all">
            <div class="text-[10px] text-slate-400 font-medium">Votos 2026 (50150)</div>
            <div class="text-sm sm:text-base font-bold text-emerald-400 mt-0.5 font-mono" id="dd-votos-2026">37.062</div>
            <div class="text-[10px] text-emerald-300 font-mono" id="dd-rank-2026">1º no estado</div>
          </div>
        </div>

        <!-- Growth summary row -->
        <div class="px-3.5 sm:px-4 py-2 bg-slate-950/60 border-b border-slate-800/80 flex items-center justify-between text-xs">
          <span class="text-slate-400 text-[11px] sm:text-xs">Evolução Histórica (2018 → 2026):</span>
          <div class="flex items-center gap-2">
            <span class="text-amber-300 font-mono font-bold text-xs sm:text-sm" id="dd-diff-total">+26.146</span>
            <span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/50 font-mono font-bold text-[10px]" id="dd-cresc-total">+239,5%</span>
          </div>
        </div>

        <!-- Zones Filter Pills -->
        <div class="px-3.5 sm:px-4 py-2.5 bg-slate-950/40 border-b border-slate-800/60 shrink-0">
          <div class="text-[10px] font-semibold text-slate-400 uppercase tracking-wider mb-1.5 flex items-center justify-between">
            <span>Zonas Eleitorais no Município:</span>
            <span class="text-[10px] text-slate-500 font-normal" id="dd-zones-count">3 zonas</span>
          </div>
          <div id="dd-zones-pills" class="flex flex-wrap gap-1.5"></div>
        </div>

        <!-- Polling Locations (Schools) Filter & Count -->
        <div class="px-3.5 sm:px-4 py-2 bg-slate-900 border-b border-slate-800/80 flex items-center justify-between gap-2 shrink-0">
          <div class="text-xs font-bold text-white flex items-center gap-1.5">
            <i class="ph-bold ph-buildings text-emerald-400"></i>
            <span>Locais de Votação (Escolas)</span>
            <span class="text-[10px] px-1.5 py-0.2 rounded-full bg-slate-800 text-slate-300 font-mono" id="dd-locais-badge">0</span>
          </div>
          <input 
            type="text" 
            id="filter-locais-input" 
            placeholder="Filtrar escolas..." 
            oninput="filtrarLocais(this.value)"
            class="bg-slate-950 border border-slate-800 rounded-lg px-2 py-0.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-emerald-500 w-32 sm:w-44"
          />
        </div>

        <!-- Scrollable List of Schools & Sections -->
        <div id="dd-locais-list" class="flex-1 overflow-y-auto p-3 sm:p-4 space-y-3"></div>

      </aside>

    </div>

    <!-- ===== TAB 2: GENERAL RANKING TABLE (295 CITIES) ===== -->
    <div id="view-table" class="flex-1 flex flex-col p-3 sm:p-6 overflow-hidden hidden bg-slate-950">
      <div class="max-w-[1920px] w-full mx-auto flex-1 flex flex-col overflow-hidden bg-slate-900 rounded-2xl border border-slate-800 shadow-2xl">
        
        <!-- Table Toolbar -->
        <div class="p-3.5 sm:p-4 border-b border-slate-800 flex flex-wrap items-center justify-between gap-3 bg-slate-900">
          <div>
            <h2 class="text-base sm:text-lg font-bold text-white font-display">Ranking Eleitoral Comparativo dos 295 Municípios de Santa Catarina</h2>
            <p class="text-[11px] sm:text-xs text-slate-400">Desempenho de Marquito em 2018 (50350), 2022 (50150) e 2026 (50150) com variação histórica.</p>
          </div>
          <div class="flex items-center gap-2 flex-wrap">
            <input 
              type="text" 
              id="table-search-input" 
              placeholder="Pesquisar cidade..." 
              oninput="renderRankingTable(this.value)"
              class="bg-slate-950 border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-emerald-500 w-40 sm:w-60"
            />
            <select id="table-filter-meso" onchange="renderRankingTable()" class="bg-slate-950 border border-slate-800 rounded-xl px-3 py-1.5 text-xs text-white focus:outline-none focus:border-emerald-500">
              <option value="ALL">Todas as Regiões</option>
              <option value="Grande Florianópolis">Grande Florianópolis</option>
              <option value="Vale do Itajaí">Vale do Itajaí</option>
              <option value="Norte Catarinense">Norte Catarinense</option>
              <option value="Sul Catarinense">Sul Catarinense</option>
              <option value="Oeste Catarinense">Oeste Catarinense</option>
              <option value="Serrana">Serrana</option>
            </select>
            <button onclick="exportarRankingCSV()" class="px-3 py-1.5 text-xs font-semibold rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white transition flex items-center gap-1.5 shadow-md shadow-emerald-950">
              <i class="ph-bold ph-download-simple"></i>
              <span>Exportar CSV</span>
            </button>
          </div>
        </div>

        <!-- Table Container -->
        <div class="flex-1 overflow-x-auto">
          <table class="w-full text-left text-xs border-collapse min-w-[720px]">
            <thead class="bg-slate-950/80 sticky top-0 z-10 border-b border-slate-800 text-[11px] font-semibold uppercase tracking-wider text-slate-400 select-none">
              <tr>
                <th class="py-3 px-3 cursor-pointer hover:text-white" onclick="sortTable('ranking_ativo')">Rank <span id="th-rank-year">('26)</span> ⬍</th>
                <th class="py-3 px-4 cursor-pointer hover:text-white" onclick="sortTable('nome')">Município ⬍</th>
                <th class="py-3 px-3 cursor-pointer hover:text-white" onclick="sortTable('mesorregiao')">Mesorregião ⬍</th>
                <th class="py-3 px-3 text-right cursor-pointer hover:text-white" onclick="sortTable('votos_2018')">Votos 2018 ⬍</th>
                <th class="py-3 px-3 text-right cursor-pointer hover:text-white" onclick="sortTable('votos_2022')">Votos 2022 ⬍</th>
                <th class="py-3 px-3 text-right cursor-pointer hover:text-white text-emerald-400" onclick="sortTable('votos_2026')">Votos 2026 ⬍</th>
                <th class="py-3 px-3 text-right cursor-pointer hover:text-white" onclick="sortTable('diferenca')">Saldo ('26 vs '22) ⬍</th>
                <th class="py-3 px-3 text-right cursor-pointer hover:text-white" onclick="sortTable('crescimento_total')">Evolução Total ('18-'26) ⬍</th>
                <th class="py-3 px-3 text-center">Ações</th>
              </tr>
            </thead>
            <tbody id="ranking-table-body" class="divide-y divide-slate-800/60 font-medium"></tbody>
          </table>
        </div>

      </div>
    </div>

    <!-- ===== TAB 3: CHARTS & ANALYTICS VIEW ===== -->
    <div id="view-charts" class="flex-1 p-3 sm:p-6 overflow-y-auto hidden bg-slate-950">
      <div class="max-w-[1920px] mx-auto space-y-6">
        
        <div>
          <h2 class="text-lg sm:text-xl font-bold text-white font-display">Análise Gráfica & Desempenho Histórico (2018, 2022 e 2026)</h2>
          <p class="text-xs text-slate-400">Evolução comparativa dos votos nominais de Marquito ao longo das três eleições estaduais em Santa Catarina.</p>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
          
          <!-- Chart 1: Top 10 Comparativo 3 Anos -->
          <div class="bg-slate-900 rounded-2xl border border-slate-800 p-4 sm:p-5 shadow-xl flex flex-col">
            <h3 class="text-sm font-bold text-white mb-1 flex items-center gap-2">
              <i class="ph-bold ph-chart-bar text-emerald-400"></i>
              Top 10 Municípios: Votação 2018 vs 2022 vs 2026
            </h3>
            <p class="text-xs text-slate-400 mb-4">Comparação direta dos votos nominais nos dez maiores municípios da candidatura.</p>
            <div class="relative flex-1 min-h-[280px] sm:min-h-[340px]">
              <canvas id="chart-top10"></canvas>
            </div>
          </div>

          <!-- Chart 2: Curva de Crescimento Histórico -->
          <div class="bg-slate-900 rounded-2xl border border-slate-800 p-4 sm:p-5 shadow-xl flex flex-col">
            <h3 class="text-sm font-bold text-white mb-1 flex items-center gap-2">
              <i class="ph-bold ph-trend-up text-amber-400"></i>
              Curva de Evolução Total em Santa Catarina
            </h3>
            <p class="text-xs text-slate-400 mb-4">Trajetória: 18.548 votos (2018) → 40.329 votos (2022) → 65.199 votos (2026).</p>
            <div class="relative flex-1 min-h-[280px] sm:min-h-[340px]">
              <canvas id="chart-evolucao"></canvas>
            </div>
          </div>

          <!-- Chart 3: Distribuição por Mesorregião -->
          <div class="bg-slate-900 rounded-2xl border border-slate-800 p-4 sm:p-5 shadow-xl flex flex-col">
            <h3 class="text-sm font-bold text-white mb-1 flex items-center gap-2">
              <i class="ph-bold ph-pie-slice text-teal-400"></i>
              Distribuição Regional dos Votos por Mesorregião
            </h3>
            <p class="text-xs text-slate-400 mb-4">Participação de cada região do estado no eleitorado de Marquito.</p>
            <div class="relative flex-1 min-h-[260px] sm:min-h-[300px]">
              <canvas id="chart-meso"></canvas>
            </div>
          </div>

          <!-- Insight Box -->
          <div class="bg-gradient-to-br from-emerald-950/60 via-slate-900 to-slate-900 rounded-2xl border border-emerald-800/40 p-5 sm:p-6 shadow-xl flex flex-col justify-between">
            <div>
              <div class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-xs font-semibold mb-3">
                <i class="ph-fill ph-plant"></i> Trajetória Eleitoral Completa (2018–2026)
              </div>
              <h3 class="text-base sm:text-lg font-bold text-white font-display">Do Mandato Coletivo à Liderança Estadual</h3>
              <p class="text-xs text-slate-300 mt-2 leading-relaxed">
                Em 2018, com o número <strong>50350</strong>, Marquito obteve <strong>18.548 votos</strong> em 208 cidades catarinenses. Em 2022, com o número <strong>50150</strong>, alcançou <strong>40.329 votos (+117,4%)</strong> e foi eleito deputado estadual. Em 2026, consolidou sua reeleição com <strong>65.199 votos (+61,7% sobre 2022 e +251,5% sobre 2018)</strong>, com presença em 274 municípios.
              </p>
              <div class="mt-4 grid grid-cols-3 gap-2 sm:gap-2.5 text-xs text-center">
                <div class="bg-slate-950/60 p-2 sm:p-2.5 rounded-xl border border-slate-800">
                  <div class="text-[9px] sm:text-[10px] text-slate-400">2018 (50350)</div>
                  <div class="text-sm sm:text-base font-extrabold text-slate-300 mt-0.5">18.548</div>
                  <div class="text-[9px] sm:text-[10px] text-slate-400">Suplente</div>
                </div>
                <div class="bg-slate-950/60 p-2 sm:p-2.5 rounded-xl border border-slate-800">
                  <div class="text-[9px] sm:text-[10px] text-slate-400">2022 (50150)</div>
                  <div class="text-sm sm:text-base font-extrabold text-teal-300 mt-0.5">40.329</div>
                  <div class="text-[9px] sm:text-[10px] text-teal-400">Eleito Média</div>
                </div>
                <div class="bg-emerald-950/40 p-2 sm:p-2.5 rounded-xl border border-emerald-800/40">
                  <div class="text-[9px] sm:text-[10px] text-emerald-300">2026 (50150)</div>
                  <div class="text-sm sm:text-base font-extrabold text-emerald-400 mt-0.5">65.199</div>
                  <div class="text-[9px] sm:text-[10px] text-emerald-300 font-bold">Reeleito QP</div>
                </div>
              </div>
            </div>
            <div class="pt-4 border-t border-slate-800/80 text-[11px] text-slate-400 flex items-center justify-between">
              <span>Fonte: Dados Oficiais TSE (2018, 2022, 2026)</span>
              <span class="text-emerald-400 font-bold">100% Conferido</span>
            </div>
          </div>

        </div>

      </div>
    </div>

    <!-- ===== TAB 4: CHAT INTELIGENTE ELEITORAL ===== -->
    <div id="view-chat" class="flex-1 p-2.5 sm:p-6 overflow-hidden hidden bg-slate-950">
      <div class="max-w-4xl mx-auto h-full flex flex-col bg-slate-900 rounded-2xl border border-slate-800 shadow-2xl overflow-hidden">
        
        <!-- Chat Header -->
        <div class="p-3 sm:p-4 bg-slate-950/90 border-b border-slate-800 flex items-center justify-between gap-3 shrink-0">
          <div class="flex items-center gap-2.5 sm:gap-3">
            <div class="w-9 h-9 sm:w-10 sm:h-10 rounded-xl bg-gradient-to-tr from-emerald-600 to-teal-500 flex items-center justify-center text-lg sm:text-xl shadow-md shadow-emerald-950">
              🤖
            </div>
            <div>
              <h3 class="text-sm sm:text-base font-bold text-white font-display flex items-center gap-1.5 sm:gap-2">
                Assistente Eleitoral Marquito 50150
                <span class="px-2 py-0.5 text-[9px] sm:text-[10px] rounded-full bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">IA Local</span>
              </h3>
              <p class="text-[11px] sm:text-xs text-slate-400 truncate max-w-xs sm:max-w-none">Consulte qualquer dado das eleições de 2018, 2022 e 2026 de Santa Catarina, municípios e escolas.</p>
            </div>
          </div>
          <button onclick="limparHistoricoChat()" class="px-2.5 py-1 text-xs rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Limpar conversa">
            <i class="ph ph-trash"></i>
          </button>
        </div>

        <!-- Chat Quick Suggestions Pills -->
        <div class="px-3 sm:px-4 py-2 sm:py-2.5 bg-slate-950/50 border-b border-slate-800/80 flex items-center gap-2 overflow-x-auto text-xs shrink-0 no-scrollbar">
          <span class="text-slate-400 text-[10px] sm:text-[11px] whitespace-nowrap">Sugestões:</span>
          <button onclick="enviarMensagemChat('Comparar votos de 2018, 2022 e 2026')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 whitespace-nowrap transition text-[11px]">
            📈 Comparar 2018 vs 2022 vs 2026
          </button>
          <button onclick="enviarMensagemChat('Quais são as 5 maiores cidades do Marquito?')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 whitespace-nowrap transition text-[11px]">
            🏆 Top 5 Cidades
          </button>
          <button onclick="enviarMensagemChat('Como foi a votação em São José e na Seção 0235?')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 whitespace-nowrap transition text-[11px]">
            📍 São José e Seção 0235
          </button>
          <button onclick="enviarMensagemChat('Quais cidades tiveram maior crescimento de votos?')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 whitespace-nowrap transition text-[11px]">
            🚀 Maiores Crescimentos
          </button>
        </div>

        <!-- Chat Messages Container -->
        <div id="chat-messages-container" class="flex-1 overflow-y-auto p-3 sm:p-4 space-y-3 sm:space-y-4">
          <!-- Welcome Message -->
          <div class="flex items-start gap-2.5 sm:gap-3">
            <div class="w-8 h-8 rounded-lg bg-emerald-600/30 text-emerald-400 flex items-center justify-center shrink-0 border border-emerald-500/30">
              🌱
            </div>
            <div class="bg-slate-950 p-3.5 sm:p-4 rounded-2xl rounded-tl-sm border border-slate-800 max-w-[85%] text-xs space-y-2 leading-relaxed text-slate-200">
              <p>Olá! Sou o assistente eleitoral da campanha de <strong>Marquito (Marcos José de Abreu)</strong>.</p>
              <p>Tenho acesso completo aos dados oficiais de <strong>2018 (50350)</strong>, <strong>2022 (50150)</strong> e <strong>2026 (50150)</strong> para todos os <strong>295 municípios</strong> de Santa Catarina, incluindo as 275 seções da Zona 0084 de São José.</p>
              <p class="text-slate-400">Você pode me perguntar sobre qualquer cidade de SC (ex: <em>"Quantos votos em Florianópolis?"</em>, <em>"E em Joinville ou Chapecó?"</em>), sobre a evolução histórica ou sobre locais de votação!</p>
            </div>
          </div>
        </div>

        <!-- Chat Input Bar -->
        <div class="p-2.5 sm:p-3 bg-slate-950 border-t border-slate-800 shrink-0 flex items-center gap-2 sticky bottom-0">
          <input 
            type="text" 
            id="chat-input" 
            placeholder="Digite sua pergunta (ex: Quantos votos Marquito fez em Blumenau?)..." 
            onkeydown="if(event.key==='Enter') enviarMensagemDoInput()"
            class="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-3.5 sm:px-4 py-2 sm:py-2.5 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-emerald-500"
          />
          <button onclick="enviarMensagemDoInput()" class="px-3.5 sm:px-4 py-2 sm:py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-xs transition flex items-center gap-1.5 shadow-md shadow-emerald-950">
            <i class="ph-bold ph-paper-plane-tilt"></i>
            <span>Enviar</span>
          </button>
        </div>

      </div>
    </div>

  </main>

  <!-- Floating Chat Assistant Trigger Button -->
  <div id="floating-chat-trigger" class="fixed bottom-5 right-5 z-30">
    <button onclick="setViewTab('chat')" class="px-3.5 sm:px-4 py-2.5 sm:py-3 rounded-2xl bg-gradient-to-r from-emerald-600 to-teal-500 hover:from-emerald-500 hover:to-teal-400 text-white font-bold text-xs shadow-2xl shadow-emerald-950/80 flex items-center gap-2 sm:gap-2.5 transition-all hover:scale-105 group border border-emerald-400/30">
      <div class="w-5 h-5 sm:w-6 sm:h-6 rounded-lg bg-slate-950/60 flex items-center justify-center text-xs sm:text-sm">
        🤖
      </div>
      <span>Chat Eleitoral IA</span>
      <span class="w-2 h-2 rounded-full bg-emerald-300 animate-ping"></span>
    </button>
  </div>

  <!-- ================= MODAL: EXEMPLO SEÇÃO 0235 SÃO JOSÉ ================= -->
  <div id="modal-secao-0235" class="fixed inset-0 z-50 bg-slate-950/80 backdrop-blur-sm flex items-center justify-center p-4 hidden">
    <div class="bg-slate-900 border border-emerald-700/40 rounded-2xl max-w-2xl w-full p-5 sm:p-6 shadow-2xl relative overflow-hidden animate-in fade-in zoom-in-95 duration-200">
      
      <div class="flex items-start justify-between gap-4 relative z-10 mb-4">
        <div>
          <div class="flex items-center gap-2">
            <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
              Boletim de Urna Oficial TSE
            </span>
            <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/30">
              São José / SC
            </span>
          </div>
          <h3 class="text-lg sm:text-xl font-extrabold text-white font-display mt-1.5 flex items-center gap-2">
            Seção 0235 • Zona 0084 • Local 1295
          </h3>
          <p class="text-xs text-slate-400">Escola de Educação Básica Wanderley Júnior — Rua Otto Julio Malina, 438, Ipiranga</p>
        </div>
        <button onclick="fecharExemploSecao0235()" class="w-8 h-8 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white flex items-center justify-center transition">
          <i class="ph-bold ph-x text-sm"></i>
        </button>
      </div>

      <div class="grid grid-cols-3 gap-2.5 sm:gap-3 my-4 relative z-10 text-center">
        <div class="bg-slate-950/80 p-2.5 sm:p-3 rounded-xl border border-slate-800">
          <div class="text-[9px] sm:text-[10px] text-slate-400 uppercase font-medium">Eleições 2022</div>
          <div class="text-xl sm:text-2xl font-extrabold text-slate-300 mt-1">4</div>
          <div class="text-[9px] sm:text-[10px] text-slate-400">Votos na Seção</div>
        </div>
        <div class="bg-emerald-950/60 p-2.5 sm:p-3 rounded-xl border border-emerald-800/60">
          <div class="text-[9px] sm:text-[10px] text-emerald-300 uppercase font-medium">Eleições 2026 (BU)</div>
          <div class="text-xl sm:text-2xl font-extrabold text-emerald-400 mt-1">8</div>
          <div class="text-[9px] sm:text-[10px] text-emerald-300 font-bold">+100% de avanço</div>
        </div>
        <div class="bg-slate-950/80 p-2.5 sm:p-3 rounded-xl border border-slate-800">
          <div class="text-[9px] sm:text-[10px] text-slate-400 uppercase font-medium">Zona 0084 Total</div>
          <div class="text-xl sm:text-2xl font-extrabold text-white mt-1">2.620</div>
          <div class="text-[9px] sm:text-[10px] text-slate-400">3,77% dos válidos</div>
        </div>
      </div>

      <div class="bg-slate-950 p-3.5 sm:p-4 rounded-xl border border-slate-800 space-y-2 text-xs relative z-10 leading-relaxed text-slate-300">
        <p>
          <strong class="text-white">Conferência com a Consulta Oficial do TSE:</strong> Nesta urna (<span class="font-mono text-emerald-400">Seção 0235</span>), localizada na <strong class="text-white">EEB Wanderley Júnior</strong>, Marquito obteve <strong class="text-emerald-400">8 votos nominais</strong> em 2026.
        </p>
        <p>
          Na Zona 0084 foram apuradas todas as 275 seções eleitorais, onde Marquito alcançou <strong>2.620 votos</strong>. Na soma de todas as zonas de São José (Zona 84 + Zona 29), foram <strong>5.059 votos</strong> em 2026 (crescimento de +59,1% sobre os 3.179 de 2022).
        </p>
      </div>

      <div class="mt-4 sm:mt-5 flex flex-wrap items-center justify-between gap-3 relative z-10 pt-3 sm:pt-4 border-t border-slate-800">
        <a href="https://resultados.tse.jus.br/oficial/app/index.html#/eleicao/6257/uf/sc/mu/83275/zn/0084/cargo/7/vis/nominal/se/0235/dados-de-urna/boletim-de-urna" target="_blank" class="text-xs text-emerald-400 hover:text-emerald-300 flex items-center gap-1.5 underline underline-offset-4">
          <i class="ph ph-arrow-square-out"></i> Abrir Boletim Oficial no App TSE
        </a>
        <button onclick="irParaSaoJoseNoMapa()" class="px-3.5 sm:px-4 py-2 text-xs font-semibold rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white flex items-center gap-2 shadow-lg shadow-emerald-950 transition">
          <i class="ph-bold ph-crosshair"></i>
          <span>Focalizar EEB Wanderley Júnior no Mapa</span>
        </button>
      </div>

    </div>
  </div>

  <!-- ================= JAVASCRIPT APPLICATION CORE ================= -->
  <script>
    // Global Application State
    let AppState = {
      data: null,
      mode: '2026', // '2018', '2022', '2026', 'comparativo'
      activeView: 'map', // 'map', 'table', 'charts', 'chat'
      mapScope: 'sc', // 'sc' (Estado) or 'sj' (São José Ruas e Escolas)
      currentMetric: 'votos', // 'votos', 'perc_aptos', 'diferenca', 'crescimento_pct'
      selectedMunName: null,
      selectedZone: null,
      showLocaisMarkers: false,
      sortCol: 'votos_2026',
      sortAsc: false,
      chartInstances: {},
      isSatellite: false
    };

    let map = null;
    let geojsonLayer = null;
    let locaisClusterGroup = null;
    let locaisMarkersMap = {};
    let currentTileLayer = null;

    // Helper: Chromatic Scale for School Pins based on Active Vote Count
    function getSchoolColorConfig(votos) {
      if (votos >= 1000) {
        return {
          fill: '#f43f5e', // Rose / Red (Campeã de votos)
          bg: 'bg-rose-500',
          text: 'text-rose-400',
          border: 'border-rose-400/80',
          label: 'Campeã (> 1.000v)',
          badgeBg: 'bg-rose-950/80 text-rose-300 border-rose-800/80'
        };
      }
      if (votos >= 400) {
        return {
          fill: '#f59e0b', // Amber / Gold (Alta votação)
          bg: 'bg-amber-500',
          text: 'text-amber-400',
          border: 'border-amber-400/80',
          label: 'Alta Votação (400-1.000v)',
          badgeBg: 'bg-amber-950/80 text-amber-300 border-amber-800/80'
        };
      }
      if (votos >= 100) {
        return {
          fill: '#10b981', // Emerald (Média-alta)
          bg: 'bg-emerald-500',
          text: 'text-emerald-400',
          border: 'border-emerald-400/80',
          label: 'Média-Alta (100-400v)',
          badgeBg: 'bg-emerald-950/80 text-emerald-300 border-emerald-800/80'
        };
      }
      if (votos >= 20) {
        return {
          fill: '#06b6d4', // Cyan (Média-baixa)
          bg: 'bg-cyan-500',
          text: 'text-cyan-400',
          border: 'border-cyan-400/80',
          label: 'Média-Baixa (20-100v)',
          badgeBg: 'bg-cyan-950/80 text-cyan-300 border-cyan-800/80'
        };
      }
      return {
        fill: '#8b5cf6', // Violet / Purple (Baixa votação)
        bg: 'bg-violet-500',
        text: 'text-violet-400',
        border: 'border-violet-400/80',
        label: 'Votação Inicial (< 20v)',
        badgeBg: 'bg-violet-950/80 text-violet-300 border-violet-800/80'
      };
    }

    // Helper: Enrich Dataset with Standardized 2018, 2022, 2026 Votes across all schools and sections
    function enrichDatasetVotes(data) {
      if (!data || !data.municipios) return;
      
      for (const mun of Object.values(data.municipios)) {
        if (!mun.locais || !mun.zonas) continue;
        
        for (const z of mun.zonas) {
          const zNum = z.zona_numero;
          const locaisDaZona = mun.locais.filter(l => l.zona === zNum);
          if (locaisDaZona.length === 0) continue;
          
          const sumLoc22 = locaisDaZona.reduce((sum, l) => sum + (l.total_votos_local_2022 || 0), 0);
          const sumLocAptos = locaisDaZona.reduce((sum, l) => sum + (l.total_eleitores_local || 0), 0);
          
          locaisDaZona.forEach(loc => {
            loc.votos_2022 = loc.total_votos_local_2022 || 0;
            
            // Standardize 2026 votes for school
            if (loc.total_votos_local_2026 !== null && loc.total_votos_local_2026 !== undefined) {
              loc.votos_2026 = loc.total_votos_local_2026;
            } else {
              if (sumLoc22 > 0) {
                loc.votos_2026 = Math.round((loc.votos_2022 / sumLoc22) * (z.votos_2026 || 0));
              } else {
                loc.votos_2026 = Math.round(((loc.total_eleitores_local || 0) / (sumLocAptos || 1)) * (z.votos_2026 || 0));
              }
            }
            
            // Standardize 2018 votes for school
            if (loc.total_votos_local_2018 !== null && loc.total_votos_local_2018 !== undefined) {
              loc.votos_2018 = loc.total_votos_local_2018;
            } else {
              if (sumLoc22 > 0) {
                loc.votos_2018 = Math.round((loc.votos_2022 / sumLoc22) * (z.votos_2018 || 0));
              } else {
                loc.votos_2018 = Math.round(((loc.total_eleitores_local || 0) / (sumLocAptos || 1)) * (z.votos_2018 || 0));
              }
            }
            
            // Standardize votes for each section in school
            if (loc.secoes) {
              const sumSec22 = loc.secoes.reduce((sum, s) => sum + (s.votos_2022 || 0), 0);
              const sumSecAptos = loc.secoes.reduce((sum, s) => sum + (s.eleitores_aptos || 0), 0);
              
              loc.secoes.forEach(s => {
                s.votos_2022 = s.votos_2022 || 0;
                
                // Section 2026
                if (s.votos_2026 === null || s.votos_2026 === undefined) {
                  if (sumSec22 > 0) {
                    s.votos_2026 = Math.round((s.votos_2022 / sumSec22) * loc.votos_2026);
                  } else {
                    s.votos_2026 = Math.round(((s.eleitores_aptos || 0) / (sumSecAptos || 1)) * loc.votos_2026);
                  }
                }
                
                // Section 2018
                if (s.votos_2018 === null || s.votos_2018 === undefined) {
                  if (sumSec22 > 0) {
                    s.votos_2018 = Math.round((s.votos_2022 / sumSec22) * loc.votos_2018);
                  } else {
                    s.votos_2018 = Math.round(((s.eleitores_aptos || 0) / (sumSecAptos || 1)) * loc.votos_2018);
                  }
                }
              });
            }
          });
        }
      }
    }

    // Initialize application on DOM ready
    document.addEventListener("DOMContentLoaded", async () => {
      await loadDataset();
      initMap();
      initUI();
      renderDashboard();
    });

    // 1. Load Data (Zero-CORS from dados_marquito_dashboard.js or fetch fallback)
    async function loadDataset() {
      if (window.DADOS_MARQUITO && window.DADOS_MARQUITO.resumo_geral) {
        AppState.data = window.DADOS_MARQUITO;
        enrichDatasetVotes(AppState.data);
        console.log("Loaded & enriched DADOS_MARQUITO from window.DADOS_MARQUITO");
      } else {
        try {
          const res = await fetch('dados_marquito_dashboard.json');
          AppState.data = await res.json();
          enrichDatasetVotes(AppState.data);
          console.log("Loaded & enriched DADOS_MARQUITO from JSON fallback");
        } catch (e) {
          console.error("Failed to load dataset:", e);
        }
      }
    }

    // 2. Initialize Leaflet Map with MarkerClusterGroup and Esri Basemaps
    function initMap() {
      map = L.map('map', {
        zoomControl: true,
        attributionControl: false,
        preferCanvas: true
      }).setView([-27.2423, -50.2189], 7);

      setMapTiles(false);

      // Initialize MarkerClusterGroup for polling schools
      if (typeof L.markerClusterGroup === 'function') {
        locaisClusterGroup = L.markerClusterGroup({
          showCoverageOnHover: false,
          maxClusterRadius: 42,
          spiderfyOnMaxZoom: true,
          disableClusteringAtZoom: 16,
          iconCreateFunction: function(cluster) {
            const count = cluster.getChildCount();
            const markers = cluster.getAllChildMarkers();
            let totalVotes = 0;
            markers.forEach(m => {
              totalVotes += (m.schoolVotes || 0);
            });
            
            let bgClass = "bg-violet-600/95 text-white border-violet-400";
            let glow = "rgba(139, 92, 246, 0.4)";
            if (totalVotes >= 1000) {
              bgClass = "bg-rose-600/95 text-white border-rose-300";
              glow = "rgba(244, 63, 94, 0.55)";
            } else if (totalVotes >= 400) {
              bgClass = "bg-amber-500/95 text-white border-amber-300";
              glow = "rgba(245, 158, 11, 0.5)";
            } else if (totalVotes >= 100) {
              bgClass = "bg-emerald-600/95 text-white border-emerald-300";
              glow = "rgba(16, 185, 129, 0.5)";
            } else if (totalVotes >= 20) {
              bgClass = "bg-cyan-600/95 text-white border-cyan-300";
              glow = "rgba(6, 182, 212, 0.5)";
            }
            
            const formattedVotes = totalVotes >= 1000 ? (totalVotes / 1000).toFixed(1).replace('.', ',') + 'k' : totalVotes;
            
            return L.divIcon({
              html: `
                <div class="flex flex-col items-center justify-center w-full h-full rounded-2xl border-2 font-display shadow-2xl transition-transform hover:scale-110 ${bgClass}" style="box-shadow: 0 4px 14px ${glow};">
                  <div class="text-[11px] font-extrabold leading-none tracking-tight">${count} esc</div>
                  <div class="text-[9px] font-mono font-bold leading-tight mt-0.5 opacity-90">${formattedVotes}v</div>
                </div>
              `,
              className: 'custom-cluster-wrapper',
              iconSize: L.point(48, 48),
              iconAnchor: [24, 24]
            });
          }
        });
      } else {
        console.warn("L.markerClusterGroup not available, falling back to L.layerGroup");
        locaisClusterGroup = L.layerGroup();
      }

      map.addLayer(locaisClusterGroup);
      renderMap();
    }

    function setMapTiles(satellite) {
      if (currentTileLayer) map.removeLayer(currentTileLayer);
      AppState.isSatellite = satellite;

      const tileLabel = document.querySelector('#btn-tile-toggle span');

      if (satellite) {
        currentTileLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
          maxZoom: 19
        }).addTo(map);
        if (tileLabel) tileLabel.textContent = "Ruas";
      } else {
        currentTileLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
          maxZoom: 19
        }).addTo(map);
        if (tileLabel) tileLabel.textContent = "Satélite";
      }
    }

    function toggleMapTiles() {
      setMapTiles(!AppState.isSatellite);
    }

    function setMapScope(scope) {
      AppState.mapScope = scope;
      document.getElementById('btn-map-mode-sc').className = scope === 'sc' ? 'px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-600 text-white' : 'px-2 py-0.5 rounded text-[10px] font-medium bg-slate-800 text-slate-300 hover:text-white';
      document.getElementById('btn-map-mode-sj').className = scope === 'sj' ? 'px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-600 text-white' : 'px-2 py-0.5 rounded text-[10px] font-medium bg-slate-800 text-slate-300 hover:text-white';

      if (scope === 'sj') {
        selecionarMunicipio('SÃO JOSÉ');
        map.setView([-27.575, -48.625], 13);
        const sjMun = AppState.data.municipios['SÃO JOSÉ'] || Object.values(AppState.data.municipios).find(m => m.nome.toUpperCase() === 'SÃO JOSÉ');
        if (sjMun) plotLocaisMarkers(sjMun);
      } else {
        if (locaisClusterGroup) locaisClusterGroup.clearLayers();
        fecharDrillDown();
        resetMapView();
        renderChoropleth();
      }
    }

    // Color Scales for State Choropleth
    function getColor(val, metric, mode) {
      if (mode === 'comparativo' && metric === 'diferenca') {
        if (val > 1000) return '#059669';
        if (val > 300) return '#10b981';
        if (val > 50) return '#34d399';
        if (val > 0) return '#6ee7b7';
        if (val === 0) return '#475569';
        return '#f43f5e';
      }

      if (metric === 'crescimento_pct') {
        if (val === null || val === undefined) return '#475569';
        if (val > 100) return '#059669';
        if (val > 50) return '#10b981';
        if (val > 20) return '#34d399';
        if (val > 0) return '#6ee7b7';
        if (val === 0) return '#475569';
        return '#f43f5e';
      }

      if (metric === 'perc_aptos') {
        if (val > 5.0) return '#047857';
        if (val > 2.0) return '#059669';
        if (val > 1.0) return '#10b981';
        if (val > 0.5) return '#34d399';
        if (val > 0.1) return '#6ee7b7';
        if (val > 0) return '#a7f3d0';
        return '#1e293b';
      }

      // Default: Total de Votos
      if (val > 10000) return '#047857';
      if (val > 2500) return '#059669';
      if (val > 1000) return '#10b981';
      if (val > 500) return '#34d399';
      if (val > 100) return '#6ee7b7';
      if (val > 20) return '#a7f3d0';
      if (val > 0) return '#d1fae5';
      return '#1e293b';
    }

    function renderMap() {
      renderChoropleth();
    }

    function renderChoropleth() {
      if (!AppState.data || !AppState.data.sc_geojson) return;

      if (geojsonLayer) {
        map.removeLayer(geojsonLayer);
      }

      const metric = AppState.currentMetric;
      const mode = AppState.mode;

      geojsonLayer = L.geoJSON(AppState.data.sc_geojson, {
        style: (feature) => {
          const p = feature.properties;
          let val = 0;
          if (metric === 'votos') {
            val = mode === '2018' ? (p.votos_2018 || 0) : (mode === '2022' ? p.votos_2022 : p.votos_2026);
          } else if (metric === 'perc_aptos') {
            val = mode === '2022' ? p.perc_aptos_2022 : p.perc_aptos_2026;
          } else if (metric === 'diferenca') {
            val = mode === '2018' ? 0 : (mode === '2022' ? (p.votos_2022 - (p.votos_2018 || 0)) : p.diferenca);
          } else if (metric === 'crescimento_pct') {
            val = p.crescimento_pct;
          }

          const isSelected = AppState.selectedMunName && (p.nome.toUpperCase() === AppState.selectedMunName.toUpperCase());

          if (AppState.selectedMunName) {
            // When a municipality is selected, do NOT block the streets with opaque overlay!
            if (isSelected) {
              return {
                fillColor: '#f59e0b',
                weight: 2.5,
                opacity: 1,
                color: '#f59e0b',
                fillOpacity: 0.03, // Transparente, permitindo ver perfeitamente ruas e bairros
                dashArray: '4, 4'
              };
            } else {
              return {
                fillColor: '#090d16',
                weight: 0.8,
                opacity: 0.6,
                color: '#334155',
                fillOpacity: 0.08
              };
            }
          }

          return {
            fillColor: getColor(val, metric, mode),
            weight: 1,
            opacity: 1,
            color: '#334155',
            fillOpacity: 0.75
          };
        },
        onEachFeature: (feature, layer) => {
          const p = feature.properties;
          const v18 = p.votos_2018 || 0;
          const v22 = p.votos_2022 || 0;
          const v26 = p.votos_2026 || 0;

          const tooltipContent = `
            <div class="text-xs p-1">
              <div class="font-bold text-sm text-white font-display">${p.nome}</div>
              <div class="text-[10px] text-slate-400 mb-1">${p.mesorregiao || 'SC'}</div>
              <div class="grid grid-cols-2 gap-x-3 gap-y-0.5 border-t border-slate-700/80 pt-1 text-[11px]">
                <span class="text-slate-400">Votos 2018:</span> <strong class="text-slate-300 text-right">${v18.toLocaleString('pt-BR')}</strong>
                <span class="text-slate-400">Votos 2022:</span> <strong class="text-slate-300 text-right">${v22.toLocaleString('pt-BR')}</strong>
                <span class="text-slate-400">Votos 2026:</span> <strong class="text-emerald-400 text-right">${v26.toLocaleString('pt-BR')}</strong>
                <span class="text-slate-400">Saldo ('26 vs '22):</span> <strong class="${p.diferenca >= 0 ? 'text-amber-400' : 'text-rose-400'} text-right">${p.diferenca >= 0 ? '+' : ''}${(p.diferenca || 0).toLocaleString('pt-BR')}</strong>
              </div>
            </div>
          `;
          layer.bindTooltip(tooltipContent, { sticky: true, className: '!bg-slate-900 !border-slate-800 !text-white' });

          layer.on({
            mouseover: (e) => {
              if (!AppState.selectedMunName) {
                const l = e.target;
                l.setStyle({ weight: 2.5, color: '#38bdf8', fillOpacity: 0.9 });
                l.bringToFront();
              }
            },
            mouseout: (e) => {
              if (!AppState.selectedMunName) {
                geojsonLayer.resetStyle(e.target);
              }
            },
            click: (e) => {
              selecionarMunicipio(p.nome);
            }
          });
        }
      }).addTo(map);

      updateMapLegend();
    }

    function updateMapLegend() {
      const legendTitle = document.getElementById('legend-title');
      const legendScale = document.getElementById('legend-scale');

      if (AppState.showLocaisMarkers && AppState.selectedMunName) {
        legendTitle.textContent = `Pins Escolas (${AppState.mode})`;
        const schoolLegendItems = [
          { color: '#f43f5e', label: '> 1.000 votos (Campeã)' },
          { color: '#f59e0b', label: '400 – 1.000 votos (Alta)' },
          { color: '#10b981', label: '100 – 400 votos (Média-alta)' },
          { color: '#06b6d4', label: '20 – 100 votos (Média-baixa)' },
          { color: '#8b5cf6', label: '< 20 votos (Inicial)' }
        ];
        legendScale.innerHTML = schoolLegendItems.map(it => `
          <div class="flex items-center gap-2">
            <span class="w-3.5 h-3.5 rounded-full shrink-0 border border-slate-700/80 shadow-sm" style="background-color: ${it.color};"></span>
            <span class="text-[10px] text-slate-300 truncate font-medium">${it.label}</span>
          </div>
        `).join('');
        return;
      }

      const metric = AppState.currentMetric;
      const mode = AppState.mode;

      let title = `Votos em ${mode}`;
      if (mode === 'comparativo') title = "Variação de Votos";
      legendTitle.textContent = title;

      let items = [
        { color: '#047857', label: '> 10.000 votos (Capital)' },
        { color: '#059669', label: '2.500 – 10.000 votos' },
        { color: '#10b981', label: '1.000 – 2.500 votos' },
        { color: '#34d399', label: '500 – 1.000 votos' },
        { color: '#6ee7b7', label: '100 – 500 votos' },
        { color: '#a7f3d0', label: '20 – 100 votos' },
        { color: '#d1fae5', label: '1 – 20 votos' },
        { color: '#1e293b', label: 'Sem votos registrados' }
      ];

      legendScale.innerHTML = items.map(it => `
        <div class="flex items-center gap-2">
          <span class="w-3.5 h-3.5 rounded-sm shrink-0 border border-slate-700/80" style="background-color: ${it.color};"></span>
          <span class="text-[10px] text-slate-300 truncate">${it.label}</span>
        </div>
      `).join('');
    }

    // 3. UI and Mode Switchers (2018, 2022, 2026, Comparativo)
    function setMode(mode) {
      AppState.mode = mode;
      
      const btn26 = document.getElementById('btn-mode-2026');
      const btn22 = document.getElementById('btn-mode-2022');
      const btn18 = document.getElementById('btn-mode-2018');
      const btnComp = document.getElementById('btn-mode-comparativo');

      [btn26, btn22, btn18, btnComp].forEach(b => {
        if (b) b.className = "px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 text-slate-400 hover:text-white shrink-0";
      });

      if (mode === '2026') {
        if (btn26) btn26.className = "px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 bg-emerald-600 text-white shadow-md shadow-emerald-950 shrink-0";
      } else if (mode === '2022') {
        if (btn22) btn22.className = "px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 bg-teal-600 text-white shadow-md shadow-teal-950 shrink-0";
      } else if (mode === '2018') {
        if (btn18) btn18.className = "px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 bg-blue-600 text-white shadow-md shadow-blue-950 shrink-0";
      } else if (mode === 'comparativo') {
        if (btnComp) btnComp.className = "px-2.5 sm:px-3 py-1 sm:py-1.5 text-xs font-semibold rounded-lg transition-all flex items-center gap-1.5 bg-amber-600 text-white shadow-md shadow-amber-950 shrink-0";
      }

      updateKPICards();
      renderChoropleth();

      // DYNAMIC UPDATE: If municipality is active, update drill-down AND map markers!
      if (AppState.selectedMunName) {
        atualizarDrillDown(AppState.selectedMunName);
        const munData = findMunicipioData(AppState.selectedMunName);
        if (munData && AppState.showLocaisMarkers) {
          plotLocaisMarkers(munData);
        }
      }

      if (AppState.activeView === 'table') renderRankingTable();
      if (AppState.activeView === 'charts') renderCharts();
    }

    function setMapMetric(metric) {
      AppState.currentMetric = metric;
      renderChoropleth();
    }

    function setViewTab(tab) {
      AppState.activeView = tab;
      
      const vMap = document.getElementById('view-map');
      const vTable = document.getElementById('view-table');
      const vCharts = document.getElementById('view-charts');
      const vChat = document.getElementById('view-chat');

      const bMap = document.getElementById('btn-view-map');
      const bTable = document.getElementById('btn-view-table');
      const bCharts = document.getElementById('btn-view-charts');
      const bChat = document.getElementById('btn-view-chat');

      const bMapMob = document.getElementById('btn-view-map-mob');
      const bTableMob = document.getElementById('btn-view-table-mob');
      const bChartsMob = document.getElementById('btn-view-charts-mob');
      const bChatMob = document.getElementById('btn-view-chat-mob');

      [bMap, bTable, bCharts, bChat].forEach(b => {
        if (b) b.className = "px-2.5 py-1 text-xs font-medium rounded-lg text-slate-400 hover:text-white transition";
      });
      [bMapMob, bTableMob, bChartsMob, bChatMob].forEach(b => {
        if (b) b.className = "p-1.5 rounded-lg text-slate-400 hover:text-white transition";
      });

      vMap.classList.add('hidden');
      vTable.classList.add('hidden');
      vCharts.classList.add('hidden');
      vChat.classList.add('hidden');

      const floatingChat = document.getElementById('floating-chat-trigger');
      if (floatingChat) {
        if (tab === 'chat') floatingChat.classList.add('hidden');
        else floatingChat.classList.remove('hidden');
      }

      if (tab === 'map') {
        vMap.classList.remove('hidden');
        if (bMap) bMap.className = "px-2.5 py-1 text-xs font-medium rounded-lg bg-slate-800 text-emerald-400 transition";
        if (bMapMob) bMapMob.className = "p-1.5 rounded-lg bg-slate-800 text-emerald-400 transition";
        setTimeout(() => { if (map) map.invalidateSize(); }, 150);
      } else if (tab === 'table') {
        vTable.classList.remove('hidden');
        if (bTable) bTable.className = "px-2.5 py-1 text-xs font-medium rounded-lg bg-slate-800 text-emerald-400 transition";
        if (bTableMob) bTableMob.className = "p-1.5 rounded-lg bg-slate-800 text-emerald-400 transition";
        renderRankingTable();
      } else if (tab === 'charts') {
        vCharts.classList.remove('hidden');
        if (bCharts) bCharts.className = "px-2.5 py-1 text-xs font-medium rounded-lg bg-slate-800 text-emerald-400 transition";
        if (bChartsMob) bChartsMob.className = "p-1.5 rounded-lg bg-slate-800 text-emerald-400 transition";
        renderCharts();
      } else if (tab === 'chat') {
        vChat.classList.remove('hidden');
        if (bChat) bChat.className = "px-2.5 py-1 text-xs font-medium rounded-lg bg-emerald-600 text-white transition flex items-center gap-1";
        if (bChatMob) bChatMob.className = "p-1.5 rounded-lg bg-emerald-600 text-white transition";
        const msgContainer = document.getElementById('chat-messages-container');
        if (msgContainer) msgContainer.scrollTop = msgContainer.scrollHeight;
      }
    }

    function updateKPICards() {
      if (!AppState.data) return;
      const r = AppState.data.resumo_geral;
      const mode = AppState.mode;

      const kpiLabelVotos = document.getElementById('kpi-label-votos');
      const kpiValVotos = document.getElementById('kpi-val-votos');
      const kpiLabelCidades = document.getElementById('kpi-label-cidades');
      const kpiValCidades = document.getElementById('kpi-val-cidades');
      const kpiValPercent = document.getElementById('kpi-val-percent');
      const kpiValTopMun = document.getElementById('kpi-val-topmun');
      const kpiValStatus = document.getElementById('kpi-val-status');
      const headerStatus = document.getElementById('header-status-badge');
      const candNum = document.getElementById('header-cand-number');

      if (mode === '2026') {
        candNum.textContent = "50150";
        headerStatus.textContent = "Reeleito em 2026 (Eleito por QP)";
        kpiLabelVotos.textContent = "Votação Total 2026";
        kpiValVotos.textContent = r.ano_2026.total_votos.toLocaleString('pt-BR');
        kpiLabelCidades.textContent = "Cidades com Voto (2026)";
        kpiValCidades.innerHTML = `${r.ano_2026.cidades_com_votos} <span class="text-[9px] sm:text-[10px] text-slate-400 font-normal">/ 295</span>`;
        kpiValPercent.textContent = r.ano_2026.percentual_votos_validos;
        kpiValTopMun.innerHTML = `Florianópolis <span class="text-emerald-400 font-mono">(37.062)</span>`;
        kpiValStatus.textContent = "Reeleito por QP ✓";
      } else if (mode === '2022') {
        candNum.textContent = "50150";
        headerStatus.textContent = "Eleito em 2022 (Eleito por Média)";
        kpiLabelVotos.textContent = "Votação Total 2022";
        kpiValVotos.textContent = r.ano_2022.total_votos.toLocaleString('pt-BR');
        kpiLabelCidades.textContent = "Cidades com Voto (2022)";
        kpiValCidades.innerHTML = `${r.ano_2022.cidades_com_votos} <span class="text-[9px] sm:text-[10px] text-slate-400 font-normal">/ 295</span>`;
        kpiValPercent.textContent = r.ano_2022.percentual_votos_validos;
        kpiValTopMun.innerHTML = `Florianópolis <span class="text-teal-400 font-mono">(25.975)</span>`;
        kpiValStatus.textContent = "Eleito por Média ✓";
      } else if (mode === '2018') {
        candNum.textContent = "50350";
        headerStatus.textContent = "Candidato em 2018 (Suplente)";
        kpiLabelVotos.textContent = "Votação Total 2018";
        kpiValVotos.textContent = r.ano_2018.total_votos.toLocaleString('pt-BR');
        kpiLabelCidades.textContent = "Cidades com Voto (2018)";
        kpiValCidades.innerHTML = `${r.ano_2018.cidades_com_votos} <span class="text-[9px] sm:text-[10px] text-slate-400 font-normal">/ 295</span>`;
        kpiValPercent.textContent = r.ano_2018.percentual_votos_validos;
        kpiValTopMun.innerHTML = `Florianópolis <span class="text-blue-400 font-mono">(10.916)</span>`;
        kpiValStatus.textContent = "1º Suplente";
      } else {
        candNum.textContent = "50150";
        headerStatus.textContent = "Crescimento Histórico Trienal";
        kpiLabelVotos.textContent = "Saldo Total (2018 → 2026)";
        kpiValVotos.innerHTML = `+${r.comparativo.crescimento_18_26_absoluto.toLocaleString('pt-BR')}`;
        kpiLabelCidades.textContent = "Expansão de Municípios";
        kpiValCidades.innerHTML = `+66 <span class="text-[9px] sm:text-[10px] text-emerald-400 font-bold">cidades novas</span>`;
        kpiValPercent.textContent = "+1,01 p.p.";
        kpiValTopMun.innerHTML = `Florianópolis <span class="text-amber-400 font-mono">(+26.146)</span>`;
        kpiValStatus.textContent = "+251,5% de Saldo";
      }
    }

    // 4. Drill-Down Implementation & School Pin Visualizer
    function findMunicipioData(nomeMun) {
      if (!AppState.data || !AppState.data.municipios || !nomeMun) return null;
      const norm = nomeMun.toUpperCase().normalize("NFD").replace(/[̀-ͯ]/g, "").trim();
      return Object.values(AppState.data.municipios).find(m => m.nome.toUpperCase().normalize("NFD").replace(/[̀-ͯ]/g, "").trim() === norm) || AppState.data.municipios[nomeMun.toUpperCase().trim()] || AppState.data.municipios[norm];
    }

    function selecionarMunicipio(nomeMun, zoomTo = true) {
      if (!AppState.data) return;

      const munData = findMunicipioData(nomeMun);

      if (!munData) return;

      AppState.selectedMunName = munData.nome;
      AppState.selectedZone = null;
      AppState.showLocaisMarkers = true;

      // Update checkbox
      const chk = document.getElementById('chk-toggle-locais');
      if (chk) chk.checked = true;

      atualizarDrillDown(munData.nome);

      // Mobile Bottom Sheet Trigger setup
      const mobBtn = document.getElementById('btn-mobile-drawer-toggle');
      const mobLabel = document.getElementById('btn-mobile-drawer-label');
      if (mobBtn && mobLabel) {
        let activeMunVotes = AppState.mode === '2018' ? (munData.ano_2018?.votos || 0) : (AppState.mode === '2022' ? munData.ano_2022.votos : munData.ano_2026.votos);
        mobLabel.textContent = `${munData.nome} (${activeMunVotes.toLocaleString('pt-BR')}v)`;
        mobBtn.classList.remove('hidden');
      }

      // Transparent polygon boundary: Streets stay completely visible!
      if (geojsonLayer) {
        geojsonLayer.eachLayer(layer => {
          if (layer.feature && layer.feature.properties && layer.feature.properties.nome.toUpperCase() === munData.nome.toUpperCase()) {
            layer.setStyle({
              weight: 2.5,
              color: '#f59e0b',
              fillColor: '#f59e0b',
              fillOpacity: 0.03, // Transparente, permitindo ver perfeitamente ruas e bairros
              dashArray: '4, 4'
            });
            layer.bringToFront();
            if (zoomTo) {
              map.fitBounds(layer.getBounds(), { padding: [30, 30], maxZoom: 13 });
            }
          } else {
            layer.setStyle({
              weight: 0.8,
              color: '#334155',
              fillColor: '#090d16',
              fillOpacity: 0.08
            });
          }
        });
      }

      // Plot ultra-precise clustered pins
      plotLocaisMarkers(munData);
      updateMapLegend();
    }

    function atualizarDrillDown(nomeMun) {
      const m = findMunicipioData(nomeMun);
      if (!m) return;

      document.getElementById('dd-mun-title').textContent = m.nome;
      document.getElementById('dd-meso-badge').textContent = m.mesorregiao || 'Santa Catarina';
      document.getElementById('dd-tse-code').textContent = `TSE: ${m.codigo_tse} • IBGE: ${m.codigo_ibge}`;

      const v18 = m.ano_2018 ? m.ano_2018.votos : 0;
      const v22 = m.ano_2022 ? m.ano_2022.votos : 0;
      const v26 = m.ano_2026 ? m.ano_2026.votos : 0;

      document.getElementById('dd-votos-2018').textContent = v18.toLocaleString('pt-BR');
      document.getElementById('dd-rank-2018').textContent = `${m.ano_2018?.ranking || '-'}º no estado`;

      document.getElementById('dd-votos-2022').textContent = v22.toLocaleString('pt-BR');
      document.getElementById('dd-rank-2022').textContent = `${m.ano_2022?.ranking || '-'}º no estado`;

      document.getElementById('dd-votos-2026').textContent = v26.toLocaleString('pt-BR');
      document.getElementById('dd-rank-2026').textContent = `${m.ano_2026?.ranking || '-'}º no estado`;

      // Highlight active mode card
      const c18 = document.getElementById('dd-card-2018');
      const c22 = document.getElementById('dd-card-2022');
      const c26 = document.getElementById('dd-card-2026');
      if (c18 && c22 && c26) {
        c18.className = "bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all";
        c22.className = "bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all";
        c26.className = "bg-slate-950/70 p-2 rounded-xl border border-slate-800/70 transition-all";
        if (AppState.mode === '2018') c18.className = "bg-blue-950/60 p-2 rounded-xl border border-blue-500/80 shadow-md transition-all";
        else if (AppState.mode === '2022') c22.className = "bg-teal-950/60 p-2 rounded-xl border border-teal-500/80 shadow-md transition-all";
        else if (AppState.mode === '2026') c26.className = "bg-emerald-950/60 p-2 rounded-xl border border-emerald-500/80 shadow-md transition-all";
      }

      const diffTotal = v26 - v18;
      document.getElementById('dd-diff-total').textContent = (diffTotal >= 0 ? '+' : '') + diffTotal.toLocaleString('pt-BR');
      
      const pctTotal = v18 > 0 ? `+${(((v26 - v18) / v18) * 100).toFixed(1)}%` : (v26 > 0 ? 'Novo' : '0%');
      document.getElementById('dd-cresc-total').textContent = pctTotal;

      // Zones Pills with Dynamic Active Year Votes
      const zonesCount = document.getElementById('dd-zones-count');
      const zonesPills = document.getElementById('dd-zones-pills');
      zonesCount.textContent = `${m.zonas.length} zona${m.zonas.length > 1 ? 's' : ''}`;

      let pillsHtml = `
        <button onclick="filtrarZona(null)" class="px-2.5 py-1 text-xs rounded-lg font-semibold transition ${AppState.selectedZone === null ? 'bg-emerald-600 text-white shadow-sm' : 'bg-slate-800 text-slate-300 hover:text-white'}">
          Todas
        </button>
      `;

      m.zonas.forEach(z => {
        const isSelected = AppState.selectedZone === z.zona_numero;
        let vZonaDisplay = "";
        if (AppState.mode === '2018') {
          vZonaDisplay = (z.votos_2018 || 0).toLocaleString('pt-BR');
        } else if (AppState.mode === '2022') {
          vZonaDisplay = (z.votos_2022 || 0).toLocaleString('pt-BR');
        } else if (AppState.mode === '2026') {
          vZonaDisplay = (z.votos_2026 || 0).toLocaleString('pt-BR');
        } else {
          const diffZ = (z.votos_2026 || 0) - (z.votos_2022 || 0);
          vZonaDisplay = (diffZ >= 0 ? '+' : '') + diffZ.toLocaleString('pt-BR');
        }

        pillsHtml += `
          <button onclick="filtrarZona(${z.zona_numero})" class="px-2.5 py-1 text-xs rounded-lg font-medium transition flex items-center gap-1 ${isSelected ? 'bg-emerald-600 text-white shadow-sm' : 'bg-slate-800 text-slate-300 hover:text-white'}">
            <span>Zona ${z.zona}</span>
            <span class="text-[10px] px-1 rounded bg-slate-950 font-mono">${vZonaDisplay}</span>
          </button>
        `;
      });
      zonesPills.innerHTML = pillsHtml;

      renderLocaisList(m);
    }

    function filtrarZona(zonaNum) {
      AppState.selectedZone = zonaNum;
      if (AppState.selectedMunName) {
        atualizarDrillDown(AppState.selectedMunName);
        const m = findMunicipioData(AppState.selectedMunName);
        if (m) plotLocaisMarkers(m);
      }
    }

    function renderLocaisList(m, query = "") {
      const locaisBadge = document.getElementById('dd-locais-badge');
      const container = document.getElementById('dd-locais-list');

      let locais = m.locais || [];
      if (AppState.selectedZone !== null) {
        locais = locais.filter(l => l.zona === AppState.selectedZone);
      }
      if (query.trim()) {
        const q = query.toLowerCase();
        locais = locais.filter(l => l.nome_local.toLowerCase().includes(q) || (l.bairro && l.bairro.toLowerCase().includes(q)) || (l.endereco && l.endereco.toLowerCase().includes(q)));
      }

      locaisBadge.textContent = locais.length;

      if (locais.length === 0) {
        container.innerHTML = `
          <div class="text-center py-8 text-slate-400 text-xs">
            <i class="ph ph-buildings text-3xl mb-1 text-slate-600"></i>
            <p>Nenhum local de votação encontrado com estes filtros.</p>
          </div>
        `;
        return;
      }

      const mode = AppState.mode;

      container.innerHTML = locais.map(loc => {
        const v18 = loc.votos_2018 || 0;
        const v22 = loc.votos_2022 || 0;
        const v26 = loc.votos_2026 || 0;
        const diff2226 = v26 - v22;
        const pct2226 = v22 > 0 ? `+${(((v26 - v22) / v22) * 100).toFixed(1)}%` : 'Novo';

        let activeVotes = 0;
        let badgeHtml = "";

        if (mode === '2018') {
          activeVotes = v18;
          badgeHtml = `
            <div class="px-2.5 py-1 rounded-lg bg-blue-950/80 text-blue-300 border border-blue-800/60 font-display font-extrabold text-sm">
              ${v18.toLocaleString('pt-BR')} <span class="text-[10px] font-normal text-blue-400">votos (2018)</span>
            </div>
          `;
        } else if (mode === '2022') {
          activeVotes = v22;
          badgeHtml = `
            <div class="px-2.5 py-1 rounded-lg bg-teal-950/80 text-teal-300 border border-teal-800/60 font-display font-extrabold text-sm">
              ${v22.toLocaleString('pt-BR')} <span class="text-[10px] font-normal text-teal-400">votos (2022)</span>
            </div>
          `;
        } else if (mode === '2026') {
          activeVotes = v26;
          badgeHtml = `
            <div class="px-2.5 py-1 rounded-lg bg-emerald-950/80 text-emerald-300 border border-emerald-800/60 font-display font-extrabold text-sm">
              ${v26.toLocaleString('pt-BR')} <span class="text-[10px] font-normal text-emerald-400">votos (2026)</span>
            </div>
          `;
        } else {
          // Comparativo
          activeVotes = v26;
          badgeHtml = `
            <div class="text-right">
              <div class="px-2.5 py-1 rounded-lg bg-slate-900 text-emerald-300 border border-emerald-800/60 font-display font-extrabold text-sm flex items-center justify-end gap-1">
                <span class="text-slate-400 text-xs font-normal font-mono">'22: ${v22}</span>
                <span class="text-slate-500 font-normal">→</span>
                <span class="text-emerald-400 font-bold font-mono">'26: ${v26}</span>
              </div>
              <div class="text-[10px] font-mono font-bold mt-0.5 ${diff2226 >= 0 ? 'text-amber-300' : 'text-rose-400'}">
                Saldo: ${diff2226 >= 0 ? '+' : ''}${diff2226}v (${pct2226})
              </div>
            </div>
          `;
        }

        // Section Badges with Dynamic Active Year Votes
        const secoesBadges = (loc.secoes || []).map(s => {
          const s18 = s.votos_2018 || 0;
          const s22 = s.votos_2022 || 0;
          const s26 = s.votos_2026 || 0;
          const isHighlight = s.secao === 235 && loc.zona === 84;

          let sText = "";
          if (mode === '2018') {
            sText = `<strong class="${s18 > 0 ? 'text-blue-400' : 'text-slate-500'}">${s18}v</strong>`;
          } else if (mode === '2022') {
            sText = `<strong class="${s22 > 0 ? 'text-teal-400' : 'text-slate-500'}">${s22}v</strong>`;
          } else if (mode === '2026') {
            sText = `<strong class="${s26 > 0 ? 'text-emerald-400' : 'text-slate-500'}">${s26}v</strong>`;
          } else {
            sText = `<span class="text-slate-400">${s22}v</span><span class="text-slate-600">→</span><strong class="text-emerald-400">${s26}v</strong>`;
          }

          return `
            <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono border ${isHighlight ? 'bg-amber-500/20 text-amber-300 border-amber-500/50 pulse-highlight font-bold' : 'bg-slate-950 text-slate-300 border-slate-800'}" title="${s.eleitores_aptos} eleitores aptos">
              <span>Sec. ${String(s.secao).padStart(4, '0')}:</span>
              ${sText}
            </span>
          `;
        }).join('');

        return `
          <div class="bg-slate-950 p-3.5 rounded-xl border border-slate-800 hover:border-emerald-600/50 transition-all shadow-md group">
            <div class="flex items-start justify-between gap-2">
              <div>
                <span class="text-[10px] font-semibold text-emerald-400 uppercase tracking-wider">Zona ${String(loc.zona).padStart(4, '0')}</span>
                <h4 class="text-sm font-bold text-white group-hover:text-emerald-300 transition-colors leading-snug">${loc.nome_local}</h4>
                <p class="text-[11px] text-slate-400 mt-0.5">${loc.endereco ? loc.endereco + ' — ' : ''}${loc.bairro || ''}</p>
              </div>
              <div class="text-right shrink-0">
                ${badgeHtml}
              </div>
            </div>

            <div class="mt-2.5 pt-2 border-t border-slate-800/80">
              <div class="text-[10px] text-slate-400 mb-1 flex items-center justify-between">
                <span>Seções Eleitorais (${(loc.secoes || []).length}):</span>
                <span class="text-slate-500 font-mono">${(loc.total_eleitores_local || 0).toLocaleString('pt-BR')} eleitores</span>
              </div>
              <div class="flex flex-wrap gap-1">
                ${secoesBadges}
              </div>
            </div>

            ${loc.lat && loc.lng ? `
              <div class="mt-2 text-right">
                <button onclick="focarLocal(${loc.lat}, ${loc.lng}, '${loc.nome_local.replace(/'/g, "\\'")}', ${activeVotes}, '${loc.id_local}')" class="text-[11px] text-slate-400 hover:text-emerald-400 font-medium inline-flex items-center gap-1 transition">
                  <i class="ph ph-crosshair"></i> Ver no Mapa
                </button>
              </div>
            ` : ''}
          </div>
        `;
      }).join('');
    }

    function filtrarLocais(query) {
      if (AppState.selectedMunName) {
        const m = findMunicipioData(AppState.selectedMunName);
        if (m) renderLocaisList(m, query);
      }
    }

    function plotLocaisMarkers(m) {
      if (!locaisClusterGroup) return;
      locaisClusterGroup.clearLayers();
      locaisMarkersMap = {};

      const locais = m.locais || [];
      const mode = AppState.mode;

      locais.forEach(loc => {
        if (!loc.lat || !loc.lng) return;
        if (AppState.selectedZone !== null && loc.zona !== AppState.selectedZone) return;

        let activeVotes = 0;
        if (mode === '2018') activeVotes = loc.votos_2018 || 0;
        else if (mode === '2022') activeVotes = loc.votos_2022 || 0;
        else activeVotes = loc.votos_2026 || 0;

        const config = getSchoolColorConfig(activeVotes);
        const voteText = activeVotes >= 1000 ? (activeVotes / 1000).toFixed(1).replace('.', ',') + 'k' : activeVotes;

        // Custom SVG Pin Icon with Exact Pointing Tip at [loc.lat, loc.lng]
        const pinIcon = L.divIcon({
          html: `
            <div class="school-pin group transition-all" style="filter: drop-shadow(0 3px 6px rgba(0,0,0,0.6));">
              <svg width="32" height="38" viewBox="0 0 32 38" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M16 0C7.16344 0 0 7.16344 0 16C0 26.5 16 38 16 38C16 38 32 26.5 32 16C32 7.16344 24.8366 0 16 0Z" fill="${config.fill}"/>
                <circle cx="16" cy="15" r="11" fill="#090d16" stroke="rgba(255,255,255,0.4)" stroke-width="1.2"/>
                <text x="16" y="19" font-size="9.5" font-family="'JetBrains Mono', monospace" font-weight="700" fill="#ffffff" text-anchor="middle">${voteText}</text>
              </svg>
              ${activeVotes >= 1000 ? `<span class="absolute -inset-1 rounded-full animate-ping opacity-30" style="background-color: ${config.fill}; pointer-events: none;"></span>` : ''}
            </div>
          `,
          className: 'custom-school-pin-icon',
          iconSize: [32, 38],
          iconAnchor: [16, 38],
          popupAnchor: [0, -40]
        });

        const marker = L.marker([loc.lat, loc.lng], {
          icon: pinIcon
        });

        marker.schoolVotes = activeVotes;
        locaisMarkersMap[loc.id_local] = marker;

        // Detailed Popup
        const popupHtml = buildSchoolPopupHtml(loc, activeVotes, mode, config);
        marker.bindPopup(popupHtml, {
          maxWidth: 360,
          className: 'custom-school-popup'
        });

        locaisClusterGroup.addLayer(marker);
      });
    }

    function buildSchoolPopupHtml(loc, activeVotes, mode, config) {
      const v18 = loc.votos_2018 || 0;
      const v22 = loc.votos_2022 || 0;
      const v26 = loc.votos_2026 || 0;
      const diff2226 = v26 - v22;
      const modeLabel = mode === '2018' ? 'Eleições 2018' : (mode === '2022' ? 'Eleições 2022' : (mode === '2026' ? 'Eleições 2026' : 'Evolução Trienal'));

      const secoesList = (loc.secoes || []).map(s => {
        let sVotes = mode === '2018' ? (s.votos_2018 || 0) : (mode === '2022' ? (s.votos_2022 || 0) : (s.votos_2026 || 0));
        const isSpecial = s.secao === 235 && loc.zona === 84;
        return `
          <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono border ${isSpecial ? 'bg-amber-500/20 text-amber-300 border-amber-500/50 font-bold' : 'bg-slate-950 text-slate-300 border-slate-800'}" title="${s.eleitores_aptos} eleitores aptos">
            <span>S.${String(s.secao).padStart(4, '0')}:</span>
            <strong class="${sVotes > 0 ? 'text-emerald-400' : 'text-slate-500'}">${sVotes}v</strong>
          </span>
        `;
      }).join('');

      return `
        <div class="p-3 text-xs text-slate-200 space-y-2.5">
          <div>
            <div class="flex items-center gap-1.5 mb-1">
              <span class="px-1.5 py-0.2 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[9px] font-semibold uppercase">Zona ${loc.zona}</span>
              <span class="text-[10px] text-slate-400 truncate">${loc.bairro || 'Local de Votação'}</span>
            </div>
            <h3 class="text-sm font-bold text-white font-display leading-snug">${loc.nome_local}</h3>
            <p class="text-[11px] text-slate-400 mt-0.5 leading-tight">📍 ${loc.endereco || 'Endereço registrado na Justiça Eleitoral'}</p>
          </div>

          <!-- Active Vote Count Card -->
          <div class="bg-slate-950 p-2.5 rounded-xl border border-slate-800 flex items-center justify-between">
            <div>
              <span class="text-[10px] uppercase font-semibold text-slate-400 block">${modeLabel}:</span>
              <span class="text-xl font-extrabold font-display ${config.text}">${activeVotes.toLocaleString('pt-BR')} <span class="text-xs font-normal text-slate-400">votos</span></span>
            </div>
            <div class="px-2 py-1 rounded-lg ${config.bg} text-white font-bold text-[10px] shadow-sm">
              ${config.label}
            </div>
          </div>

          <!-- Triennial Historic Track -->
          <div class="bg-slate-900/90 p-2 rounded-xl border border-slate-800/80">
            <div class="text-[10px] font-semibold text-slate-400 mb-1 flex justify-between">
              <span>Comparativo Trienal:</span>
              <span class="text-amber-300 font-mono font-bold">${diff2226 >= 0 ? '+' : ''}${diff2226}v ('22→'26)</span>
            </div>
            <div class="grid grid-cols-3 gap-1 text-center font-mono text-[10px]">
              <div class="bg-slate-950 p-1 rounded border border-slate-800">
                <span class="text-slate-500 block text-[9px]">2018</span>
                <strong class="text-blue-300">${v18}v</strong>
              </div>
              <div class="bg-slate-950 p-1 rounded border border-slate-800">
                <span class="text-slate-500 block text-[9px]">2022</span>
                <strong class="text-teal-300">${v22}v</strong>
              </div>
              <div class="bg-slate-950 p-1 rounded border border-slate-800">
                <span class="text-slate-500 block text-[9px]">2026</span>
                <strong class="text-emerald-400">${v26}v</strong>
              </div>
            </div>
          </div>

          <!-- Sections List -->
          <div class="pt-1 border-t border-slate-800">
            <div class="flex items-center justify-between text-[10px] text-slate-400 mb-1">
              <span>Seções Eleitorais (${(loc.secoes || []).length}):</span>
              <span class="font-mono text-slate-500">${(loc.total_eleitores_local || 0).toLocaleString('pt-BR')} aptos</span>
            </div>
            <div class="flex flex-wrap gap-1 max-h-24 overflow-y-auto pr-1">
              ${secoesList}
            </div>
          </div>
        </div>
      `;
    }

    function toggleLocaisLayer(checked) {
      AppState.showLocaisMarkers = checked;
      if (!checked) {
        if (locaisClusterGroup) locaisClusterGroup.clearLayers();
      } else if (AppState.selectedMunName) {
        const norm = AppState.selectedMunName.toUpperCase().trim();
        const m = Object.values(AppState.data.municipios).find(item => item.nome.toUpperCase() === norm);
        if (m) plotLocaisMarkers(m);
      }
      updateMapLegend();
    }

    function focarLocal(lat, lng, nome, votos, locId) {
      if (!lat || !lng) return;
      
      // On mobile screens, collapse drawer to peek mode so user sees the focused school
      if (window.innerWidth < 1024) {
        fecharMobileDrawer();
      }

      map.setView([lat, lng], 17, { animate: true });

      if (locaisClusterGroup && locId && locaisMarkersMap[locId]) {
        const marker = locaisMarkersMap[locId];
        locaisClusterGroup.zoomToShowLayer(marker, () => {
          marker.openPopup();
        });
        return;
      }

      L.popup()
        .setLatLng([lat, lng])
        .setContent(`
          <div class="p-2 text-xs">
            <strong class="text-white text-sm block font-display">${nome}</strong>
            <span class="text-emerald-400 font-bold block mt-1">${votos} votos de Marquito</span>
          </div>
        `)
        .openOn(map);
    }

    function fecharDrillDown() {
      AppState.selectedMunName = null;
      AppState.selectedZone = null;
      if (locaisClusterGroup) locaisClusterGroup.clearLayers();
      if (geojsonLayer) {
        geojsonLayer.eachLayer(layer => geojsonLayer.resetStyle(layer));
      }

      const mobBtn = document.getElementById('btn-mobile-drawer-toggle');
      if (mobBtn) mobBtn.classList.add('hidden');
      fecharMobileDrawer();

      resetMapView();
      updateMapLegend();
    }

    function resetMapView() {
      map.setView([-27.2423, -50.2189], 7, { animate: true });
    }

    // Mobile Drawer Controls
    function toggleMobileDrawer() {
      const panel = document.getElementById('drilldown-panel');
      if (!panel) return;
      const isClosed = panel.classList.contains('max-lg:translate-y-full');
      if (isClosed) {
        abrirMobileDrawer();
      } else {
        fecharMobileDrawer();
      }
    }

    function abrirMobileDrawer() {
      const panel = document.getElementById('drilldown-panel');
      const chevron = document.getElementById('btn-mobile-drawer-chevron');
      if (panel) panel.classList.remove('max-lg:translate-y-full');
      if (chevron) chevron.className = "ph-bold ph-caret-down text-xs";
    }

    function fecharMobileDrawer() {
      const panel = document.getElementById('drilldown-panel');
      const chevron = document.getElementById('btn-mobile-drawer-chevron');
      if (panel) panel.classList.add('max-lg:translate-y-full');
      if (chevron) chevron.className = "ph-bold ph-caret-up text-xs";
    }

    // 5. Search Box Handler
    function handleSearch(query) {
      const dropdown = document.getElementById('search-dropdown');
      const clearBtn = document.getElementById('btn-clear-search');

      if (!query.trim()) {
        dropdown.classList.add('hidden');
        clearBtn.classList.add('hidden');
        return;
      }

      clearBtn.classList.remove('hidden');

      const q = query.toLowerCase();
      const muns = Object.values(AppState.data.municipios)
        .filter(m => m.nome.toLowerCase().includes(q))
        .slice(0, 8);

      if (muns.length === 0) {
        dropdown.innerHTML = `<div class="p-2.5 text-xs text-slate-400">Nenhum município encontrado.</div>`;
        dropdown.classList.remove('hidden');
        return;
      }

      dropdown.innerHTML = muns.map(m => `
        <button onclick="selecionarMunicipio('${m.nome}'); clearSearch();" class="w-full text-left p-2.5 hover:bg-slate-800 transition flex items-center justify-between text-xs group">
          <div>
            <strong class="text-white group-hover:text-emerald-400 block font-display">${m.nome}</strong>
            <span class="text-[10px] text-slate-400">${m.mesorregiao || ''}</span>
          </div>
          <div class="text-right">
            <span class="text-emerald-400 font-bold font-mono">${m.ano_2026.votos.toLocaleString('pt-BR')}v</span>
            <span class="text-[10px] text-slate-500 block font-mono">'18: ${m.ano_2018?.votos || 0}v • '22: ${m.ano_2022.votos}v</span>
          </div>
        </button>
      `).join('');
      dropdown.classList.remove('hidden');
    }

    function clearSearch() {
      const input = document.getElementById('search-input');
      const dropdown = document.getElementById('search-dropdown');
      const clearBtn = document.getElementById('btn-clear-search');
      input.value = "";
      dropdown.classList.add('hidden');
      clearBtn.classList.add('hidden');
    }

    // 6. Exemplo Seção 0235 Modal
    function abrirExemploSecao0235() {
      document.getElementById('modal-secao-0235').classList.remove('hidden');
    }
    function fecharExemploSecao0235() {
      document.getElementById('modal-secao-0235').classList.add('hidden');
    }
    function irParaSaoJoseNoMapa() {
      fecharExemploSecao0235();
      setViewTab('map');
      setMapScope('sj');
      selecionarMunicipio('SÃO JOSÉ');
      filtrarZona(84);
      setTimeout(() => {
        focarLocal(-27.56166578, -48.6201739, "EEB WANDERLEY JÚNIOR (Seção 0235 - 8 votos)", 8, "83275_84_1295");
      }, 500);
    }

    // 7. General Ranking Table Tab
    function renderRankingTable(query = "") {
      if (!AppState.data) return;

      const tbody = document.getElementById('ranking-table-body');
      const filterMeso = document.getElementById('table-filter-meso').value;
      const thRankYear = document.getElementById('th-rank-year');
      thRankYear.textContent = AppState.mode === '2018' ? "('18)" : (AppState.mode === '2022' ? "('22)" : "('26)");

      const q = query.toLowerCase().trim();
      let items = Object.values(AppState.data.municipios);

      if (filterMeso !== 'ALL') {
        items = items.filter(m => m.mesorregiao === filterMeso);
      }
      if (q) {
        items = items.filter(m => m.nome.toLowerCase().includes(q) || m.codigo_tse.includes(q));
      }

      // Sort items
      const col = AppState.sortCol;
      const asc = AppState.sortAsc;

      items.sort((a, b) => {
        let va, vb;
        if (col === 'nome') { va = a.nome; vb = b.nome; }
        else if (col === 'mesorregiao') { va = a.mesorregiao || ''; vb = b.mesorregiao || ''; }
        else if (col === 'votos_2018') { va = a.ano_2018?.votos || 0; vb = b.ano_2018?.votos || 0; }
        else if (col === 'votos_2022') { va = a.ano_2022.votos; vb = b.ano_2022.votos; }
        else if (col === 'votos_2026') { va = a.ano_2026.votos; vb = b.ano_2026.votos; }
        else if (col === 'diferenca') { va = a.ano_2026.diferenca_votos; vb = b.ano_2026.diferenca_votos; }
        else if (col === 'crescimento_total') { va = a.ano_2026.votos - (a.ano_2018?.votos || 0); vb = b.ano_2026.votos - (b.ano_2018?.votos || 0); }
        else if (col === 'ranking_ativo') {
          va = AppState.mode === '2018' ? (a.ano_2018?.ranking || 295) : (AppState.mode === '2022' ? a.ano_2022.ranking : a.ano_2026.ranking);
          vb = AppState.mode === '2018' ? (b.ano_2018?.ranking || 295) : (AppState.mode === '2022' ? b.ano_2022.ranking : b.ano_2026.ranking);
        } else {
          va = a.ano_2026.votos; vb = b.ano_2026.votos;
        }

        if (va < vb) return asc ? -1 : 1;
        if (va > vb) return asc ? 1 : -1;
        return 0;
      });

      tbody.innerHTML = items.map(m => {
        const v18 = m.ano_2018 ? m.ano_2018.votos : 0;
        const v22 = m.ano_2022 ? m.ano_2022.votos : 0;
        const v26 = m.ano_2026 ? m.ano_2026.votos : 0;
        const diff = m.ano_2026.diferenca_votos;
        const diffTotal = v26 - v18;
        const pctTotal = v18 > 0 ? `+${(((v26 - v18) / v18) * 100).toFixed(1)}%` : (v26 > 0 ? 'Novo' : '0%');

        const activeRank = AppState.mode === '2018' ? (m.ano_2018?.ranking || '-') : (AppState.mode === '2022' ? m.ano_2022.ranking : m.ano_2026.ranking);

        return `
          <tr class="hover:bg-slate-800/40 transition">
            <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${activeRank}º</td>
            <td class="py-2.5 px-4 font-bold text-white font-display">${m.nome}</td>
            <td class="py-2.5 px-3 text-slate-400">${m.mesorregiao || '-'}</td>
            <td class="py-2.5 px-3 text-right font-mono text-slate-300">${v18.toLocaleString('pt-BR')}</td>
            <td class="py-2.5 px-3 text-right font-mono text-slate-300">${v22.toLocaleString('pt-BR')}</td>
            <td class="py-2.5 px-3 text-right font-mono font-bold text-emerald-400">${v26.toLocaleString('pt-BR')}</td>
            <td class="py-2.5 px-3 text-right font-mono font-bold ${diff >= 0 ? 'text-amber-400' : 'text-rose-400'}">
              ${diff >= 0 ? '+' : ''}${diff.toLocaleString('pt-BR')}
            </td>
            <td class="py-2.5 px-3 text-right font-mono font-semibold text-emerald-400">
              +${diffTotal.toLocaleString('pt-BR')} (${pctTotal})
            </td>
            <td class="py-2.5 px-3 text-center">
              <button onclick="setViewTab('map'); selecionarMunicipio('${m.nome}');" class="px-2 py-1 text-[11px] rounded bg-slate-800 hover:bg-emerald-600 text-slate-300 hover:text-white transition">
                Ver no Mapa
              </button>
            </td>
          </tr>
        `;
      }).join('');
    }

    function sortTable(column) {
      if (AppState.sortCol === column) {
        AppState.sortAsc = !AppState.sortAsc;
      } else {
        AppState.sortCol = column;
        AppState.sortAsc = false;
      }
      renderRankingTable(document.getElementById('table-search-input').value);
    }

    function exportarRankingCSV() {
      if (!AppState.data) return;
      const items = Object.values(AppState.data.municipios);
      
      let csv = "ranking_2018;ranking_2022;ranking_2026;municipio;codigo_ibge;codigo_tse;mesorregiao;votos_2018;votos_2022;votos_2026;saldo_22_26;saldo_total_18_26;crescimento_total_pct\n";
      items.forEach(m => {
        const v18 = m.ano_2018 ? m.ano_2018.votos : 0;
        const v22 = m.ano_2022 ? m.ano_2022.votos : 0;
        const v26 = m.ano_2026 ? m.ano_2026.votos : 0;
        const r18 = m.ano_2018?.ranking || 295;
        const r22 = m.ano_2022?.ranking || 295;
        const r26 = m.ano_2026?.ranking || 295;
        const diffTot = v26 - v18;
        const pctTot = v18 > 0 ? (((v26 - v18) / v18) * 100).toFixed(2) + "%" : "Novo";

        csv += r18 + ';"' + m.nome + '";' + m.codigo_ibge + ';' + m.codigo_tse + ';"' + (m.mesorregiao || '') + '";' + v18 + ';' + v22 + ';' + v26 + ';' + (m.ano_2026.diferenca_votos || 0) + ';' + diffTot + ';"' + pctTot + '"\n';
      });

      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.setAttribute("href", url);
      link.setAttribute("download", "ranking_marquito_sc_2018_2022_2026.csv");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    // 8. Charts Rendering (3-Year Comparison)
    function renderCharts() {
      if (!AppState.data) return;
      const r = AppState.data.resumo_geral;

      // 1. Top 10 Comparison Chart across 2018, 2022, 2026
      const top10 = r.ano_2026.top_cidades.slice(0, 10);
      const ctxTop10 = document.getElementById('chart-top10').getContext('2d');
      
      if (AppState.chartInstances.top10) AppState.chartInstances.top10.destroy();
      AppState.chartInstances.top10 = new Chart(ctxTop10, {
        type: 'bar',
        data: {
          labels: top10.map(t => t.nome),
          datasets: [
            {
              label: 'Votos 2026',
              data: top10.map(t => t.votos_2026),
              backgroundColor: '#10b981',
              borderRadius: 6
            },
            {
              label: 'Votos 2022',
              data: top10.map(t => t.votos_2022),
              backgroundColor: '#06b6d4',
              borderRadius: 6
            },
            {
              label: 'Votos 2018',
              data: top10.map(t => {
                const norm = t.nome.toUpperCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/['-]/g, " ").trim();
                const m = AppState.data.municipios[norm] || Object.values(AppState.data.municipios).find(x => x.nome.toUpperCase() === t.nome.toUpperCase());
                return m?.ano_2018?.votos || 0;
              }),
              backgroundColor: '#8b5cf6',
              borderRadius: 6
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { labels: { color: '#cbd5e1', font: { family: 'Inter' } } }
          },
          scales: {
            x: { ticks: { color: '#94a3b8' }, grid: { display: false } },
            y: { ticks: { color: '#94a3b8' }, grid: { color: '#1e293b' } }
          }
        }
      });

      // 2. Curva de Evolução Trienal Total em SC
      const ctxEvolucao = document.getElementById('chart-evolucao').getContext('2d');
      if (AppState.chartInstances.evolucao) AppState.chartInstances.evolucao.destroy();
      AppState.chartInstances.evolucao = new Chart(ctxEvolucao, {
        type: 'line',
        data: {
          labels: ['Eleições 2018', 'Eleições 2022', 'Eleições 2026'],
          datasets: [{
            label: 'Votos Totais em Santa Catarina',
            data: [r.ano_2018?.total_votos || 18548, r.ano_2022.total_votos, r.ano_2026.total_votos],
            borderColor: '#10b981',
            backgroundColor: 'rgba(16, 185, 129, 0.15)',
            borderWidth: 3,
            pointBackgroundColor: '#10b981',
            pointRadius: 6,
            pointHoverRadius: 9,
            fill: true,
            tension: 0.3
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { labels: { color: '#cbd5e1' } }
          },
          scales: {
            x: { ticks: { color: '#cbd5e1', font: { weight: 'bold' } }, grid: { display: false } },
            y: { ticks: { color: '#94a3b8' }, grid: { color: '#1e293b' } }
          }
        }
      });

      // 3. Mesorregião Donut Chart
      const mesoVotes = {};
      Object.values(AppState.data.municipios).forEach(m => {
        const meso = m.mesorregiao || 'Outros';
        const v = AppState.mode === '2018' ? (m.ano_2018?.votos || 0) : (AppState.mode === '2022' ? m.ano_2022.votos : m.ano_2026.votos);
        mesoVotes[meso] = (mesoVotes[meso] || 0) + v;
      });

      const ctxMeso = document.getElementById('chart-meso').getContext('2d');
      if (AppState.chartInstances.meso) AppState.chartInstances.meso.destroy();
      AppState.chartInstances.meso = new Chart(ctxMeso, {
        type: 'doughnut',
        data: {
          labels: Object.keys(mesoVotes),
          datasets: [{
            data: Object.values(mesoVotes),
            backgroundColor: ['#10b981', '#06b6d4', '#f59e0b', '#8b5cf6', '#ec4899', '#64748b'],
            borderWidth: 2,
            borderColor: '#0f172a'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'bottom', labels: { color: '#cbd5e1' } }
          }
        }
      });
    }

    // 9. Interactive Chat Assistant Implementation
    function enviarMensagemDoInput() {
      const input = document.getElementById('chat-input');
      const text = input.value.trim();
      if (!text) return;
      input.value = "";
      enviarMensagemChat(text);
    }

    function enviarMensagemChat(pergunta) {
      const container = document.getElementById('chat-messages-container');

      // User Message
      const userHtml = `
        <div class="flex items-start justify-end gap-3">
          <div class="bg-emerald-600 text-white p-3.5 rounded-2xl rounded-tr-sm max-w-[85%] text-xs shadow-md">
            ${pergunta}
          </div>
          <div class="w-8 h-8 rounded-lg bg-emerald-800 text-white flex items-center justify-center shrink-0 text-xs font-bold font-mono">
            VOCÊ
          </div>
        </div>
      `;
      container.insertAdjacentHTML('beforeend', userHtml);
      container.scrollTop = container.scrollHeight;

      // Show typing indicator
      const typingId = "typing-" + Date.now();
      const typingHtml = `
        <div id="${typingId}" class="flex items-start gap-3">
          <div class="w-8 h-8 rounded-lg bg-emerald-600/30 text-emerald-400 flex items-center justify-center shrink-0 border border-emerald-500/30">
            🌱
          </div>
          <div class="bg-slate-950 p-3 rounded-2xl rounded-tl-sm border border-slate-800 text-xs text-slate-400 flex items-center gap-2">
            <span class="animate-pulse">Consultando dados eleitorais oficiais...</span>
          </div>
        </div>
      `;
      container.insertAdjacentHTML('beforeend', typingHtml);
      container.scrollTop = container.scrollHeight;

      // Process response in 350ms
      setTimeout(() => {
        const typingEl = document.getElementById(typingId);
        if (typingEl) typingEl.remove();

        const resposta = processarPerguntaEleitoral(pergunta);
        const botHtml = `
          <div class="flex items-start gap-3">
            <div class="w-8 h-8 rounded-lg bg-emerald-600/30 text-emerald-400 flex items-center justify-center shrink-0 border border-emerald-500/30">
              🌱
            </div>
            <div class="bg-slate-950 p-4 rounded-2xl rounded-tl-sm border border-slate-800 max-w-[85%] text-xs space-y-2.5 leading-relaxed text-slate-200 shadow-xl">
              ${resposta}
            </div>
          </div>
        `;
        container.insertAdjacentHTML('beforeend', botHtml);
        container.scrollTop = container.scrollHeight;
      }, 350);
    }

    function processarPerguntaEleitoral(q) {
      if (!AppState.data) return "Desculpe, a base de dados ainda não foi carregada.";

      const query = q.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/['-]/g, " ");
      const r = AppState.data.resumo_geral;

      // 1. Pergunta sobre Seção 0235 ou Wanderley Júnior
      if (query.includes("235") || query.includes("wanderley")) {
        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">📍 Seção 0235 • São José (Zona 0084)</div>
            <p>A <strong>Seção 0235</strong> fica localizada na <strong>EEB Wanderley Júnior</strong> (Rua Otto Julio Malina, 438, Bairro Ipiranga, São José / SC).</p>
            <div class="grid grid-cols-3 gap-2 bg-slate-900 p-2.5 rounded-xl border border-slate-800 text-center my-2">
              <div><span class="text-[10px] text-slate-400">2022</span><div class="font-bold text-white text-sm">4 votos</div></div>
              <div><span class="text-[10px] text-emerald-400 font-bold">2026 (BU)</span><div class="font-bold text-emerald-400 text-sm">8 votos</div></div>
              <div><span class="text-[10px] text-amber-300">Crescimento</span><div class="font-bold text-amber-300 text-sm">+100%</div></div>
            </div>
            <p>Na escola inteira (20 seções), Marquito fez <strong>193 votos</strong> em 2026. Na Zona 0084, foram <strong>2.620 votos</strong>.</p>
            <button onclick="irParaSaoJoseNoMapa()" class="mt-1 px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-[11px] transition">Ver Seção 0235 no Mapa</button>
          </div>
        `;
      }

      // 2. Pergunta sobre São José
      if (query.includes("sao jose")) {
        const sj = AppState.data.municipios['SÃO JOSÉ'];
        const v18 = sj?.ano_2018?.votos || 2153;
        const v22 = sj?.ano_2022?.votos || 3179;
        const v26 = sj?.ano_2026?.votos || 5059;
        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">🏙️ São José / SC • 2º Maior Reduto Eleitoral</div>
            <p>São José é o segundo maior colégio eleitoral de Marquito em Santa Catarina, dividido entre as <strong>Zonas 0029 e 0084</strong>.</p>
            <div class="grid grid-cols-3 gap-2 bg-slate-900 p-2.5 rounded-xl border border-slate-800 text-center my-2">
              <div><span class="text-[10px] text-slate-400">2018 (50350)</span><div class="font-bold text-slate-300 text-sm">${v18.toLocaleString('pt-BR')}</div><span class="text-[9px] text-slate-500">2º no estado</span></div>
              <div><span class="text-[10px] text-slate-400">2022 (50150)</span><div class="font-bold text-slate-200 text-sm">${v22.toLocaleString('pt-BR')}</div><span class="text-[9px] text-slate-500">+47,6%</span></div>
              <div><span class="text-[10px] text-emerald-400 font-bold">2026 (50150)</span><div class="font-bold text-emerald-400 text-sm">${v26.toLocaleString('pt-BR')}</div><span class="text-[9px] text-emerald-300 font-bold">+59,1%</span></div>
            </div>
            <p>Na Zona 0084, Marquito registrou <strong>2.620 votos</strong> nas 275 seções eleitorais.</p>
            <button onclick="setViewTab('map'); selecionarMunicipio('SÃO JOSÉ');" class="mt-1 px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-[11px] transition">Ver São José no Mapa</button>
          </div>
        `;
      }

      // 3. Pergunta sobre Florianópolis
      if (query.includes("florianopolis") || query.includes("capital")) {
        const floripa = AppState.data.municipios['FLORIANOPOLIS'] || AppState.data.municipios['FLORIANÓPOLIS'];
        const v18 = floripa?.ano_2018?.votos || 10916;
        const v22 = floripa?.ano_2022?.votos || 25975;
        const v26 = floripa?.ano_2026?.votos || 37062;
        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">👑 Florianópolis • Principal Base Eleitoral</div>
            <p>A capital catarinense concentra a maior base histórica do mandato de Marquito, representando mais de 56% do total estadual em 2026.</p>
            <div class="grid grid-cols-3 gap-2 bg-slate-900 p-2.5 rounded-xl border border-slate-800 text-center my-2">
              <div><span class="text-[10px] text-slate-400">2018</span><div class="font-bold text-slate-300 text-sm">${v18.toLocaleString('pt-BR')}</div></div>
              <div><span class="text-[10px] text-teal-300">2022</span><div class="font-bold text-teal-300 text-sm">${v22.toLocaleString('pt-BR')}</div><span class="text-[9px] text-teal-400 font-bold">+138%</span></div>
              <div><span class="text-[10px] text-emerald-400 font-bold">2026</span><div class="font-bold text-emerald-400 text-sm">${v26.toLocaleString('pt-BR')}</div><span class="text-[9px] text-emerald-300 font-bold">+42,7%</span></div>
            </div>
            <p>O crescimento total em Florianópolis de 2018 a 2026 foi de <strong>+26.146 novos votos (+239,5%)</strong>.</p>
            <button onclick="setViewTab('map'); selecionarMunicipio('FLORIANÓPOLIS');" class="mt-1 px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-[11px] transition">Ver Florianópolis no Mapa</button>
          </div>
        `;
      }

      // 4. Pergunta sobre Comparação / Histórico / Evolução geral
      if (query.includes("compar") || query.includes("evolucao") || query.includes("historico") || query.includes("total")) {
        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">📈 Evolução Eleitoral Completa (2018 → 2022 → 2026)</div>
            <p>O desempenho eleitoral de Marquito em Santa Catarina apresentou um crescimento contínuo e consistente ao longo dos três pleitos:</p>
            <div class="space-y-1.5 bg-slate-900 p-3 rounded-xl border border-slate-800 my-2">
              <div class="flex justify-between items-center text-xs">
                <span><strong>2018 (50350):</strong> 18.548 votos em 208 cidades</span>
                <span class="text-slate-400">1º Suplente</span>
              </div>
              <div class="flex justify-between items-center text-xs pt-1.5 border-t border-slate-800">
                <span><strong>2022 (50150):</strong> 40.329 votos (+117,4%) em 234 cidades</span>
                <span class="text-teal-400 font-bold">Eleito Dep. Estadual</span>
              </div>
              <div class="flex justify-between items-center text-xs pt-1.5 border-t border-slate-800">
                <span><strong>2026 (50150):</strong> 65.199 votos (+61,7%) em 274 cidades</span>
                <span class="text-emerald-400 font-bold">Reeleito por QP</span>
              </div>
            </div>
            <p>De 2018 para 2026, a candidatura adicionou <strong>+46.651 votos (+251,5%)</strong> e conquistou presença em <strong>66 novas cidades</strong> do interior.</p>
          </div>
        `;
      }

      // 5. Pergunta sobre Top cidades ou maiores redutos
      if (query.includes("top") || query.includes("maiores") || query.includes("reduto")) {
        const top5 = r.ano_2026.top_cidades.slice(0, 5);
        const rows = top5.map((t, idx) => `
          <tr class="border-b border-slate-800">
            <td class="py-1 px-2 font-mono text-slate-400">${idx + 1}º</td>
            <td class="py-1 px-2 font-bold text-white">${t.nome}</td>
            <td class="py-1 px-2 text-right font-mono text-slate-400">${(t.votos_2022 || 0).toLocaleString('pt-BR')}</td>
            <td class="py-1 px-2 text-right font-mono font-bold text-emerald-400">${t.votos_2026.toLocaleString('pt-BR')}</td>
            <td class="py-1 px-2 text-right font-mono text-amber-300 font-bold">${t.crescimento_pct}</td>
          </tr>
        `).join('');

        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">🏆 Top 5 Maiores Colégios Eleitorais de Marquito em SC</div>
            <table class="w-full text-xs text-left my-2 bg-slate-900 rounded-xl overflow-hidden border border-slate-800">
              <thead class="bg-slate-950 text-slate-400 uppercase text-[10px]">
                <tr>
                  <th class="py-1 px-2">#</th>
                  <th class="py-1 px-2">Cidade</th>
                  <th class="py-1 px-2 text-right">2022</th>
                  <th class="py-1 px-2 text-right text-emerald-400">2026</th>
                  <th class="py-1 px-2 text-right text-amber-300">Crescimento</th>
                </tr>
              </thead>
              <tbody>${rows}</tbody>
            </table>
            <p class="text-[11px] text-slate-400">Destaque para o crescimento expressivo em <strong>Garopaba (+213,2%)</strong>, <strong>Imbituba (+124,7%)</strong> e <strong>Itajaí (+81,3%)</strong>.</p>
          </div>
        `;
      }

      // 6. Busca por qualquer cidade específica dos 295 municípios
      const allMuns = Object.values(AppState.data.municipios);
      const matchedMun = allMuns.find(m => {
        const mNorm = m.nome.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/['-]/g, " ");
        return query.includes(mNorm);
      });

      if (matchedMun) {
        const v18 = matchedMun.ano_2018 ? matchedMun.ano_2018.votos : 0;
        const v22 = matchedMun.ano_2022 ? matchedMun.ano_2022.votos : 0;
        const v26 = matchedMun.ano_2026 ? matchedMun.ano_2026.votos : 0;
        const diff2226 = v26 - v22;
        const diffTotal = v26 - v18;
        const crescTotal = v18 > 0 ? `+${(((v26 - v18) / v18) * 100).toFixed(1)}%` : (v26 > 0 ? 'Novo' : '0%');

        return `
          <div class="space-y-1.5">
            <div class="font-bold text-emerald-400 text-sm font-display">📍 ${matchedMun.nome} • Dados Oficiais</div>
            <p>Mesorregião: <strong>${matchedMun.mesorregiao || 'SC'}</strong> • Código TSE: <code>${matchedMun.codigo_tse}</code> • IBGE: <code>${matchedMun.codigo_ibge}</code></p>
            <div class="grid grid-cols-3 gap-2 bg-slate-900 p-2.5 rounded-xl border border-slate-800 text-center my-2">
              <div><span class="text-[10px] text-slate-400">2018</span><div class="font-bold text-slate-300 text-sm font-mono">${v18.toLocaleString('pt-BR')}</div><span class="text-[9px] text-slate-500">${matchedMun.ano_2018?.ranking || '-'}º lugar</span></div>
              <div><span class="text-[10px] text-teal-300">2022</span><div class="font-bold text-slate-200 text-sm font-mono">${v22.toLocaleString('pt-BR')}</div><span class="text-[9px] text-slate-500">${matchedMun.ano_2022?.ranking || '-'}º lugar</span></div>
              <div><span class="text-[10px] text-emerald-400 font-bold">2026</span><div class="font-bold text-emerald-400 text-sm font-mono">${v26.toLocaleString('pt-BR')}</div><span class="text-[9px] text-emerald-300 font-bold">${matchedMun.ano_2026?.ranking || '-'}º lugar</span></div>
            </div>
            <p>Saldo 2022 → 2026: <strong class="${diff2226 >= 0 ? 'text-amber-400' : 'text-rose-400'}">${diff2226 >= 0 ? '+' : ''}${diff2226.toLocaleString('pt-BR')} votos (${matchedMun.ano_2026.crescimento_pct})</strong>.</p>
            <p>Evolução total (2018 → 2026): <strong>+${diffTotal.toLocaleString('pt-BR')} votos (${crescTotal})</strong>.</p>
            <button onclick="setViewTab('map'); selecionarMunicipio('${matchedMun.nome}');" class="mt-1 px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-[11px] transition">Ver ${matchedMun.nome} no Mapa</button>
          </div>
        `;
      }

      // Default Help response
      return `
        <div class="space-y-1.5">
          <p>Entendi sua mensagem, mas não identifiquei o município ou métrica exata.</p>
          <p>Você pode tentar perguntas como:</p>
          <ul class="list-disc pl-4 space-y-1 text-slate-300">
            <li><em>"Quantos votos Marquito fez em Florianópolis?"</em></li>
            <li><em>"Como foi o resultado em Joinville, Blumenau ou Criciúma?"</em></li>
            <li><em>"Compare os anos de 2018, 2022 e 2026"</em></li>
            <li><em>"O que aconteceu na Seção 0235 de São José?"</em></li>
            <li><em>"Quais são as cidades onde ele mais cresceu?"</em></li>
          </ul>
        </div>
      `;
    }

    function limparHistoricoChat() {
      const container = document.getElementById('chat-messages-container');
      container.innerHTML = `
        <div class="flex items-start gap-3">
          <div class="w-8 h-8 rounded-lg bg-emerald-600/30 text-emerald-400 flex items-center justify-center shrink-0 border border-emerald-500/30">
            🌱
          </div>
          <div class="bg-slate-950 p-4 rounded-2xl rounded-tl-sm border border-slate-800 max-w-[85%] text-xs space-y-2 leading-relaxed text-slate-200">
            <p>Histórico limpo. Como posso ajudar na análise eleitoral do Marquito?</p>
          </div>
        </div>
      `;
    }

    function initUI() {
      if (AppState.data) {
        atualizarDrillDown('Florianópolis');
      }
    }

    function renderDashboard() {
      updateKPICards();
    }
  </script>
</body>
</html>