Profpatsch/users/Profpatsch/modular-flyer/main.go
   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
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"

	qrcode "github.com/skip2/go-qrcode"
	_ "modernc.org/sqlite"
)

// The template DB is the baseline — it already contains:
//   locations, routes, visits, config, sessions, schema_version
// Migrations are numbered from 1 and applied in order.
// Each migration is a single SQL statement.

var dbMigrations = []struct {
	version int
	sql     string
}{
	{1, `ALTER TABLE locations ADD COLUMN route_updated_at INTEGER NOT NULL DEFAULT 0`},
	{2, `ALTER TABLE locations ADD COLUMN created_by TEXT`},
	{3, `ALTER TABLE locations ADD COLUMN created_at INTEGER`},
	{4, `ALTER TABLE visits ADD COLUMN visit_type INTEGER NOT NULL DEFAULT 1`},
	{5, `ALTER TABLE sessions ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0`},
	{6, `CREATE TABLE IF NOT EXISTS invite_tokens (
		token      TEXT PRIMARY KEY,
		username   TEXT NOT NULL,
		is_admin   INTEGER NOT NULL DEFAULT 0,
		created_at INTEGER NOT NULL,
		expires_at INTEGER NOT NULL,
		used_at    INTEGER
	)`},
}

const initSchema = `
CREATE TABLE IF NOT EXISTS schema_version (
  version    INTEGER PRIMARY KEY,
  applied_at INTEGER NOT NULL
);
`

func openDB(path string) *sql.DB {
	db, err := sql.Open("sqlite", path)
	if err != nil {
		log.Panicf("open db %q: %v", path, err)
	}
	if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
		log.Panicf("pragma foreign_keys: %v", err)
	}
	if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
		log.Panicf("pragma journal_mode: %v", err)
	}
	// ensure schema_version table exists (needed even on fresh template DBs)
	if _, err := db.Exec(initSchema); err != nil {
		log.Panicf("initSchema: %v", err)
	}
	// apply any pending migrations
	for _, m := range dbMigrations {
		var count int
		db.QueryRow(`SELECT COUNT(*) FROM schema_version WHERE version = ?`, m.version).Scan(&count)
		if count > 0 {
			continue // already applied
		}
		if _, err := db.Exec(m.sql); err != nil {
			log.Panicf("migration %d: %v", m.version, err)
		}
		mustExec(db, `INSERT INTO schema_version (version, applied_at) VALUES (?, ?)`,
			m.version, time.Now().Unix())
		log.Printf("applied migration %d", m.version)
	}
	return db
}

func mustExec(db *sql.DB, query string, args ...any) {
	if _, err := db.Exec(query, args...); err != nil {
		log.Panicf("exec %q: %v", query, err)
	}
}

const mapHTML = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Modular Flyer Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<link rel="stylesheet" href="https://unpkg.com/@geoman-io/leaflet-geoman-free@2.19.2/dist/leaflet-geoman.css"/>
<style>
  html, body, #map { height: 100%; margin: 0; padding: 0; }

  /* shared button base */
  .btn {
    border: none; border-radius: 6px; cursor: pointer;
    font-family: sans-serif; font-weight: 500;
    -webkit-tap-highlight-color: transparent;
    touch-action: manipulation; user-select: none;
  }
  .btn:active { opacity: 0.75; }

  /* top bar — username + hamburger */
  #top-bar {
    display: none;
    position: absolute; top: 12px; right: 12px; z-index: 1000;
    align-items: center; gap: 0;
  }
  #top-bar.visible { display: flex; }
  #user-label {
    background: white; border: 2px solid rgba(0,0,0,0.25);
    border-right: none;
    border-radius: 6px 0 0 6px;
    padding: 10px 14px; font-size: 14px; font-family: sans-serif;
    color: #333; white-space: nowrap;
    box-shadow: 0 2px 6px rgba(0,0,0,0.3);
    pointer-events: none;
  }
  #menu-btn {
    background: white; border: 2px solid rgba(0,0,0,0.25);
    border-radius: 0 6px 6px 0;
    padding: 10px 14px; font-size: 17px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.3);
  }

  /* dropdown menu */
  #menu-dropdown {
    display: none;
    position: absolute; top: 52px; right: 12px; z-index: 1001;
    background: white; border: 1px solid rgba(0,0,0,0.15);
    border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    min-width: 160px; overflow: hidden;
  }

  /* placement mode crosshair */
  #crosshair {
    display: none;
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000;
    font-size: 36px;
    line-height: 1;
    pointer-events: none;
    color: #e63946;
    text-shadow: 0 0 4px rgba(255,255,255,0.8);
  }
  #crosshair.active { display: block; }

  /* placement action bar */
  #place-bar {
    display: none; align-items: center; gap: 12px;
    padding: 12px 16px;
  }
  #place-bar.open { display: flex; }
  #place-confirm-btn {
    flex: 1; background: #4a9; color: #fff;
    padding: 12px; font-size: 16px; border-radius: 6px;
  }
  #place-cancel-btn {
    background: #444; color: #ccc;
    padding: 12px 16px; font-size: 15px; border-radius: 6px;
  }

  /* place form sheet */
  #place-sheet { padding: 20px 16px 16px; }
  #place-sheet h3 { margin: 0 0 14px; font-size: 16px; color: #aaa; font-weight: normal; text-transform: uppercase; letter-spacing: 0.05em; }
  #place-name {
    width: 100%; box-sizing: border-box;
    padding: 12px; font-size: 16px; border-radius: 6px;
    border: 1px solid #444; background: #2a2a2a; color: #eee;
    margin-bottom: 12px;
  }
  #place-comment {
    width: 100%; box-sizing: border-box;
    padding: 12px; font-size: 16px; border-radius: 6px;
    border: 1px solid #444; background: #2a2a2a; color: #eee;
    margin-bottom: 12px;
  }
  #place-visited-btn   { background: #4a9;  color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #place-na-btn        { background: #222;  color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #place-comment-btn   { background: #e6a800; color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #place-only-btn      { background: #555;  color: #ccc; padding: 12px 24px; font-size: 15px; width: 100%; margin-bottom: 8px; }
  #place-sheet-cancel  { background: #333;  color: #aaa; padding: 12px 24px; font-size: 15px; width: 100%; }

  /* delete confirm sheet */
  #delete-sheet { padding: 20px 16px 16px; }
  #delete-sheet p { margin: 0 0 16px; font-size: 15px; color: #aaa; }
  #delete-sheet b { color: #fff; }
  #delete-confirm-btn { background: #c0392b; color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #delete-cancel-btn  { background: #333; color: #aaa; padding: 12px 24px; font-size: 15px; width: 100%; }

  /* legend */
  #legend {
    position: absolute; bottom: 24px; left: 12px; z-index: 1000;
    background: white; border: 1px solid rgba(0,0,0,0.15);
    border-radius: 6px; box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    padding: 8px 12px; font-family: sans-serif; font-size: 12px;
    color: #333; line-height: 1.8;
  }
  .legend-row { display: flex; align-items: center; gap: 8px; }
  .legend-dot {
    width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0;
    border: 2px solid #fff; box-shadow: 0 0 0 1px rgba(0,0,0,0.2);
  }
  #menu-dropdown.open { display: block; }
  #menu-dropdown button {
    display: block; width: 100%; padding: 14px 18px;
    text-align: left; font-size: 16px; color: #222;
    background: transparent; border: none; border-bottom: 1px solid #eee;
    cursor: pointer; touch-action: manipulation;
    -webkit-tap-highlight-color: transparent;
  }
  #menu-dropdown button:last-child { border-bottom: none; }
  #menu-dropdown button:active { background: #f4f4f4; }

  /* bottom sheet — shared */
  .sheet {
    display: none;
    position: absolute; bottom: 0; left: 0; right: 0;
    z-index: 1001;
    background: #1a1a1a; color: #eee;
    font-family: sans-serif;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.5);
  }
  .sheet.open { display: block; }

  /* route picker sheet */
  #route-sheet { padding: 0; }
  #route-sheet-title {
    padding: 14px 16px 10px;
    font-size: 13px; color: #888; text-transform: uppercase; letter-spacing: 0.05em;
    border-bottom: 1px solid #2a2a2a;
  }
  #route-list { list-style: none; margin: 0; padding: 0; }
  #route-list li {
    display: flex; align-items: center; gap: 12px;
    padding: 14px 16px; border-bottom: 1px solid #2a2a2a;
    cursor: pointer; touch-action: manipulation;
    -webkit-tap-highlight-color: transparent;
  }
  #route-list li:active { background: #252525; }
  .route-dot {
    width: 18px; height: 18px; border-radius: 50%;
    flex-shrink: 0; border: 2px solid rgba(255,255,255,0.3);
  }
  .route-label { font-size: 16px; flex: 1; }
  .route-count { font-size: 13px; color: #666; }
  #new-route-btn {
    width: 100%; padding: 16px; font-size: 16px; color: #4af;
    background: transparent; text-align: left;
    border-top: 1px solid #333;
  }
  #sheet-cancel-btn {
    width: 100%; padding: 14px; font-size: 15px; color: #888;
    background: #111; text-align: center;
    border-top: 1px solid #222;
  }

  /* draw bar — shown while drawing */
  #draw-bar {
    padding: 12px 16px;
    display: none; align-items: center; gap: 12px;
  }
  #draw-bar.open { display: flex; }
  #draw-color-dot {
    width: 16px; height: 16px; border-radius: 50%; flex-shrink: 0;
  }
  #draw-label { flex: 1; font-size: 15px; color: #aaa; }
  #draw-count { font-size: 15px; color: #fff; font-weight: 600; }
  #finish-btn {
    background: #4a9; color: #fff;
    padding: 10px 20px; font-size: 16px;
  }
  #draw-cancel-btn {
    background: #444; color: #ccc;
    padding: 10px 14px; font-size: 15px;
  }

  /* besucht sheet */
  #visit-sheet { padding: 20px 16px 16px; }
  #visit-sheet h3 { margin: 0 0 4px; font-size: 16px; color: #fff; }
  #visit-sheet-street { font-size: 13px; color: #888; margin-bottom: 14px; }
  #visit-comment {
    width: 100%; box-sizing: border-box;
    padding: 12px; font-size: 16px; border-radius: 6px;
    border: 1px solid #444; background: #2a2a2a; color: #eee;
    margin-bottom: 12px;
  }
  #visit-submit-btn { background: #4a9; color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #visit-cancel-btn { background: #333; color: #aaa; padding: 12px 24px; font-size: 15px; width: 100%; }

  /* einladen sheet */
  #invite-sheet { padding: 20px 16px 16px; }
  #invite-sheet h3 { margin: 0 0 16px; font-size: 16px; color: #aaa; font-weight: normal; text-transform: uppercase; letter-spacing: 0.05em; }
  #invite-sheet input[type=text] {
    width: 100%; box-sizing: border-box;
    padding: 12px; font-size: 16px; border-radius: 6px;
    border: 1px solid #444; background: #2a2a2a; color: #eee;
    margin-bottom: 12px;
  }
  #invite-sheet label { display: flex; align-items: center; gap: 10px; font-size: 15px; color: #aaa; margin-bottom: 16px; cursor: pointer; }
  #invite-sheet input[type=checkbox] { width: 18px; height: 18px; cursor: pointer; }
  #invite-submit-btn { background: #4a9; color: #fff; padding: 12px 24px; font-size: 16px; width: 100%; margin-bottom: 8px; }
  #invite-cancel-btn { background: #333; color: #aaa; padding: 12px 24px; font-size: 15px; width: 100%; }

  /* einladen waiting state */
  #invite-waiting { display: none; padding: 20px 16px 16px; }
  #invite-waiting.open { display: block; }
  #invite-qr {
    display: flex; justify-content: center; margin-bottom: 14px;
  }
  #invite-qr img { border-radius: 8px; width: 220px; height: 220px; }
  #invite-url-box {
    background: #2a2a2a; border-radius: 6px; padding: 12px;
    font-size: 12px; color: #4af; word-break: break-all;
    margin-bottom: 10px; user-select: all;
  }
  #invite-copy-btn { background: #333; color: #eee; padding: 10px 20px; font-size: 15px; width: 100%; margin-bottom: 12px; }
  #invite-status { text-align: center; color: #888; font-size: 14px; margin-bottom: 14px; }
  #invite-wait-cancel-btn { background: #333; color: #aaa; padding: 12px; font-size: 15px; width: 100%; }

  /* toast for route selection */
  #route-toast {
    display: none;
    position: absolute; bottom: 0; left: 0; right: 0;
    z-index: 1000;
    background: #1a1a1a; color: #eee;
    font-family: sans-serif;
    padding: 14px 16px;
    align-items: center; gap: 12px;
    box-shadow: 0 -2px 8px rgba(0,0,0,0.4);
  }
  #route-toast.open { display: flex; }
  #toast-dot { width: 14px; height: 14px; border-radius: 50%; flex-shrink: 0; }
  #toast-label { flex: 1; font-size: 15px; }
  #toast-close {
    background: transparent; color: #888;
    font-size: 22px; padding: 0 4px; line-height: 1;
  }
</style>
</head>
<body>
<div id="map"></div>

<!-- auth overlay -->
<div id="auth-overlay" style="display:flex;position:absolute;inset:0;z-index:2000;background:rgba(0,0,0,0.85);align-items:center;justify-content:center;">
  <div style="color:#eee;font-family:sans-serif;font-size:18px;text-align:center;padding:32px;white-space:pre-line;" id="auth-msg">Wird geladen…</div>
</div>

<!-- top bar: username + hamburger (admin only) -->
<div id="top-bar">
  <div id="user-label"></div>
  <button id="menu-btn" class="btn" onclick="toggleMenu()">&#9776;</button>
</div>

<!-- legend -->
<div id="legend">
  <div class="legend-row"><div class="legend-dot" style="background:#fff;border-color:#555;box-shadow:0 0 0 1px rgba(0,0,0,0.3)"></div> Besucht</div>
  <div class="legend-row"><div class="legend-dot" style="background:#222;border-color:#fff"></div> Nicht möglich</div>
  <div class="legend-row"><div class="legend-dot" style="background:#3a7bd5;border-color:#f1c40f;box-shadow:0 0 0 1px #f1c40f"></div> Kommentar</div>
</div>
<div id="menu-dropdown">
  <button onclick="menuAction('place')">Ort Hinzufügen</button>
  <button id="menu-route" onclick="menuAction('route')" style="display:none">Route zuweisen</button>
  <button id="menu-invite" onclick="menuAction('invite')" style="display:none">Einladen</button>
</div>

<!-- Crosshair -->
<div id="crosshair">⊕</div>

<!-- Placement action bar -->
<div id="place-bar" class="sheet">
  <button id="place-cancel-btn" class="btn" onclick="cancelPlacement()">✕</button>
  <button id="place-confirm-btn" class="btn" onclick="confirmPlacement()">Hier platzieren →</button>
</div>

<!-- Placement form sheet -->
<div id="place-sheet" class="sheet">
  <h3>Ort Hinzufügen</h3>
  <input type="text" id="place-name" placeholder="Name (erforderlich)" autocomplete="off" autocorrect="off"/>
  <input type="text" id="place-comment" placeholder="Kommentar (optional)" autocomplete="off"/>
  <button id="place-visited-btn" class="btn" onclick="submitPlace(1)">Besucht ✓</button>
  <button id="place-na-btn" class="btn" onclick="submitPlace(2)">Nicht möglich 🚫</button>
  <button id="place-comment-btn" class="btn" onclick="submitPlace(0)">Kommentar 💬</button>
  <button id="place-only-btn" class="btn" onclick="submitPlace(null)">Nur platzieren</button>
  <button id="place-sheet-cancel" class="btn" onclick="cancelPlaceSheet()">Abbrechen</button>
</div>

<!-- Delete confirm sheet -->
<div id="delete-sheet" class="sheet">
  <p>Ort wirklich löschen?<br/><b id="delete-name"></b></p>
  <button id="delete-confirm-btn" class="btn" onclick="confirmDelete()">Ja, löschen</button>
  <button id="delete-cancel-btn" class="btn" onclick="closeDeleteSheet()">Abbrechen</button>
</div>

<!-- Route picker sheet -->
<div id="route-sheet" class="sheet">
  <div id="route-sheet-title">Route zuweisen</div>
  <ul id="route-list"></ul>
  <button id="new-route-btn" class="btn" onclick="createRoute()">+ Neue Route</button>
  <button id="sheet-cancel-btn" class="btn" onclick="closeRouteSheet()">Abbrechen</button>
</div>

<!-- Draw bar -->
<div id="draw-bar" class="sheet">
  <div id="draw-color-dot"></div>
  <div id="draw-label">Bereich auswählen</div>
  <div id="draw-count">0</div>
  <button id="finish-btn" class="btn" onclick="finishDrawing()">Fertig ✓</button>
  <button id="draw-cancel-btn" class="btn" onclick="cancelDrawing()">✕</button>
</div>

<!-- Besucht sheet -->
<div id="visit-sheet" class="sheet">
  <h3 id="visit-sheet-name"></h3>
  <div id="visit-sheet-street"></div>
  <input type="text" id="visit-comment" placeholder="Kommentar (optional)" autocomplete="off"/>
  <button id="visit-submit-btn" class="btn" onclick="submitVisit(1)">Besucht ✓</button>
  <button id="visit-na-btn" class="btn" onclick="submitVisit(2)" style="background:#222;color:#fff;padding:12px 24px;font-size:16px;width:100%;margin-bottom:8px;">Nicht möglich 🚫</button>
  <button id="visit-comment-btn" class="btn" onclick="submitVisit(0)" style="background:#e6a800;color:#fff;padding:12px 24px;font-size:16px;width:100%;margin-bottom:8px;">Kommentar 💬</button>
  <button id="visit-cancel-btn" class="btn" onclick="closeVisitSheet()">Abbrechen</button>
</div>

<!-- Einladen sheet -->
<div id="invite-sheet" class="sheet">
  <h3>Einladen</h3>
  <input type="text" id="invite-username" placeholder="Benutzername" autocomplete="off" autocorrect="off" autocapitalize="off"/>
  <label><input type="checkbox" id="invite-is-admin"/> Admin</label>
  <button id="invite-submit-btn" class="btn" onclick="submitInvite()">Einladen</button>
  <button id="invite-cancel-btn" class="btn" onclick="closeInviteSheet()">Abbrechen</button>
</div>

<!-- Einladen waiting state -->
<div id="invite-waiting" class="sheet">
  <div style="padding:20px 16px 0">
    <div id="invite-qr"><img id="invite-qr-img" src="" alt="QR Code"/></div>
    <div id="invite-url-box"></div>
    <button id="invite-copy-btn" class="btn" onclick="copyInviteUrl()">Link kopieren</button>
    <div id="invite-status">⏳ Warte auf Scan…</div>
  </div>
  <button id="invite-wait-cancel-btn" class="btn" onclick="cancelInviteWait()">Abbrechen</button>
</div>

<!-- Route selected toast -->
<div id="route-toast">
  <div id="toast-dot"></div>
  <div id="toast-label"></div>
  <button id="toast-close" class="btn" onclick="dismissToast()">×</button>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/@geoman-io/leaflet-geoman-free@2.19.2/dist/leaflet-geoman.min.js"></script>
<script>
var map = L.map('map', { zoomControl: true }).setView([48.3705, 10.8978], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '© <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);

// ── state ──────────────────────────────────────────────────────────────────
var locations = [];   // apiLocation[]
var routes = [];      // apiRoute[]
var markers = {};     // location id → L.CircleMarker
var selected = new Set(); // location indices currently selected for drawing
var activeRouteId = null; // route being drawn into
var activeRouteColor = null;

// ── load state ─────────────────────────────────────────────────────────────
var pollingStarted = false;

function loadState() {
  return fetch('/api/state')
    .then(function(r) { return r.json(); })
    .then(function(state) {
      locations = state.locations || [];
      routes = state.routes || [];
      renderMarkers();
      if (!pollingStarted) {
        pollingStarted = true;
        visitsSince = Math.floor(Date.now() / 1000);
        pollUpdates();
      }
    });
}

// ── markers ────────────────────────────────────────────────────────────────
function markerFillColor(loc) {
  if (loc.visited)       return '#fff';     // white = besucht
  if (loc.not_available) return '#222';     // black = nicht möglich
  return loc.color || '#3a7bd5';            // route color or default blue
}

function markerBorderColor(loc) {
  if (loc.has_comment) return '#f1c40f';       // yellow = has comment
  if (loc.visited)     return loc.color || '#555';  // route color border for visited
  return '#fff';
}

function markerStyle(loc, highlight) {
  var radius = (loc.route_id ? 8 : 7)
             + (loc.visited || loc.not_available || loc.has_comment ? 1 : 0)
             + (highlight ? 4 : 0);
  return {
    radius: radius,
    fillColor: markerFillColor(loc),
    color: markerBorderColor(loc),
    weight: loc.has_comment ? 3 : 2,
    fillOpacity: 0.95,
    opacity: 1,
  };
}

function relativeTime(unixTs) {
  var secs = Math.floor(Date.now() / 1000) - unixTs;
  if (secs < 60) return 'gerade eben';
  if (secs < 3600) return 'vor ' + Math.floor(secs/60) + ' Min.';
  if (secs < 86400) return 'vor ' + Math.floor(secs/3600) + ' Std.';
  return 'vor ' + Math.floor(secs/86400) + ' Tag(en)';
}

function buildPopupHTML(loc) {
  var html = '<b>' + loc.name + '</b>';
  if (loc.created_by) {
    html += '<br/><small style="color:#888">Hinzugefügt von ' + loc.created_by + '</small>';
  } else if (loc.street) {
    html += '<br/>' + loc.street +
      '<br/><small>' + loc.postal_code + ' ' + loc.district + '</small>';
  }
  if (loc.visits && loc.visits.length > 0) {
    html += '<hr style="margin:6px 0;border-color:#ddd"/>';
    loc.visits.forEach(function(v) {
      var icon = v.visit_type === 1 ? '✓' : v.visit_type === 2 ? '🚫' : '💬';
      html += '<div style="font-size:12px;margin-bottom:2px">' + icon + ' <b>' + v.username + '</b> — ' + relativeTime(v.visited_at);
      if (v.comment) html += '<br/><span style="color:#666">"' + v.comment + '"</span>';
      html += '</div>';
    });
  }
  html += '<br/><button onclick="openVisitSheet(' + loc.id + ')" ' +
    'style="margin-top:4px;padding:6px 12px;background:#4a9;color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:13px">' +
    'Eintrag hinzufügen</button>';
  if (isAdmin) {
    html += ' <button onclick="openDeleteSheet(' + loc.id + ',\'' + loc.name.replace(/'/g,"\\'") + '\')" ' +
      'style="margin-top:4px;padding:6px 12px;background:#333;color:#aaa;border:none;border-radius:4px;cursor:pointer;font-size:13px">' +
      'Löschen</button>';
  }
  return html;
}

function addMarker(loc) {
  if (loc.lat === null || loc.lon === null) return;
  var m = L.circleMarker([loc.lat, loc.lon], markerStyle(loc, false));
  m.bindPopup(buildPopupHTML(loc), { maxWidth: 260 });
  m.on('click', function() { onMarkerClick(loc); });
  m.addTo(map);
  markers[loc.id] = m;
}

function renderMarkers() {
  Object.values(markers).forEach(function(m) { m.remove(); });
  markers = {};
  locations.forEach(function(loc) { addMarker(loc); });
}

function onMarkerClick(loc) {
  // popup opens automatically via Leaflet click
}

function highlightRoute(routeId) {
  locations.forEach(function(loc) {
    if (!markers[loc.id]) return;
    markers[loc.id].setStyle(markerStyle(loc, loc.route_id === routeId));
  });
}

function clearHighlight() {
  locations.forEach(function(loc) {
    if (!markers[loc.id]) return;
    markers[loc.id].setStyle(markerStyle(loc, false));
  });
}

// ── route toast ────────────────────────────────────────────────────────────
function showRouteToast(routeId) {
  var route = routes.find(function(r) { return r.id === routeId; });
  if (!route) return;
  var count = locations.filter(function(l) { return l.route_id === routeId; }).length;
  document.getElementById('toast-dot').style.background = route.color;
  document.getElementById('toast-label').textContent = 'Route ' + routeId + ' · ' + count + ' Orte';
  document.getElementById('route-toast').classList.add('open');
  highlightRoute(routeId);
}

function dismissToast() {
  document.getElementById('route-toast').classList.remove('open');
  clearHighlight();
}

// ── route sheet ────────────────────────────────────────────────────────────
// ── hamburger menu ─────────────────────────────────────────────────────────
function toggleMenu() {
  var dd = document.getElementById('menu-dropdown');
  dd.classList.toggle('open');
}

function closeMenu() {
  document.getElementById('menu-dropdown').classList.remove('open');
}

function menuAction(action) {
  closeMenu();
  if (action === 'place') startPlacement();
  if (action === 'route') openRouteSheet();
  if (action === 'invite') openInviteSheet();
}

// close dropdown when tapping outside
document.addEventListener('click', function(e) {
  var btn = document.getElementById('menu-btn');
  var dd = document.getElementById('menu-dropdown');
  if (!btn.contains(e.target) && !dd.contains(e.target)) closeMenu();
});

function openRouteSheet() {
  dismissToast();
  renderRouteList();
  document.getElementById('route-sheet').classList.add('open');
}

function closeRouteSheet() {
  document.getElementById('route-sheet').classList.remove('open');
}

function renderRouteList() {
  var ul = document.getElementById('route-list');
  ul.innerHTML = '';
  routes.forEach(function(route) {
    var li = document.createElement('li');
    li.innerHTML =
      '<div class="route-dot" style="background:' + route.color + '"></div>' +
      '<div class="route-label">Route ' + route.id + '</div>' +
      '<div class="route-count">' + route.count + ' Orte</div>';
    li.onclick = function() { pickRoute(route.id, route.color); };
    ul.appendChild(li);
  });
}

function pickRoute(routeId, color) {
  closeRouteSheet();
  startDrawing(routeId, color);
}

function createRoute() {
  fetch('/api/routes', { method: 'POST' })
    .then(function(r) { return r.json(); })
    .then(function(route) {
      routes.push({ id: route.id, color: route.color, count: 0 });
      closeRouteSheet();
      startDrawing(route.id, route.color);
    });
}

// ── drawing ────────────────────────────────────────────────────────────────
function startDrawing(routeId, color) {
  activeRouteId = routeId;
  activeRouteColor = color;
  selected.clear();
  document.getElementById('draw-color-dot').style.background = color;
  document.getElementById('draw-count').textContent = '0';
  document.getElementById('draw-bar').classList.add('open');
  document.getElementById('top-bar').classList.remove('visible');

  map.pm.setGlobalOptions({ continueDrawing: false, snappable: false,
    pathOptions: { color: color, fillColor: color, fillOpacity: 0.15 } });
  map.pm.enableDraw('Polygon');
}

map.on('pm:create', function(e) {
  selectWithinLayer(e.layer);
  map.removeLayer(e.layer);
  // re-arm for another polygon pass
  map.pm.enableDraw('Polygon');
});

function finishDrawing() {
  // auto-close in-progress polygon
  var draw = map.pm.Draw.Polygon;
  if (draw && draw._finishShape) draw._finishShape();
  map.pm.disableDraw();

  if (selected.size === 0) { cancelDrawing(); return; }

  var ids = Array.from(selected).map(function(idx) { return locations[idx].id; });
  fetch('/api/assign', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ route_id: activeRouteId, location_ids: ids }),
  }).then(function() {
    return loadState();
  }).then(function() {
    selected.clear();
    activeRouteId = null;
    activeRouteColor = null;
    document.getElementById('draw-bar').classList.remove('open');
    document.getElementById('top-bar').classList.add('visible');
  });
}

function cancelDrawing() {
  map.pm.disableDraw();
  selected.clear();
  // revert selected markers to their actual style
  renderMarkers();
  activeRouteId = null;
  activeRouteColor = null;
  document.getElementById('draw-bar').classList.remove('open');
  document.getElementById('top-bar').classList.add('visible');
}

function selectWithinLayer(layer) {
  var latlngs = layer.getLatLngs ? layer.getLatLngs() : null;
  if (!latlngs) return;
  var ring = (latlngs[0] && latlngs[0][0] && latlngs[0][0].lat !== undefined)
    ? latlngs[0] : latlngs;

  locations.forEach(function(loc, i) {
    if (loc.lat === null || loc.lon === null) return;
    if (pointInPolygon([loc.lat, loc.lon], ring)) {
      selected.add(i);
      // preview the route color on the marker
      if (markers[loc.id]) {
        markers[loc.id].setStyle({
          fillColor: activeRouteColor, color: '#fff',
          radius: 9, fillOpacity: 0.95, weight: 2, opacity: 1,
        });
      }
    }
  });
  document.getElementById('draw-count').textContent = selected.size;
}

function pointInPolygon(point, polygon) {
  var x = point[1], y = point[0];
  var inside = false;
  for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    var xi = polygon[i].lng, yi = polygon[i].lat;
    var xj = polygon[j].lng, yj = polygon[j].lat;
    if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi))
      inside = !inside;
  }
  return inside;
}

// ── besucht ────────────────────────────────────────────────────────────────
var visitLocationId = null;

function openVisitSheet(locId) {
  // close any open leaflet popup
  map.closePopup();
  visitLocationId = locId;
  var loc = locations.find(function(l) { return l.id === locId; });
  document.getElementById('visit-sheet-name').textContent = loc ? loc.name : '';
  document.getElementById('visit-sheet-street').textContent = loc ? loc.street : '';
  document.getElementById('visit-comment').value = '';
  document.getElementById('visit-sheet').classList.add('open');
  setTimeout(function() { document.getElementById('visit-comment').focus(); }, 100);
}

function closeVisitSheet() {
  document.getElementById('visit-sheet').classList.remove('open');
  visitLocationId = null;
}

// applyVisit merges a visit record into a location object and updates its marker.
// Deduplicates by (username, visited_at).
function applyVisit(loc, v) {
  if (!loc.visits) loc.visits = [];
  var exists = loc.visits.some(function(x) {
    return x.username === v.username && x.visited_at === v.visited_at;
  });
  if (!exists) loc.visits.unshift(v);
  if (v.visit_type === 1) loc.visited = true;
  if (v.visit_type === 2) loc.not_available = true;
  if (v.comment) loc.has_comment = true;
  var m = markers[loc.id];
  if (m) {
    m.setStyle(markerStyle(loc, false));
    m.setPopupContent(buildPopupHTML(loc));
  }
}

function submitVisit(visitType) {
  if (!visitLocationId) return;
  var comment = document.getElementById('visit-comment').value.trim();
  if (visitType === 0 && !comment) return;
  fetch('/api/visits', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ location_id: visitLocationId, comment: comment, visit_type: visitType }),
  }).then(function() {
    var loc = locations.find(function(l) { return l.id === visitLocationId; });
    if (loc) applyVisit(loc, { username: currentUsername, visited_at: Math.floor(Date.now()/1000), comment: comment, visit_type: visitType });
    closeVisitSheet();
  });
}

// ── long-poll updates ───────────────────────────────────────────────────────
var visitsSince = Math.floor(Date.now() / 1000);
var currentUsername = '';

var updatesAbortController = null;

function pollUpdates() {
  updatesAbortController = new AbortController();
  fetch('/api/updates?since=' + visitsSince, { signal: updatesAbortController.signal })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      if (data.visits && data.visits.length > 0) {
        data.visits.forEach(function(v) {
          var loc = locations.find(function(l) { return l.id === v.location_id; });
          if (loc) applyVisit(loc, v);
          if (v.visited_at > visitsSince) visitsSince = v.visited_at;
        });
      }
      if (data.route_changes && data.route_changes.length > 0) {
        var routeChangeTime = Math.floor(Date.now() / 1000);
        if (routeChangeTime > visitsSince) visitsSince = routeChangeTime;
        data.route_changes.forEach(function(rc) {
          var loc = locations.find(function(l) { return l.id === rc.location_id; });
          if (loc) {
            loc.route_id = rc.route_id;
            loc.color = rc.color || null;
            if (markers[loc.id]) {
              markers[loc.id].setStyle(markerStyle(loc, false));
              markers[loc.id].setPopupContent(buildPopupHTML(loc));
            }
          }
        });
        renderRouteList();
      }
      if (data.new_locations && data.new_locations.length > 0) {
        var newLocTime = Math.floor(Date.now() / 1000);
        if (newLocTime > visitsSince) visitsSince = newLocTime;
        data.new_locations.forEach(function(loc) {
          // skip if we already have it (e.g. the creator)
          if (locations.some(function(l) { return l.id === loc.id; })) return;
          loc.visits = loc.visits || [];
          locations.push(loc);
          addMarker(loc);
        });
      }
      pollUpdates(); // re-arm immediately
    })
    .catch(function(e) {
      if (e.name === 'AbortError') return;
      setTimeout(pollUpdates, 3000);
    });
}

// ── einladen ───────────────────────────────────────────────────────────────
var inviteShareURL = '';
var inviteAbortController = null;

function openInviteSheet() {
  document.getElementById('invite-username').value = '';
  document.getElementById('invite-is-admin').checked = false;
  document.getElementById('invite-sheet').classList.add('open');
  document.getElementById('invite-waiting').classList.remove('open');
  setTimeout(function() { document.getElementById('invite-username').focus(); }, 100);
}

function closeInviteSheet() {
  document.getElementById('invite-sheet').classList.remove('open');
}

function submitInvite() {
  var username = document.getElementById('invite-username').value.trim();
  if (!username) return;
  var isAdminInvite = document.getElementById('invite-is-admin').checked;
  fetch('/api/invite', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: username, is_admin: isAdminInvite }),
  }).then(function(r) { return r.json(); })
  .then(function(data) {
    inviteShareURL = data.share_url;
    closeInviteSheet();
    showInviteWaiting(username, data.since, data.qr_url);
  });
}

function showInviteWaiting(username, since, qrURL) {
  document.getElementById('invite-url-box').textContent = inviteShareURL;
  document.getElementById('invite-qr-img').src = '/api/qr?url=' + encodeURIComponent(qrURL);
  document.getElementById('invite-status').textContent = '⏳ Warte auf Verbindung…';
  document.getElementById('invite-waiting').classList.add('open');
  inviteAbortController = new AbortController();
  fetch('/api/invite/status?username=' + encodeURIComponent(username) + '&since=' + since, {
    signal: inviteAbortController.signal,
  }).then(function(r) { return r.json(); })
  .then(function() {
    // scanned or timed out — reset silently either way
    document.getElementById('invite-waiting').classList.remove('open');
    inviteAbortController = null;
  }).catch(function(e) {
    if (e.name !== 'AbortError') console.error(e);
  });
}

function cancelInviteWait() {
  if (inviteAbortController) { inviteAbortController.abort(); inviteAbortController = null; }
  document.getElementById('invite-waiting').classList.remove('open');
}

function copyInviteUrl() {
  navigator.clipboard.writeText(inviteShareURL).then(function() {
    var btn = document.getElementById('invite-copy-btn');
    btn.textContent = 'Kopiert ✓';
    setTimeout(function() { btn.textContent = 'Link kopieren'; }, 2000);
  });
}

// ── ort löschen ────────────────────────────────────────────────────────────
var deleteLocationId = null;

function openDeleteSheet(locId, name) {
  map.closePopup();
  deleteLocationId = locId;
  document.getElementById('delete-name').textContent = name;
  document.getElementById('delete-sheet').classList.add('open');
}

function closeDeleteSheet() {
  document.getElementById('delete-sheet').classList.remove('open');
  deleteLocationId = null;
}

function confirmDelete() {
  if (!deleteLocationId) return;
  fetch('/api/locations/' + deleteLocationId, { method: 'DELETE' })
    .then(function(r) {
      if (!r.ok) { alert('Fehler beim Löschen'); return; }
      // remove from local state
      var idx = locations.findIndex(function(l) { return l.id === deleteLocationId; });
      if (idx >= 0) locations.splice(idx, 1);
      if (markers[deleteLocationId]) { markers[deleteLocationId].remove(); delete markers[deleteLocationId]; }
      closeDeleteSheet();
    });
}

// ── ort hinzufügen ─────────────────────────────────────────────────────────
var placeLat = 0, placeLon = 0;

function startPlacement() {
  document.getElementById('crosshair').classList.add('active');
  document.getElementById('place-bar').classList.add('open');
  document.getElementById('top-bar').classList.remove('visible');
}

function cancelPlacement() {
  document.getElementById('crosshair').classList.remove('active');
  document.getElementById('place-bar').classList.remove('open');
  document.getElementById('top-bar').classList.add('visible');
}

function confirmPlacement() {
  var center = map.getCenter();
  placeLat = center.lat;
  placeLon = center.lng;
  document.getElementById('crosshair').classList.remove('active');
  document.getElementById('place-bar').classList.remove('open');
  document.getElementById('place-name').value = '';
  document.getElementById('place-comment').value = '';
  document.getElementById('place-sheet').classList.add('open');
  setTimeout(function() { document.getElementById('place-name').focus(); }, 100);
}

function cancelPlaceSheet() {
  document.getElementById('place-sheet').classList.remove('open');
  document.getElementById('top-bar').classList.add('visible');
}

function submitPlace(visitType) {
  var name = document.getElementById('place-name').value.trim();
  if (!name) { document.getElementById('place-name').focus(); return; }
  var comment = document.getElementById('place-comment').value.trim();
  if (visitType === 0 && !comment) { document.getElementById('place-comment').focus(); return; }

  var body = { name: name, lat: placeLat, lon: placeLon, comment: comment };
  if (visitType !== null) body.visit_type = visitType;

  fetch('/api/locations', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  }).then(function(r) { return r.json(); })
  .then(function(loc) {
    // add to local state and render marker immediately
    loc.visits = loc.visits || [];
    locations.push(loc);
    addMarker(loc);
    document.getElementById('place-sheet').classList.remove('open');
    document.getElementById('top-bar').classList.add('visible');
    // fly to the new marker and open its popup
    map.setView([loc.lat, loc.lon], Math.max(map.getZoom(), 16));
    if (markers[loc.id]) markers[loc.id].openPopup();
  });
}

// ── auth ───────────────────────────────────────────────────────────────────
var isAdmin = false;

function setUserLabel(username) {
  currentUsername = username;
  document.getElementById('user-label').textContent = 'Hi ' + username;
}

function showTopBar(admin) {
  document.getElementById('top-bar').classList.add('visible');
  // menu-btn always visible — all users get "Ort Hinzufügen"
  if (admin) {
    document.getElementById('menu-route').style.display = '';
    document.getElementById('menu-invite').style.display = '';
  }
}

function showOverlay(msg) {
  document.getElementById('auth-overlay').style.display = 'flex';
  document.getElementById('auth-msg').textContent = msg;
}

function hideOverlay() {
  document.getElementById('auth-overlay').style.display = 'none';
}

function stripWhoParam() {
  var url = new URL(window.location.href);
  if (url.searchParams.has('who')) {
    url.searchParams.delete('who');
    history.replaceState(null, '', url.pathname + (url.search === '?' ? '' : url.search));
  }
}

function boot() {
  var whoParam = new URL(window.location.href).searchParams.get('who');

  // try existing session first
  fetch('/api/me').then(function(r) {
    if (r.ok) return r.json();
    return { ok: false };
  }).then(function(me) {
    if (me.ok) {
      isAdmin = me.is_admin;
      stripWhoParam();
      hideOverlay();
      setUserLabel(me.username);
      showTopBar(isAdmin);
      loadState();
      return;
    }
    // no valid session — try ?who=
    if (!whoParam) {
      showOverlay('Du bist nicht eingeloggt.\nBitte jemanden um einen Zugangslink.');
      return;
    }
    var decoded;
    try {
      decoded = JSON.parse(atob(whoParam.replace(/-/g,'+').replace(/_/g,'/')));
    } catch(e) {
      showOverlay('Ungültiger Zugangslink.');
      return;
    }
    fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: decoded.username, token: decoded.token }),
    }).then(function(r) {
      if (!r.ok) {
        r.text().then(function(msg) {
          showOverlay(msg.trim() || 'Ungültiger Zugangslink.');
        });
        return null;
      }
      return r.json();
    }).then(function(data) {
      if (!data) return;
      isAdmin = data.is_admin;
      stripWhoParam();
      hideOverlay();
      setUserLabel(data.username);
      showTopBar(isAdmin);
      loadState();
    });
  });
}

// ── boot ───────────────────────────────────────────────────────────────────
boot();

</script>
</body>
</html>`

// ── auth helpers ─────────────────────────────────────────────────────────────

func randomBase64(bytes int) string {
	b := make([]byte, bytes)
	if _, err := rand.Read(b); err != nil {
		log.Panicf("rand: %v", err)
	}
	return base64.URLEncoding.EncodeToString(b)
}

// makeInviteToken creates a token in invite_tokens and returns the ?who= URL.
func makeInviteToken(db *sql.DB, baseURL, username string, isAdmin bool, ttl time.Duration) string {
	token := randomBase64(24) // 192 bits
	now := time.Now().Unix()
	isAdminInt := 0
	if isAdmin {
		isAdminInt = 1
	}
	mustExec(db,
		`INSERT INTO invite_tokens (token, username, is_admin, created_at, expires_at) VALUES (?,?,?,?,?)`,
		token, username, isAdminInt, now, now+int64(ttl.Seconds()),
	)
	who := base64.URLEncoding.EncodeToString([]byte(`{"username":"` + username + `","token":"` + token + `"}`))
	return strings.TrimRight(baseURL, "/") + "/?who=" + who
}

// setSessionCookie writes the session cookie with a 1-year MaxAge.
func setSessionCookie(w http.ResponseWriter, sessionID string) {
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    sessionID,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
		MaxAge:   365 * 24 * 60 * 60, // 1 year
	})
}

// requireSession checks the session cookie and returns (username, isAdmin, ok).
// If ok is false it has already written a 401 response.
func requireSession(db *sql.DB, w http.ResponseWriter, r *http.Request) (string, bool, bool) {
	cookie, err := r.Cookie("session")
	if err != nil {
		http.Error(w, "unauthorized", 401)
		return "", false, false
	}
	var username string
	var isAdmin int
	err = db.QueryRow(`SELECT username, is_admin FROM sessions WHERE session_id = ?`, cookie.Value).
		Scan(&username, &isAdmin)
	if err != nil {
		http.Error(w, "unauthorized", 401)
		return "", false, false
	}
	// Refresh the cookie on every authenticated request so it stays permanent.
	setSessionCookie(w, cookie.Value)
	return username, isAdmin == 1, true
}

// requireAdmin checks session and admin flag; writes 403 if not admin.
func requireAdmin(db *sql.DB, w http.ResponseWriter, r *http.Request) bool {
	_, isAdmin, ok := requireSession(db, w, r)
	if !ok {
		return false
	}
	if !isAdmin {
		http.Error(w, "forbidden", 403)
		return false
	}
	return true
}

var routePalette = []string{
	"#f4a261", "#457b9d", "#8338ec", "#c77dff",
	"#ffbe0b", "#4cc9f0", "#118ab2", "#a8dadc",
}

type apiVisit struct {
	Username  string `json:"username"`
	VisitedAt int64  `json:"visited_at"`
	Comment   string `json:"comment"`
	VisitType int    `json:"visit_type"` // 0=comment, 1=visited ok, 2=nicht möglich
}

type apiLocation struct {
	ID           int        `json:"id"`
	Name         string     `json:"name"`
	Street       string     `json:"street"`
	PostalCode   string     `json:"postal_code"`
	District     string     `json:"district"`
	Lat          *float64   `json:"lat"`
	Lon          *float64   `json:"lon"`
	RouteID      *int       `json:"route_id"`
	Color        *string    `json:"color"`
	Visited      bool       `json:"visited"`
	NotAvailable bool       `json:"not_available"`
	HasComment   bool       `json:"has_comment"`
	Visits       []apiVisit `json:"visits"`
	CreatedBy    *string    `json:"created_by"`
}

type apiRoute struct {
	ID    int    `json:"id"`
	Color string `json:"color"` // computed from id, not stored
	Count int    `json:"count"`
}

func routeColor(id int) string {
	return routePalette[(id-1)%len(routePalette)]
}

type apiState struct {
	Locations []apiLocation `json:"locations"`
	Routes    []apiRoute    `json:"routes"`
}

func queryState(db *sql.DB) (apiState, error) {
	var state apiState

	rows, err := db.Query(`
		SELECT l.id, l.name, COALESCE(l.street,''),
		       COALESCE(l.postal_code,''), COALESCE(l.district,''),
		       l.lat, l.lon, l.route_id, l.created_by
		FROM locations l
		ORDER BY l.id
	`)
	if err != nil {
		return state, err
	}
	defer rows.Close()
	for rows.Next() {
		var l apiLocation
		if err := rows.Scan(&l.ID, &l.Name, &l.Street, &l.PostalCode, &l.District,
			&l.Lat, &l.Lon, &l.RouteID, &l.CreatedBy); err != nil {
			return state, err
		}
		if l.RouteID != nil {
			c := routeColor(*l.RouteID)
			l.Color = &c
		}
		state.Locations = append(state.Locations, l)
	}
	if err := rows.Err(); err != nil {
		return state, err
	}

	// load all visits, newest first, and attach to locations
	vrows, err := db.Query(`
		SELECT location_id, username, visited_at, COALESCE(comment,''), visit_type
		FROM visits ORDER BY visited_at DESC
	`)
	if err != nil {
		return state, err
	}
	defer vrows.Close()
	locIdx := make(map[int]int, len(state.Locations))
	for i, l := range state.Locations {
		locIdx[l.ID] = i
	}
	for vrows.Next() {
		var locID int
		var v apiVisit
		if err := vrows.Scan(&locID, &v.Username, &v.VisitedAt, &v.Comment, &v.VisitType); err != nil {
			return state, err
		}
		if i, ok := locIdx[locID]; ok {
			state.Locations[i].Visits = append(state.Locations[i].Visits, v)
			if v.VisitType == 1 {
				state.Locations[i].Visited = true
			}
			if v.VisitType == 2 {
				state.Locations[i].NotAvailable = true
			}
			if v.Comment != "" {
				state.Locations[i].HasComment = true
			}
		}
	}
	if err := vrows.Err(); err != nil {
		return state, err
	}

	rrows, err := db.Query(`
		SELECT r.id, COUNT(l.id)
		FROM routes r
		LEFT JOIN locations l ON l.route_id = r.id
		GROUP BY r.id ORDER BY r.id
	`)
	if err != nil {
		return state, err
	}
	defer rrows.Close()
	for rrows.Next() {
		var r apiRoute
		if err := rrows.Scan(&r.ID, &r.Count); err != nil {
			return state, err
		}
		r.Color = routeColor(r.ID)
		state.Routes = append(state.Routes, r)
	}
	if err := rrows.Err(); err != nil {
		return state, err
	}

	return state, nil
}

func writeJSON(w http.ResponseWriter, v any) {
	b, err := json.Marshal(v)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(b)
}

const defaultBaseURL = "https://rolery.tail4db08.ts.net"

// startBackupLoop runs a goroutine that takes a VACUUM INTO backup every hour.
// Backups are written to <dbDir>/backups/modular-plakate-<timestamp>.db.
func startBackupLoop(db *sql.DB, dbPath string) {
	backupDir := filepath.Join(filepath.Dir(dbPath), "backups")
	if err := os.MkdirAll(backupDir, 0755); err != nil {
		log.Printf("backup: failed to create backup dir %q: %v", backupDir, err)
		return
	}
	go func() {
		for {
			time.Sleep(1 * time.Hour)
			ts := time.Now().Format("20060102-150405")
			dest := filepath.Join(backupDir, "modular-plakate-"+ts+".db")
			if _, err := db.Exec(`VACUUM INTO ?`, dest); err != nil {
				log.Printf("backup: VACUUM INTO %q failed: %v", dest, err)
			} else {
				log.Printf("backup: wrote %s", dest)
			}
		}
	}()
}

func cmdServe(dbPath, baseURL, addr string) {
	db := openDB(dbPath)
	startBackupLoop(db, dbPath)
	// clean up stale config passwords from old auth scheme
	mustExec(db, `DELETE FROM config WHERE key IN ('password_user','password_admin')`)
	exe, _ := os.Executable()
	if exe == "" {
		exe = "modular-flyer"
	}
	absDB, _ := filepath.Abs(dbPath)
	if absDB == "" {
		absDB = dbPath
	}
	fmt.Printf("To generate an admin login link, run:\n  %s gen-link --admin --base-url %s %s\n", exe, baseURL, absDB)
	// compute ETag from the HTML template content — constant per binary run
	sum := sha256.Sum256([]byte(mapHTML))
	htmlETag := fmt.Sprintf(`"%x"`, sum[:8])

	pageBytes := []byte(mapHTML)

	// GET / — serve the map page
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("If-None-Match") == htmlETag {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Header().Set("ETag", htmlETag)
		w.Header().Set("Cache-Control", "no-cache")
		w.Write(pageBytes)
	})

	// POST /api/login — {username, token} → sets session cookie
	http.HandleFunc("/api/login", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		var req struct {
			Username string `json:"username"`
			Token    string `json:"token"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		var isAdminInt int
		var expiresAt int64
		var usedAt sql.NullInt64
		err := db.QueryRow(
			`SELECT is_admin, expires_at, used_at FROM invite_tokens WHERE token=? AND username=?`,
			req.Token, req.Username,
		).Scan(&isAdminInt, &expiresAt, &usedAt)
		if err != nil {
			http.Error(w, "Ungültiger Zugangslink.", 401)
			return
		}
		if usedAt.Valid {
			http.Error(w, "Link bereits verwendet.", 401)
			return
		}
		if time.Now().Unix() > expiresAt {
			http.Error(w, "Link abgelaufen.", 401)
			return
		}
		// mark token used
		mustExec(db, `UPDATE invite_tokens SET used_at=? WHERE token=?`, time.Now().Unix(), req.Token)
		// invalidate caller's existing session (if any)
		if existing, err := r.Cookie("session"); err == nil {
			mustExec(db, `DELETE FROM sessions WHERE session_id = ?`, existing.Value)
		}
		sessionID := randomBase64(32) // 256 bits
		mustExec(db, `INSERT INTO sessions (session_id, username, is_admin, created_at) VALUES (?,?,?,?)`,
			sessionID, req.Username, isAdminInt, time.Now().Unix())
		setSessionCookie(w, sessionID)
		writeJSON(w, map[string]any{"ok": true, "is_admin": isAdminInt == 1, "username": req.Username})
	})

	// GET /api/me — returns current session info
	http.HandleFunc("/api/me", func(w http.ResponseWriter, r *http.Request) {
		username, isAdmin, ok := requireSession(db, w, r)
		if !ok {
			return
		}
		writeJSON(w, map[string]any{"ok": true, "username": username, "is_admin": isAdmin})
	})

	// GET /api/state — all locations + routes (requires session)
	http.HandleFunc("/api/state", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", 405)
			return
		}
		if _, _, ok := requireSession(db, w, r); !ok {
			return
		}
		state, err := queryState(db)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		writeJSON(w, state)
	})

	// POST /api/routes — create a new route (admin only)
	http.HandleFunc("/api/routes", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		if !requireAdmin(db, w, r) {
			return
		}
		res, err := db.Exec(`INSERT INTO routes DEFAULT VALUES`)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		id, _ := res.LastInsertId()
		writeJSON(w, apiRoute{ID: int(id), Color: routeColor(int(id))})
	})

	// POST /api/assign — {route_id: N, location_ids: [...]} (admin only)
	http.HandleFunc("/api/assign", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		if !requireAdmin(db, w, r) {
			return
		}
		var req struct {
			RouteID     int   `json:"route_id"`
			LocationIDs []int `json:"location_ids"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		tx, err := db.Begin()
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		now := time.Now().Unix()
		stmt, err := tx.Prepare(`UPDATE locations SET route_id = ?, route_updated_at = ? WHERE id = ?`)
		if err != nil {
			tx.Rollback()
			http.Error(w, err.Error(), 500)
			return
		}
		defer stmt.Close()
		for _, lid := range req.LocationIDs {
			if _, err := stmt.Exec(req.RouteID, now, lid); err != nil {
				tx.Rollback()
				http.Error(w, err.Error(), 500)
				return
			}
		}
		if err := tx.Commit(); err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		w.WriteHeader(204)
	})

	// POST /api/locations — any session, creates a user-placed location
	http.HandleFunc("/api/locations", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		username, _, ok := requireSession(db, w, r)
		if !ok {
			return
		}
		var req struct {
			Name      string  `json:"name"`
			Lat       float64 `json:"lat"`
			Lon       float64 `json:"lon"`
			Comment   string  `json:"comment"`
			VisitType *int    `json:"visit_type"` // nil = nur platzieren
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		if req.Name == "" {
			http.Error(w, "name required", 400)
			return
		}
		now := time.Now().Unix()
		res, err := db.Exec(
			`INSERT INTO locations (name, lat, lon, created_by, created_at) VALUES (?,?,?,?,?)`,
			req.Name, req.Lat, req.Lon, username, now,
		)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		locID, _ := res.LastInsertId()
		if req.VisitType != nil {
			mustExec(db,
				`INSERT INTO visits (location_id, username, visited_at, comment, visit_type) VALUES (?,?,?,?,?)`,
				locID, username, now, req.Comment, *req.VisitType,
			)
		}
		// return the full location object
		loc := apiLocation{
			ID:        int(locID),
			Name:      req.Name,
			Lat:       &req.Lat,
			Lon:       &req.Lon,
			CreatedBy: &username,
		}
		if req.VisitType != nil {
			v := apiVisit{Username: username, VisitedAt: now, Comment: req.Comment, VisitType: *req.VisitType}
			loc.Visits = []apiVisit{v}
			if *req.VisitType == 1 {
				loc.Visited = true
			}
			if *req.VisitType == 2 {
				loc.NotAvailable = true
			}
			if req.Comment != "" {
				loc.HasComment = true
			}
		}
		writeJSON(w, loc)
	})

	// DELETE /api/locations/<id> — admin only, deletes a location and its visits
	http.HandleFunc("/api/locations/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodDelete {
			http.Error(w, "method not allowed", 405)
			return
		}
		if !requireAdmin(db, w, r) {
			return
		}
		idStr := strings.TrimPrefix(r.URL.Path, "/api/locations/")
		var id int
		if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil || id == 0 {
			http.Error(w, "invalid id", 400)
			return
		}
		mustExec(db, `DELETE FROM visits WHERE location_id = ?`, id)
		mustExec(db, `DELETE FROM locations WHERE id = ?`, id)
		w.WriteHeader(204)
	})

	// POST /api/visits — any session, records a visit
	http.HandleFunc("/api/visits", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		username, _, ok := requireSession(db, w, r)
		if !ok {
			return
		}
		var req struct {
			LocationID int    `json:"location_id"`
			Comment    string `json:"comment"`
			VisitType  int    `json:"visit_type"` // 0=comment, 1=visited ok, 2=nicht möglich
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		mustExec(db,
			`INSERT INTO visits (location_id, username, visited_at, comment, visit_type) VALUES (?,?,?,?,?)`,
			req.LocationID, username, time.Now().Unix(), req.Comment, req.VisitType,
		)
		w.WriteHeader(204)
	})

	// GET /api/updates?since=<unix> — long-polls for new visits+route changes, blocks up to 30s
	http.HandleFunc("/api/updates", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", 405)
			return
		}
		if _, _, ok := requireSession(db, w, r); !ok {
			return
		}
		var since int64
		fmt.Sscanf(r.URL.Query().Get("since"), "%d", &since)

		type visitUpdate struct {
			LocationID int    `json:"location_id"`
			Username   string `json:"username"`
			VisitedAt  int64  `json:"visited_at"`
			Comment    string `json:"comment"`
			VisitType  int    `json:"visit_type"`
		}
		type routeUpdate struct {
			LocationID int    `json:"location_id"`
			RouteID    *int   `json:"route_id"`
			Color      string `json:"color"`
		}

		deadline := time.Now().Add(30 * time.Second)
		for time.Now().Before(deadline) {
			// check new visits
			vrows, err := db.Query(
				`SELECT location_id, username, visited_at, COALESCE(comment,''), visit_type
				 FROM visits WHERE visited_at > ? ORDER BY visited_at ASC`,
				since,
			)
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			var visits []visitUpdate
			for vrows.Next() {
				var v visitUpdate
				vrows.Scan(&v.LocationID, &v.Username, &v.VisitedAt, &v.Comment, &v.VisitType)
				visits = append(visits, v)
			}
			vrows.Close()

			// check route assignment changes
			rrows, err := db.Query(
				`SELECT id, route_id FROM locations WHERE route_updated_at > ?`,
				since,
			)
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			var routeChanges []routeUpdate
			for rrows.Next() {
				var u routeUpdate
				rrows.Scan(&u.LocationID, &u.RouteID)
				if u.RouteID != nil {
					u.Color = routeColor(*u.RouteID)
				}
				routeChanges = append(routeChanges, u)
			}
			rrows.Close()

			// check new user-created locations
			lrows, err := db.Query(
				`SELECT id, name, COALESCE(street,''), COALESCE(postal_code,''),
				        COALESCE(district,''), lat, lon, route_id, created_by
				 FROM locations WHERE created_at > ?`,
				since,
			)
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			var newLocs []apiLocation
			for lrows.Next() {
				var l apiLocation
				lrows.Scan(&l.ID, &l.Name, &l.Street, &l.PostalCode, &l.District,
					&l.Lat, &l.Lon, &l.RouteID, &l.CreatedBy)
				if l.RouteID != nil {
					c := routeColor(*l.RouteID)
					l.Color = &c
				}
				newLocs = append(newLocs, l)
			}
			lrows.Close()

			if len(visits) > 0 || len(routeChanges) > 0 || len(newLocs) > 0 {
				writeJSON(w, map[string]any{
					"visits":        visits,
					"route_changes": routeChanges,
					"new_locations": newLocs,
				})
				return
			}
			select {
			case <-r.Context().Done():
				return
			case <-time.After(5 * time.Second):
			}
		}
		writeJSON(w, map[string]any{"visits": []any{}, "route_changes": []any{}, "new_locations": []any{}})
	})

	// GET /api/qr?url=... — returns a PNG QR code (admin only)
	http.HandleFunc("/api/qr", func(w http.ResponseWriter, r *http.Request) {
		if !requireAdmin(db, w, r) {
			return
		}
		rawURL := r.URL.Query().Get("url")
		if rawURL == "" {
			http.Error(w, "missing url", 400)
			return
		}
		png, err := qrcode.Encode(rawURL, qrcode.Medium, 256)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		w.Header().Set("Content-Type", "image/png")
		w.Write(png)
	})

	// POST /api/invite — admin only, returns share_url (12h) + qr_url (5min)
	http.HandleFunc("/api/invite", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "method not allowed", 405)
			return
		}
		if !requireAdmin(db, w, r) {
			return
		}
		var req struct {
			Username string `json:"username"`
			IsAdmin  bool   `json:"is_admin"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), 400)
			return
		}
		since := time.Now().Unix()
		shareURL := makeInviteToken(db, baseURL, req.Username, req.IsAdmin, 12*time.Hour)
		qrURL := makeInviteToken(db, baseURL, req.Username, req.IsAdmin, 5*time.Minute)
		writeJSON(w, map[string]any{
			"share_url": shareURL,
			"qr_url":    qrURL,
			"since":     since,
		})
	})

	// GET /api/invite/status?username=alice&since=1234567890
	// blocks until a new session for that username or client disconnects or 30s elapses
	http.HandleFunc("/api/invite/status", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", 405)
			return
		}
		if !requireAdmin(db, w, r) {
			return
		}
		username := r.URL.Query().Get("username")
		sinceStr := r.URL.Query().Get("since")
		var since int64
		fmt.Sscanf(sinceStr, "%d", &since)

		deadline := time.Now().Add(30 * time.Second)
		for time.Now().Before(deadline) {
			var found int
			db.QueryRow(
				`SELECT COUNT(*) FROM sessions WHERE username=? AND created_at>?`,
				username, since,
			).Scan(&found)
			if found > 0 {
				writeJSON(w, map[string]any{"scanned": true})
				return
			}
			select {
			case <-r.Context().Done():
				return
			case <-time.After(500 * time.Millisecond):
			}
		}
		writeJSON(w, map[string]any{"scanned": false})
	})

	fmt.Printf("listening on %s\n", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Panicf("listen: %v", err)
	}
}

func cmdGenLink(args []string) {
	fs := flag.NewFlagSet("gen-link", flag.ExitOnError)
	isAdmin := fs.Bool("admin", false, "generate an admin link")
	username := fs.String("username", "", "username for the invite (default: 'admin' if --admin)")
	baseURL := fs.String("base-url", defaultBaseURL, "base URL for the link")
	fs.Parse(args)
	if fs.NArg() != 1 {
		log.Panicf("usage: modular-flyer gen-link [--admin] [--username <name>] [--base-url <url>] <db>")
	}
	if *username == "" {
		if *isAdmin {
			*username = "admin"
		} else {
			log.Panicf("--username is required for non-admin links")
		}
	}
	db := openDB(fs.Arg(0))
	defer db.Close()
	url := makeInviteToken(db, *baseURL, *username, *isAdmin, 12*time.Hour)
	fmt.Println(url)
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "usage: modular-flyer <command> [args]\n")
		fmt.Fprintf(os.Stderr, "commands:\n")
		fmt.Fprintf(os.Stderr, "  serve    [flags] <db>\n")
		fmt.Fprintf(os.Stderr, "  gen-link [flags] <db>\n")
		os.Exit(1)
	}

	switch os.Args[1] {
	case "serve":
		fs := flag.NewFlagSet("serve", flag.ExitOnError)
		baseURL := fs.String("base-url", defaultBaseURL, "base URL for invite links")
		addr := fs.String("addr", ":8081", "listen address")
		fs.Parse(os.Args[2:])
		if fs.NArg() != 1 {
			log.Panicf("usage: modular-flyer serve [flags] <db>")
		}
		cmdServe(fs.Arg(0), *baseURL, *addr)
	case "gen-link":
		cmdGenLink(os.Args[2:])
	default:
		log.Panicf("unknown command %q", os.Args[1])
	}
}