File size: 110,633 Bytes
3e1cf28
 
 
2b14ea4
 
 
 
 
3e1cf28
b4a8f62
72e655c
b4a8f62
3e1cf28
b4a8f62
3e1cf28
 
b4a8f62
 
 
 
 
 
 
2c422c6
b16e88e
 
2c422c6
 
 
 
 
 
 
b4a8f62
af9debc
 
74a053f
 
 
 
 
af9debc
3e1cf28
 
 
 
 
 
 
b4a8f62
0cc15f2
175a7fe
 
 
 
0cc15f2
175a7fe
0cc15f2
 
 
72e655c
175a7fe
2b14ea4
b16e88e
 
 
74a053f
 
 
 
 
 
 
 
 
0cc15f2
175a7fe
0cc15f2
175a7fe
 
72e655c
 
 
175a7fe
 
72e655c
 
 
0cc15f2
57519d7
 
 
 
2b14ea4
72e655c
 
57519d7
0cc15f2
175a7fe
0cc15f2
72e655c
0cc15f2
 
72e655c
 
 
 
 
175a7fe
0cc15f2
 
 
 
 
 
 
 
b4a8f62
 
9672344
 
 
a5d6d84
 
 
 
 
 
 
 
74a053f
a5d6d84
74a053f
a5d6d84
 
74a053f
 
 
 
 
 
a5d6d84
 
 
 
 
 
 
 
 
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
9672344
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9debc
 
922edb8
 
 
 
 
 
 
 
af9debc
922edb8
 
 
 
 
 
af9debc
922edb8
 
af9debc
 
442ba7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e88e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af9debc
 
2e9a2d0
9672344
442ba7e
9672344
442ba7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
9672344
442ba7e
9672344
442ba7e
 
 
 
 
 
9672344
 
dcb0a1b
 
 
922edb8
 
7c5c778
922edb8
 
 
 
 
 
 
 
7c5c778
922edb8
 
 
 
 
af9debc
922edb8
af9debc
922edb8
 
 
af9debc
922edb8
 
9672344
442ba7e
922edb8
9672344
 
 
 
 
922edb8
 
 
 
9672344
 
 
 
 
 
 
 
 
 
922edb8
af9debc
 
5f2bd86
af9debc
922edb8
 
 
 
 
 
 
 
 
af9debc
922edb8
 
9672344
922edb8
 
af9debc
9672344
dcb0a1b
 
 
9672344
dcb0a1b
 
922edb8
af9debc
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e88e
442ba7e
 
175a7fe
b16e88e
922edb8
442ba7e
 
 
 
 
 
 
 
b16e88e
74a053f
b16e88e
 
175a7fe
b16e88e
72e655c
af9debc
175a7fe
442ba7e
 
 
 
b16e88e
442ba7e
b16e88e
442ba7e
b16e88e
442ba7e
 
 
b16e88e
442ba7e
b16e88e
175a7fe
b16e88e
72e655c
922edb8
af9debc
442ba7e
9672344
 
 
922edb8
442ba7e
 
 
 
 
 
 
 
 
 
 
9672344
 
442ba7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
442ba7e
 
 
 
 
 
 
 
 
 
9672344
922edb8
 
9672344
442ba7e
 
 
 
 
9672344
 
 
 
 
922edb8
2e9a2d0
a5d6d84
2e9a2d0
 
922edb8
af9debc
922edb8
af9debc
922edb8
9672344
 
 
 
 
 
922edb8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
 
 
 
 
af9debc
 
b4a8f62
9672344
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
442ba7e
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
 
b4a8f62
2e9a2d0
 
b4a8f62
2e9a2d0
 
b4a8f62
 
 
7c5c778
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
b4a8f62
9672344
b4a8f62
 
 
9672344
 
 
 
 
b4a8f62
 
 
 
 
442ba7e
9672344
b4a8f62
 
 
 
 
 
 
 
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
b16e88e
 
 
b4a8f62
 
 
b16e88e
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
 
 
 
 
 
 
b4a8f62
9672344
 
 
 
 
 
 
 
b4a8f62
9672344
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
9672344
 
b735d78
2b14ea4
 
 
9672344
 
 
 
 
2b14ea4
 
 
 
b735d78
9672344
 
 
 
 
 
 
 
2b14ea4
 
9672344
2b14ea4
 
 
 
a5d6d84
b735d78
 
2b14ea4
9672344
b735d78
 
 
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
9672344
a5d6d84
 
2e9a2d0
b735d78
2e9a2d0
 
 
 
b735d78
9672344
 
 
 
2e9a2d0
 
 
 
 
 
 
 
 
 
 
 
af9debc
b735d78
2e9a2d0
9672344
 
2e9a2d0
9672344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
9672344
 
 
 
 
2e9a2d0
9672344
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f85f6f1
2e9a2d0
 
b735d78
2e9a2d0
 
 
 
 
 
 
a5d6d84
2e9a2d0
a5d6d84
2e9a2d0
 
 
2b14ea4
 
9672344
 
 
 
2e9a2d0
 
2b14ea4
 
a5d6d84
2e9a2d0
a5d6d84
 
 
2e9a2d0
 
 
a5d6d84
 
 
 
 
 
 
 
 
 
 
2e9a2d0
 
b735d78
b4a8f62
 
2e9a2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
2e9a2d0
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
2e9a2d0
 
b4a8f62
2e9a2d0
b4a8f62
 
2e9a2d0
 
 
 
 
 
b4a8f62
2e9a2d0
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
b4a8f62
 
 
3e1cf28
 
 
b4a8f62
 
3574d32
3e1cf28
 
 
b4a8f62
2e9a2d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
 
9672344
3e1cf28
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
b4a8f62
3e1cf28
 
 
 
b4a8f62
 
 
 
3e1cf28
 
b4a8f62
 
 
 
 
 
3e1cf28
b4a8f62
 
3e1cf28
b4a8f62
 
3e1cf28
74a053f
b4a8f62
3e1cf28
b4a8f62
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
3e1cf28
74a053f
b4a8f62
3e1cf28
b4a8f62
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
3e1cf28
b4a8f62
 
 
 
b16e88e
b4a8f62
 
 
9672344
 
 
 
 
 
74a053f
9672344
 
2c422c6
b16e88e
 
 
 
442ba7e
 
 
2c422c6
b16e88e
 
 
 
 
 
 
 
 
 
 
2c422c6
b16e88e
2c422c6
 
b16e88e
2c422c6
b16e88e
 
 
 
442ba7e
 
b16e88e
 
 
 
 
2c422c6
 
 
 
 
b16e88e
2c422c6
 
 
442ba7e
2c422c6
 
442ba7e
 
 
 
 
 
 
 
2c422c6
b16e88e
 
 
 
 
 
 
 
 
 
 
 
74a053f
b16e88e
74a053f
2c422c6
 
442ba7e
 
 
2c422c6
 
 
b4a8f62
b16e88e
 
 
2c422c6
b16e88e
2c422c6
b16e88e
 
2c422c6
442ba7e
2c422c6
b16e88e
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
 
9672344
3e1cf28
b4a8f62
 
74a053f
9672344
 
74a053f
 
 
 
 
 
 
 
9672344
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
b4a8f62
3e1cf28
 
 
 
 
b4a8f62
 
 
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
922edb8
b4a8f62
 
 
 
 
 
 
 
74a053f
 
 
 
 
 
922edb8
b4a8f62
 
74a053f
 
 
 
 
 
922edb8
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
2e9a2d0
b4a8f62
 
2e9a2d0
 
 
 
 
b4a8f62
 
2e9a2d0
b4a8f62
 
 
 
 
 
 
9672344
 
 
 
 
 
b4a8f62
af9debc
b4a8f62
a5d6d84
2e9a2d0
 
b4a8f62
 
 
 
9672344
b4a8f62
 
 
 
9672344
b4a8f62
 
 
 
 
 
9672344
442ba7e
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9672344
 
 
 
 
 
b4a8f62
af9debc
b4a8f62
a5d6d84
2e9a2d0
 
b4a8f62
 
2c422c6
 
2b14ea4
2c422c6
 
 
 
b4a8f62
 
 
 
2c422c6
b4a8f62
 
 
b16e88e
7032376
 
 
b16e88e
 
7032376
 
 
 
 
b4a8f62
af9debc
b4a8f62
b16e88e
 
b4a8f62
 
 
 
 
 
 
 
922edb8
af9debc
 
b4a8f62
b16e88e
 
 
b4a8f62
 
2b14ea4
 
2c422c6
2b14ea4
2c422c6
 
b4a8f62
2c422c6
 
 
 
 
 
 
 
 
 
b4a8f62
2c422c6
922edb8
 
b16e88e
 
922edb8
f921425
922edb8
2c422c6
 
 
2e9a2d0
 
 
2c422c6
 
 
 
 
 
 
b4a8f62
2c422c6
b4a8f62
 
 
 
2c422c6
 
 
 
2e9a2d0
 
2c422c6
 
 
 
 
 
 
2b14ea4
2c422c6
 
 
 
2e9a2d0
2c422c6
 
 
 
 
 
 
 
 
 
2e9a2d0
 
2c422c6
 
74a053f
2c422c6
 
 
 
 
74a053f
 
 
 
 
 
2c422c6
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c422c6
 
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
2c422c6
 
 
 
 
 
 
 
 
74a053f
2c422c6
b16e88e
 
 
 
2c422c6
 
2b14ea4
 
2c422c6
2b14ea4
2c422c6
 
 
 
74a053f
 
 
 
 
2c422c6
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c422c6
74a053f
 
 
 
 
 
 
b16e88e
74a053f
b16e88e
cdc6c8b
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c422c6
74a053f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e9a2d0
2c422c6
 
 
 
b16e88e
af9debc
922edb8
 
af9debc
 
922edb8
 
af9debc
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
b4a8f62
 
 
 
9672344
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
b4a8f62
 
 
442ba7e
b735d78
 
 
 
442ba7e
 
 
b735d78
442ba7e
b735d78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
b735d78
 
 
b4a8f62
b735d78
 
 
583dfbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b16e88e
 
 
 
 
 
 
 
 
 
 
 
 
583dfbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
442ba7e
 
 
 
 
 
 
583dfbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b735d78
 
 
 
 
 
25e5bee
b735d78
 
 
 
 
 
25e5bee
b735d78
 
 
 
 
 
25e5bee
b735d78
 
 
 
 
 
25e5bee
b735d78
 
 
442ba7e
 
 
 
 
b735d78
25e5bee
b735d78
 
 
 
 
 
25e5bee
b735d78
 
442ba7e
 
 
 
 
 
 
 
 
 
b735d78
 
 
 
25e5bee
b735d78
 
583dfbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
442ba7e
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b735d78
b4a8f62
 
 
b735d78
b4a8f62
 
 
b735d78
 
 
 
 
 
b4a8f62
 
 
b735d78
b4a8f62
 
 
b735d78
 
 
 
 
 
 
442ba7e
 
 
 
b735d78
 
b4a8f62
 
 
 
 
 
 
 
442ba7e
f478b24
442ba7e
f478b24
 
442ba7e
f478b24
442ba7e
f478b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f478b24
 
442ba7e
 
 
 
 
 
 
f478b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
f478b24
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
d910e3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4a8f62
d910e3c
 
 
 
 
 
b4a8f62
d910e3c
 
b4a8f62
 
 
f478b24
b4a8f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e1cf28
 
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
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
# server.R
server <- function(input, output, session) {
  stations <- reactive({
    st <- get_imgw_stations()
    if (!"station_uid" %in% names(st)) {
      st$station_uid <- paste(st$id, st$name, sep = "|")
    }
    st
  })


  # Map state
  style_change_trigger <- reactiveVal(0)
  stations_before_id <- reactiveVal("waterway_line_label")
  current_raster_layers <- reactiveVal(character(0))
  map_initialized <- reactiveVal(FALSE)

  # Dashboard station state
  current_station_uid <- reactiveVal(NULL)
  station_data <- reactiveVal(NULL)
  station_fetching <- reactiveVal(FALSE)
  station_fetch_message <- reactiveVal("")
  station_fetch_error <- reactiveVal(NULL)
  prev_dates <- reactiveVal(NULL)
  monthly_auto_shifted <- reactiveVal(FALSE)
  active_fetch_dates <- reactiveVal(NULL)

  # Fetch Async State Machine Variables
  fetch_stage <- reactiveVal(0) # 0=Idle, 1=Init, 2=Next, 4=Download/Parse, 6=Merge
  fetch_queue <- reactiveVal(NULL)
  fetch_queue_idx <- reactiveVal(0)
  parsed_data_list <- reactiveVal(list())
  fetch_current_token <- reactiveVal(NULL)

  # Track if URL params have been applied
  url_initialized <- reactiveVal(FALSE)
  has_url_dates <- reactiveVal(FALSE)

  is_session_closed <- function(sess = session) {
    tryCatch(!is.null(sess) && is.function(sess$isClosed) && isTRUE(sess$isClosed()), error = function(e) FALSE)
  }

  # Map bounds for Poland
  map_bounds <- list(
    lng_min = 14.0,
    lat_min = 49.0,
    lng_max = 24.5,
    lat_max = 55.0
  )

  # --- Midnight Rollover: keep end date current across days ---
  # The default_end_date in global.R is frozen at container startup.
  # This handles TWO scenarios:
  #   A) New session opened days after container start → fix on session init
  #   B) Long-lived session staying open past midnight → fix via hourly poll

  # Poll every hour for scenario B
  day_tick <- reactiveTimer(3600000)

  observe({
    day_tick() # re-fire every hour
    # Also depend on url_initialized so we fire once on session start
    req(url_initialized(), input$date_range)
    if (identical(isolate(selected_resolution()), "monthly")) {
      return()
    }
    if (isTRUE(has_url_dates())) {
      return()
    }
    pd_cur <- isolate(prev_dates())
    if (!is.null(pd_cur) && length(pd_cur) >= 2 && !any(is.na(pd_cur)) &&
        length(input$date_range) >= 2 && !any(is.na(input$date_range)) &&
        !identical(as.Date(pd_cur[1:2]), as.Date(input$date_range[1:2]))) {
      return()
    }

    today <- Sys.Date()

    # Read current end date from the widget, coerce explicitly to Date
    current_end <- tryCatch(as.Date(input$date_range[2]), error = function(e) NA)
    if (is.null(current_end) || is.na(current_end)) {
      return()
    }

    # Only auto-advance if the end date is in the past (stale)
    if (current_end >= today) {
      return()
    }

    # Only auto-advance if end date is very recent (within 2 days of today).
    # This handles genuine midnight rollover (session stayed open past midnight)
    # without resetting intentionally historical date ranges chosen by the user.
    days_behind <- as.numeric(difftime(today, current_end, units = "days"))
    if (!is.na(days_behind) && days_behind > 2) {
      return()
    }

    # Maintain the same window width (start -> end distance)
    current_start <- tryCatch(as.Date(input$date_range[1]), error = function(e) today - 366)
    window_days <- as.numeric(difftime(current_end, current_start, units = "days"))
    new_end <- today
    new_start <- new_end - window_days

    message(
      "[midnight-rollover] Updating date range: ",
      current_end, " -> ", new_end,
      " (start: ", current_start, " -> ", new_start, ")"
    )

    updateDateRangeInput(session, "date_range",
      start = new_start, end = new_end,
      max = today
    )

    prev_dates(c(new_start, new_end))
  })

  # --- Loading State & Freeze Window ---
  loading_status <- reactiveVal(FALSE)
  selected_county <- reactiveVal("All")
  selected_resolution <- reactiveVal("daily")
  suppress_next_county_effect <- reactiveVal(FALSE)
  suppress_selectize_empty <- reactiveVal(FALSE)
  selectize_suppress_token <- reactiveVal(0L)
  client_station_synced <- reactiveVal(NULL)

  arm_suppress_selectize <- function(duration = 1.5) {
    tok <- isolate(selectize_suppress_token()) + 1L
    selectize_suppress_token(tok)
    suppress_selectize_empty(TRUE)
    current_session <- session
    session$onFlushed(function() {
      if (is_session_closed(current_session)) return()
      later::later(function() {
        tryCatch({
          if (is_session_closed(current_session)) return()
          shiny::withReactiveDomain(current_session, shiny::isolate({
            if (identical(selectize_suppress_token(), tok)) {
              suppress_selectize_empty(FALSE)
            }
          }))
        }, error = function(e) NULL)
      }, duration)
    }, once = TRUE)
  }

  clear_suppress_selectize <- function() {
    selectize_suppress_token(isolate(selectize_suppress_token()) + 1L)
    suppress_selectize_empty(FALSE)
  }

  has_county_filter <- function(val) {
    is_valid_str(val) && !identical(trimws(as.character(val[1])), "All")
  }

  set_county_filter <- function(val, update_input = TRUE, suppress_effect = FALSE) {
    clean_val <- if (has_county_filter(val)) as.character(val[1]) else "All"
    if (isTRUE(suppress_effect) && isTRUE(isolate(url_initialized())) && !identical(isolate(selected_county()), clean_val)) {
      suppress_next_county_effect(TRUE)
    }
    selected_county(clean_val)
    if (isTRUE(update_input)) {
      updateSelectizeInput(session, "county_filter", selected = clean_val)
    }
  }

  # Observer: Freeze UI during loading
  observe({
    is_loading <- loading_status()

    # List of inputs to disable/enable
    inputs_to_toggle <- c(
      "county_filter",
      "temporal_resolution",
      "date_range",
      "zoom_home",
      "main_nav",
      "basemap",
      "show_labels",
      "stations_table" # Also disable table interaction if possible (though specific row clicks are hard to prevent, visual disable is good)
    )

    if (is_loading) {
      for (inp in inputs_to_toggle) {
        shinyjs::disable(inp)
      }
      # Optional: Show a global loading notification or overlay if desired,
      # but the inputs being disabled is the primary visual cue + the spinner in dashboard.
    } else {
      for (inp in inputs_to_toggle) {
        shinyjs::enable(inp)
      }
    }
  })

  # Helper: Parse URL query string
  parse_url_params <- function(query_string) {
    if (is.null(query_string) || query_string == "" || query_string == "?") {
      return(list())
    }
    # Remove leading "?"
    qs <- sub("^\\?", "", query_string)
    if (qs == "") {
      return(list())
    }

    pairs <- strsplit(qs, "&")[[1]]
    params <- list()
    for (pair in pairs) {
      kv <- strsplit(pair, "=")[[1]]
      if (length(kv) == 2) {
        params[[kv[1]]] <- URLdecode(kv[2])
      }
    }
    params
  }

  imgw_coalesce_code <- function(id_val, id_9_val) {
    v1 <- if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1]) && nzchar(trimws(as.character(id_val[1])))) trimws(as.character(id_val[1])) else NULL
    if (!is.null(v1)) return(v1)
    if (!is.null(id_9_val) && length(id_9_val) > 0 && !is.na(id_9_val[1]) && nzchar(trimws(as.character(id_9_val[1])))) trimws(as.character(id_9_val[1])) else NULL
  }

  imgw_disambiguated_slug <- function(name_val, id_val, id_9_val, st_all) {
    if (!is_valid_str(name_val)) return(NULL)
    base_slug <- imgw_slugify(name_val)
    if (is.null(st_all) || nrow(st_all) == 0 || !"name" %in% names(st_all)) return(base_slug)
    dup_count <- sum(imgw_slugify(st_all$name) == base_slug, na.rm = TRUE)
    if (dup_count > 1L) {
      code_part <- imgw_coalesce_code(id_val, id_9_val)
      if (!is.null(code_part)) {
        return(paste0(base_slug, "-", imgw_slugify(code_part)))
      }
    }
    base_slug
  }

  latest_monthly_archive_date <- function() {
    cur_yr <- as.integer(format(Sys.Date(), "%Y"))
    dirs <- tryCatch(
      imgw_list_source_dirs(imgw_raw_sources$monthly$synop$base_url),
      error = function(e) character(0)
    )
    yr_nums <- integer(0)
    for (d in dirs) {
      yr <- imgw_parse_year_range(d)
      if (!is.na(yr[["end_year"]])) yr_nums <- c(yr_nums, as.integer(yr[["end_year"]]))
    }
    yr_nums <- yr_nums[yr_nums <= cur_yr]
    max_yr <- if (length(yr_nums) > 0) max(yr_nums, na.rm = TRUE) else (cur_yr - 2L)
    as.Date(sprintf("%04d-12-31", max_yr))
  }

  # Helper to calculate and enforce resolution span & archive availability bounds
  check_and_limit_dates <- function(start, end, resolution, anchor = "end", from_resolution_switch = FALSE) {
    res_norm <- if (is_valid_str(resolution)) tolower(trimws(as.character(resolution[1]))) else "daily"
    if (identical(res_norm, "monthly")) {
      latest_m <- latest_monthly_archive_date()
      if (end > latest_m) {
        if (isTRUE(from_resolution_switch) || start > latest_m || as.numeric(latest_m - start) < 365) {
          new_end <- latest_m
          new_start <- new_end - 2191
          return(list(
            start = new_start,
            end = new_end,
            limited = TRUE,
            clamped_monthly_archive = TRUE,
            msg = paste0("latest published monthly archives (through ", format(latest_m, "%Y"), ")")
          ))
        } else {
          new_end <- latest_m
          new_start <- if (as.numeric(new_end - start) > 2191) new_end - 2191 else start
          return(list(
            start = new_start,
            end = new_end,
            limited = TRUE,
            clamped_monthly_archive = FALSE,
            msg = paste0("latest published monthly archives (through ", format(latest_m, "%Y"), ")")
          ))
        }
      }
    }

    limit_days <- Inf
    limit_msg <- ""

    if (identical(res_norm, "hourly")) {
      limit_days <- 93
      limit_msg <- "3 months"
    } else if (identical(res_norm, "daily")) {
      limit_days <- 366
      limit_msg <- "1 year"
    } else if (identical(res_norm, "monthly")) {
      limit_days <- 2191
      limit_msg <- "6 years"
    }

    diff <- as.numeric(end - start)
    if (diff > limit_days) {
      new_start <- start
      new_end <- end

      if (anchor == "start") {
        new_end <- start + limit_days
      } else {
        new_start <- end - limit_days
      }
      return(list(start = new_start, end = new_end, limited = TRUE, clamped_monthly_archive = FALSE, msg = limit_msg))
    }
    return(list(start = start, end = end, limited = FALSE, clamped_monthly_archive = FALSE, msg = ""))
  }

  # Authoritative date range (reflects server-clamped prev_dates immediately without waiting for client round-trip)
  effective_date_range <- reactive({
    pd <- prev_dates()
    if (!is.null(pd) && length(pd) >= 2 && !any(is.na(pd))) {
      d1 <- tryCatch(as.Date(pd[1]), error = function(e) NA)
      d2 <- tryCatch(as.Date(pd[2]), error = function(e) NA)
      if (!is.na(d1) && !is.na(d2)) {
        return(c(d1, d2))
      }
    }
    dr <- input$date_range
    if (!is.null(dr) && length(dr) >= 2) {
      d1 <- tryCatch(as.Date(dr[1]), error = function(e) NA)
      d2 <- tryCatch(as.Date(dr[2]), error = function(e) NA)
      if (!is.na(d1) && !is.na(d2)) {
        return(c(d1, d2))
      }
    }
    c(default_start_date, default_end_date)
  })

  # Helper: Broadcast current state to parent page
  broadcast_state <- function(view_override = NULL) {
    st <- tryCatch(isolate(selected_station()), error = function(e) NULL)
    res_key <- tryCatch(isolate(resolution_key()), error = function(e) "daily")
    st_all <- tryCatch(isolate(stations()), error = function(e) NULL)

    # Extract scalar values from tibble row (coalescing 9-digit CBDH code when short id is missing)
    has_st <- !is.null(st) && nrow(st) > 0
    station_id <- if (has_st) {
      imgw_coalesce_code(
        if ("id" %in% names(st)) st$id[1] else NULL,
        if ("id_9" %in% names(st)) st$id_9[1] else NULL
      )
    } else NULL
    station_name <- if (has_st && "name" %in% names(st) && !is.na(st$name[1])) as.character(st$name[1]) else NULL
    station_uid <- if (has_st && "station_uid" %in% names(st) && is_valid_str(st$station_uid[1])) as.character(st$station_uid[1]) else if (!is.null(station_id) && !is.null(station_name)) paste(station_id, station_name, sep = "|") else NULL
    station_slug <- if (has_st) {
      imgw_disambiguated_slug(
        station_name,
        if ("id" %in% names(st)) st$id[1] else NULL,
        if ("id_9" %in% names(st)) st$id_9[1] else NULL,
        st_all
      )
    } else NULL
    station_type <- if (has_st && "station_type" %in% names(st) && !is.na(st$station_type[1])) as.character(st$station_type[1]) else NULL
    landname <- if (has_st && "station_type" %in% names(st) && "data_order" %in% names(st) && !is.na(st$station_type[1]) && !is.na(st$data_order[1])) paste0(st$station_type[1], "-", st$data_order[1]) else NULL

    elevation <- if (!is.null(st) && nrow(st) > 0 && "elevation" %in% names(st) && !is.na(st$elevation[1])) {
      suppressWarnings(as.numeric(st$elevation[1]))
    } else {
      NULL
    }
    lat <- if (!is.null(st) && nrow(st) > 0 && "lat" %in% names(st) && !is.na(st$lat[1])) {
      round(suppressWarnings(as.numeric(st$lat[1])), 5)
    } else {
      NULL
    }
    lon <- if (!is.null(st) && nrow(st) > 0 && "lon" %in% names(st) && !is.na(st$lon[1])) {
      round(suppressWarnings(as.numeric(st$lon[1])), 5)
    } else {
      NULL
    }

    res_start_col <- paste0("date_start_", res_key)
    res_end_col <- paste0("date_end_", res_key)
    overall_start <- if (!is.null(st) && nrow(st) > 0) {
      if (res_start_col %in% names(st) && !is.na(st[[res_start_col]][1])) {
        as.character(st[[res_start_col]][1])
      } else if ("date_start" %in% names(st) && !is.na(st$date_start[1])) {
        as.character(st$date_start[1])
      } else {
        NULL
      }
    } else {
      NULL
    }
    overall_end <- if (!is.null(st) && nrow(st) > 0) {
      if (res_end_col %in% names(st) && !is.na(st[[res_end_col]][1])) {
        as.character(st[[res_end_col]][1])
      } else if ("date_end" %in% names(st) && !is.na(st$date_end[1])) {
        as.character(st$date_end[1])
      } else {
        NULL
      }
    } else {
      NULL
    }

    available_params <- if (!is.null(st) && nrow(st) > 0) {
      order_key <- tolower(trimws(if ("data_order" %in% names(st) && !is.na(st$data_order[1])) as.character(st$data_order[1]) else ""))
      res_map <- tryCatch(params_by_resolution[[res_key]], error = function(e) NULL)
      if (!is.null(res_map) && order_key %in% names(res_map)) {
        unname(res_map[[order_key]])
      } else if ("params_summary" %in% names(st) && is_valid_str(st$params_summary[1])) {
        as.character(st$params_summary[1])
      } else if (!is.null(res_map) && "klimat" %in% names(res_map)) {
        unname(res_map[["klimat"]])
      } else {
        NULL
      }
    } else {
      NULL
    }

    active_cf <- isolate(selected_county())
    county_val <- if (!is.null(st) && nrow(st) > 0 && "voivodeship" %in% names(st) && is_valid_str(st$voivodeship[1])) {
      as.character(st$voivodeship[1])
    } else if (has_county_filter(active_cf)) {
      as.character(active_cf[1])
    } else {
      NULL
    }
    county_slug <- if (is_valid_str(county_val)) imgw_slugify(county_val) else NULL
    resolution <- switch(res_key,
      hourly = "Hourly",
      daily = "Daily",
      monthly = "Monthly",
      "Daily"
    )

    pd <- isolate(prev_dates())
    date_range_val <- if (!is.null(pd) && length(pd) >= 2 && !any(is.na(pd))) pd else isolate(input$date_range)
    start_date <- if (!is.null(date_range_val) && length(date_range_val) >= 1 && !is.na(date_range_val[1])) as.character(date_range_val[1]) else NULL
    end_date <- if (!is.null(date_range_val) && length(date_range_val) >= 2 && !is.na(date_range_val[2])) as.character(date_range_val[2]) else NULL

    # Compute total and active station counts and Voivodeship station list
    st_res <- if (!is.null(st_all) && nrow(st_all) > 0 && res_start_col %in% names(st_all)) {
      st_all[!is.na(st_all[[res_start_col]]), , drop = FALSE]
    } else {
      st_all
    }
    st_scope <- if (is_valid_str(county_val) && !is.null(st_res) && "voivodeship" %in% names(st_res)) {
      st_res[!is.na(st_res$voivodeship) & st_res$voivodeship == county_val, , drop = FALSE]
    } else {
      st_res
    }
    total_count <- if (!is.null(st_scope)) nrow(st_scope) else 0L
    active_count <- if (!is.null(st_scope) && nrow(st_scope) > 0 && !is.null(start_date) && !is.null(end_date)) {
      u_start <- tryCatch(as.Date(start_date), error = function(e) NA)
      u_end <- tryCatch(as.Date(end_date), error = function(e) NA)
      s_col <- st_scope[[res_start_col]]
      e_col <- if (res_end_col %in% names(st_scope)) st_scope[[res_end_col]] else st_scope$date_end
      if (!is.na(u_start) && !is.na(u_end) && !is.null(s_col)) {
        sum(!is.na(s_col) & s_col <= u_end & (is.na(e_col) | e_col >= u_start), na.rm = TRUE)
      } else {
        total_count
      }
    } else {
      total_count
    }

    county_station_list <- if (is.null(station_id) && is_valid_str(county_val) && !is.null(st_scope) && nrow(st_scope) > 0) {
      st_sorted <- st_scope[order(st_scope$name), , drop = FALSE]
      lapply(seq_len(nrow(st_sorted)), function(i) {
        c_id <- imgw_coalesce_code(
          if ("id" %in% names(st_sorted)) st_sorted$id[i] else NULL,
          if ("id_9" %in% names(st_sorted)) st_sorted$id_9[i] else NULL
        )
        list(
          id = c_id,
          name = as.character(st_sorted$name[i]),
          slug = imgw_disambiguated_slug(
            st_sorted$name[i],
            if ("id" %in% names(st_sorted)) st_sorted$id[i] else NULL,
            if ("id_9" %in% names(st_sorted)) st_sorted$id_9[i] else NULL,
            st_all
          )
        )
      })
    } else {
      NULL
    }

    # Determine current view
    main_tab <- isolate(input$main_nav)
    view <- if (!is.null(view_override)) {
      view_override
    } else if (!is.null(main_tab)) {
      if (main_tab == "Map View") {
        "map"
      } else if (main_tab == "Stations Info") {
        "station-info"
      } else if (main_tab == "Dashboard") {
        subtab <- isolate(input$dashboard_subtabs)
        if (!is.null(subtab) && subtab == "Data") {
          "dashboard-data"
        } else {
          "dashboard-plots"
        }
      } else {
        "map"
      }
    } else {
      "map"
    }

    session$sendCustomMessage("updateParentURL", list(
      station = station_id,
      stationId = station_id,
      stationUid = station_uid,
      stationName = station_name,
      stationSlug = station_slug,
      stationType = station_type,
      county = county_val,
      countySlug = county_slug,
      voivodeship = county_val,
      landname = landname,
      resolution = resolution,
      view = view,
      start = start_date,
      end = end_date,
      elevation = elevation,
      lat = lat,
      lon = lon,
      overallStart = overall_start,
      overallEnd = overall_end,
      availableParams = available_params,
      activeCount = active_count,
      totalCount = total_count,
      countyStationList = county_station_list
    ))
  }

  # Observer: Apply URL params on app startup (runs once)
  observe({
    req(!url_initialized())
    # Use invalidateLater to retry if clientData isn't ready yet
    query <- session$clientData$url_search
    if (is.null(query)) {
      # clientData not ready yet — set initialized anyway to unblock
      url_initialized(TRUE)
      return()
    }
    params <- parse_url_params(query)

    if (length(params) == 0) {
      url_initialized(TRUE)
      broadcast_state()
      return()
    }

    # Apply resolution synchronously via selected_resolution and update UI
    if (!is.null(params$resolution) && length(params$resolution) > 0 && !is.na(params$resolution[1]) && nzchar(trimws(as.character(params$resolution[1])))) {
      res_lower <- tolower(trimws(as.character(params$resolution[1])))
      if (res_lower %in% c("hourly", "daily", "monthly")) {
        selected_resolution(res_lower)
        updateRadioGroupButtons(session, "temporal_resolution", selected = res_lower)
      }
    }

    # Apply Voivodeship / county filter if present in URL
    url_county_applied <- FALSE
    raw_county_param <- if (is_valid_str(params$county)) {
      params$county[1]
    } else if (is_valid_str(params$voivodeship)) {
      params$voivodeship[1]
    } else if (is_valid_str(params$region)) {
      params$region[1]
    } else {
      NULL
    }
    if (is_valid_str(raw_county_param)) {
      all_st <- stations()
      avail_voiv <- if ("voivodeship" %in% names(all_st)) unique(na.omit(as.character(all_st$voivodeship))) else NULL
      matched_voiv <- resolve_imgw_voivodeship(raw_county_param, available = avail_voiv)
      if (is_valid_str(matched_voiv)) {
        set_county_filter(matched_voiv, update_input = TRUE)
        url_county_applied <- TRUE
      }
    }

    # Apply date range (validated and clamped against active resolution & monthly archive limits)
    active_res_init <- isolate(selected_resolution())
    if (!active_res_init %in% c("hourly", "daily", "monthly")) active_res_init <- "daily"
    today <- Sys.Date()
    init_max_date <- if (identical(active_res_init, "monthly")) latest_monthly_archive_date() else today
    if (!is.null(params$start) && !is.null(params$end)) {
      start_date <- tryCatch(as.Date(params$start), error = function(e) NA)
      end_date <- tryCatch(as.Date(params$end), error = function(e) NA)
      if (!is.na(start_date) && !is.na(end_date)) {
        if (start_date > end_date) {
          tmp_d <- start_date; start_date <- end_date; end_date <- tmp_d
        }
        if (end_date > today) end_date <- today
        if (start_date > end_date) start_date <- end_date
        clamped <- check_and_limit_dates(start_date, end_date, active_res_init, anchor = "end", from_resolution_switch = FALSE)
        has_url_dates(TRUE)
        monthly_auto_shifted(isTRUE(clamped$clamped_monthly_archive))
        prev_dates(c(clamped$start, clamped$end))
        updateDateRangeInput(session, "date_range",
          start = clamped$start, end = clamped$end, max = init_max_date
        )
      }
    } else {
      # No URL dates — choose resolution-appropriate active window
      if (identical(active_res_init, "hourly")) {
        new_end <- today
        new_start <- new_end - 90
        monthly_auto_shifted(FALSE)
      } else if (identical(active_res_init, "monthly")) {
        new_end <- init_max_date
        new_start <- new_end - 2191
        monthly_auto_shifted(TRUE)
      } else {
        new_end <- today
        new_start <- new_end - 366
        monthly_auto_shifted(FALSE)
      }
      prev_dates(c(new_start, new_end))
      updateDateRangeInput(session, "date_range",
        start = new_start, end = new_end, max = init_max_date
      )
    }

    # Apply station selection (scoped to matched voivodeship first for duplicate names, falling back to full catalog)
    url_station_applied <- FALSE
    if (is_valid_str(params$station)) {
      station <- trimws(as.character(params$station[1]))
      all_stations <- stations()

      find_station_match <- function(pool) {
        if (is.null(pool) || nrow(pool) == 0) return(pool)
        prefer_active <- function(cand) {
          if (nrow(cand) <= 1) return(cand)
          is_act <- is.na(cand$date_end)
          cand[order(!is_act, cand$date_end, decreasing = FALSE, na.last = FALSE), , drop = FALSE][1, , drop = FALSE]
        }
        m <- pool[pool$station_uid == station, , drop = FALSE]
        if (nrow(m) > 0) return(prefer_active(m))

        st_slug <- imgw_slugify(station)
        if (nzchar(st_slug)) {
          disambig <- vapply(seq_len(nrow(pool)), function(i) {
            imgw_disambiguated_slug(pool$name[i], pool$id[i], pool$id_9[i], all_stations) %||% ""
          }, character(1))
          m <- pool[disambig == st_slug, , drop = FALSE]
          if (nrow(m) > 0) return(prefer_active(m))
        }

        m <- pool[(!is.na(pool$id) & pool$id == station) | (!is.na(pool$id_9) & pool$id_9 == station), , drop = FALSE]
        if (nrow(m) > 0) return(prefer_active(m))

        m <- pool[!is.na(pool$name) & pool$name == station, , drop = FALSE]
        if (nrow(m) > 0) return(prefer_active(m))

        if (nzchar(st_slug)) {
          m <- pool[imgw_slugify(pool$name) == st_slug, , drop = FALSE]
          if (nrow(m) > 0) return(prefer_active(m))
        }
        pool[0, , drop = FALSE]
      }

      cf_init <- isolate(selected_county())
      st <- if (has_county_filter(cf_init) && "voivodeship" %in% names(all_stations)) {
        pool_v <- all_stations[!is.na(all_stations$voivodeship) & all_stations$voivodeship == cf_init, , drop = FALSE]
        res_v <- find_station_match(pool_v)
        if (nrow(res_v) > 0) res_v else find_station_match(all_stations)
      } else {
        find_station_match(all_stations)
      }

      if (nrow(st) > 0) {
        url_station_applied <- TRUE
        uid <- if ("station_uid" %in% names(st) && is_valid_str(st$station_uid[1])) {
          as.character(st$station_uid[1])
        } else {
          paste(imgw_coalesce_code(st$id[1], st$id_9[1]), st$name[1], sep = "|")
        }
        cf_now <- isolate(selected_county())
        if (has_county_filter(cf_now) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf_now[1]))) {
          set_county_filter("All", update_input = TRUE, suppress_effect = FALSE)
        }
        current_station_uid(uid)
        shinyjs::delay(200, {
          current_station_uid(uid)
          arm_suppress_selectize(1.5)
          updateSelectizeInput(session, "station_selector", selected = uid)
          highlight_selected_station(st, move_map = TRUE)
        })
      }
    }

    # Apply view/tab navigation (deferred)
    url_view_override <- NULL
    if (is_valid_str(params$view)) {
      view <- as.character(params$view[1])
      if (view %in% c("map", "station-info", "dashboard-plots", "dashboard-data")) {
        url_view_override <- view
      }
      shinyjs::delay(600, {
        if (view == "map") {
          session$sendCustomMessage("switchTab", list(tabId = "Map View"))
        } else if (view == "station-info") {
          session$sendCustomMessage("switchTab", list(tabId = "Stations Info"))
        } else if (view %in% c("dashboard-plots", "dashboard-data")) {
          session$sendCustomMessage("switchTab", list(tabId = "Dashboard"))
          if (view == "dashboard-data") {
            shinyjs::delay(800, {
              shinyjs::runjs("$('a[data-value=\"Data\"]').tab('show');")
            })
          }
        }
      })
    }

    url_initialized(TRUE)

    if (url_county_applied && !url_station_applied) {
      zoom_to_active_extent(force_full_poland = !has_county_filter(isolate(selected_county())), clear_highlight = FALSE)
    }
    broadcast_state(view_override = url_view_override)
  })

  resolution_key <- reactive({
    res <- selected_resolution()
    if (is.null(res) || !res %in% c("hourly", "daily", "monthly")) {
      raw <- input$temporal_resolution
      res <- if (is_valid_str(raw)) tolower(trimws(as.character(raw[1]))) else "daily"
    }
    if (!res %in% c("hourly", "daily", "monthly")) "daily" else res
  })

  params_by_resolution <- list(
    hourly = c(
      synop = "Temperature, humidity, wind, pressure, clouds, visibility, precipitation, snow, sunshine, soil",
      klimat = "Temperature, humidity, wind, clouds, visibility",
      opad = "Not available for hourly",
      `tylko dok. papierowe` = "Paper archives only"
    ),
    daily = c(
      synop = "Temperature, precipitation, snow, wind, humidity, pressure, cloudiness, sunshine, weather phenomena, soil",
      klimat = "Temperature, precipitation, snow, wind, humidity, cloudiness",
      opad = "Precipitation, snow depth, snowfall type",
      `tylko dok. papierowe` = "Paper archives only"
    ),
    monthly = c(
      synop = "Temperature, precipitation, snow, sunshine, wind, humidity, cloudiness, weather days",
      klimat = "Temperature, precipitation, snow, wind, humidity, cloudiness",
      opad = "Precipitation, snow days, snow cover days",
      `tylko dok. papierowe` = "Paper archives only"
    )
  )

  parse_station_uid <- function(uid) {
    uid <- as.character(uid)[1]
    if (is.na(uid) || uid == "") {
      return(list(id = NA_character_, name = NA_character_))
    }
    if (!grepl("|", uid, fixed = TRUE)) {
      clean_id <- if (uid == "NA" || !nzchar(uid)) NA_character_ else uid
      return(list(id = clean_id, name = NA_character_))
    }
    raw_id <- sub("\\|.*$", "", uid)
    raw_name <- sub("^[^|]*\\|", "", uid)
    list(
      id = if (raw_id == "NA" || !nzchar(raw_id)) NA_character_ else raw_id,
      name = if (raw_name == "NA" || !nzchar(raw_name)) NA_character_ else raw_name
    )
  }

  build_station_popup <- function(st_row, res = NULL) {
    if (is.null(res)) res <- resolution_key()
    if (is.null(st_row) || nrow(st_row) == 0) {
      return("Station")
    }

    resolution_label <- switch(res,
      hourly = "Hourly",
      daily = "Daily",
      monthly = "Monthly",
      "Daily"
    )

    selected_start <- switch(res,
      hourly = if ("date_start_hourly" %in% names(st_row)) st_row$date_start_hourly[1] else NA,
      daily = if ("date_start_daily" %in% names(st_row)) st_row$date_start_daily[1] else NA,
      monthly = if ("date_start_monthly" %in% names(st_row)) st_row$date_start_monthly[1] else NA,
      if ("date_start" %in% names(st_row)) st_row$date_start[1] else NA
    )
    selected_end <- switch(res,
      hourly = if ("date_end_hourly" %in% names(st_row)) st_row$date_end_hourly[1] else NA,
      daily = if ("date_end_daily" %in% names(st_row)) st_row$date_end_daily[1] else NA,
      monthly = if ("date_end_monthly" %in% names(st_row)) st_row$date_end_monthly[1] else NA,
      if ("date_end" %in% names(st_row)) st_row$date_end[1] else NA
    )

    if (is.na(selected_start) && "date_start" %in% names(st_row)) selected_start <- st_row$date_start[1]
    if (is.na(selected_end) && "date_end" %in% names(st_row)) selected_end <- st_row$date_end[1]
    if (!is.na(selected_end) && !is.na(selected_start) && selected_end < selected_start) selected_end <- NA

    start_fmt <- if (is.na(selected_start)) "Unknown" else as.character(selected_start)
    end_fmt <- if (is.na(selected_end)) "Present" else as.character(selected_end)
    date_range <- paste0(start_fmt, " to ", end_fmt)

    station_name <- if ("name" %in% names(st_row)) as.character(st_row$name[1]) else "Unknown"
    station_id <- if ("id" %in% names(st_row) && !is.na(st_row$id[1]) && nzchar(trimws(as.character(st_row$id[1])))) as.character(st_row$id[1]) else "N/A"
    station_cbdh <- if ("id_9" %in% names(st_row) && !is.na(st_row$id_9[1]) && nzchar(trimws(as.character(st_row$id_9[1])))) as.character(st_row$id_9[1]) else "N/A"
    station_type <- if ("station_type" %in% names(st_row)) as.character(st_row$station_type[1]) else "Unknown"
    voivodeship <- if ("voivodeship" %in% names(st_row) && is_valid_str(st_row$voivodeship[1])) as.character(st_row$voivodeship[1]) else NULL
    params_summary <- if ("params_summary" %in% names(st_row)) as.character(st_row$params_summary[1]) else "Unknown"
    elevation <- if ("elevation" %in% names(st_row)) as.character(st_row$elevation[1]) else ""
    elev_fmt <- if (is.na(elevation) || elevation == "") "N/A" else paste0(elevation, " m")
    voiv_line <- if (!is.null(voivodeship)) {
      paste0("<span style='font-size:80%; color:#555;'>Voivodeship: ", htmltools::htmlEscape(voivodeship), "</span><br>")
    } else {
      ""
    }

    paste0(
      "<div style='font-size:16px; max-width: 350px;'>",
      "<b>", htmltools::htmlEscape(station_name), "</b><br>",
      "<span style='font-size:80%; color:#555;'>Code: ", htmltools::htmlEscape(station_id), "</span><br>",
      "<span style='font-size:80%; color:#555;'>CBDH Code: ", htmltools::htmlEscape(station_cbdh), "</span><br>",
      voiv_line,
      "<span style='font-size:80%; color:#555;'>Type: ", htmltools::htmlEscape(station_type), "</span><br>",
      "<span style='font-size:80%; color:#555;'>Parameters (", resolution_label, "): ", htmltools::htmlEscape(params_summary), "</span><br>",
      "<span style='font-size:80%; color:#555;'>Active: ", date_range, "</span><br>",
      "<span style='font-size:80%; color:#555;'>Elevation: ", elev_fmt, "</span>",
      "</div>"
    )
  }

  # Populate Voivodeship / Region dropdown choices from station metadata
  observe({
    df <- stations()
    req(!is.null(df) && nrow(df) > 0 && "voivodeship" %in% names(df))

    voivs <- sort(unique(na.omit(as.character(df$voivodeship))))
    voivs <- voivs[nzchar(trimws(voivs))]
    choices <- c("All Voivodeships" = "All", setNames(voivs, voivs))

    curr_cf <- isolate(selected_county())
    sel_cf <- if (has_county_filter(curr_cf) && curr_cf[1] %in% voivs) {
      as.character(curr_cf[1])
    } else {
      "All"
    }
    updateSelectizeInput(session, "county_filter", choices = choices, selected = sel_cf)
  })

  # Sync input$county_filter into selected_county reactiveVal
  observeEvent(input$county_filter, {
    cf <- input$county_filter
    if (!is_valid_str(cf)) {
      return()
    }
    avail_voiv <- tryCatch(isolate(stations()$voivodeship), error = function(e) NULL)
    resolved <- resolve_imgw_voivodeship(cf[1], available = avail_voiv)
    target_voiv <- if (is_valid_str(resolved)) resolved else trimws(as.character(cf[1]))
    if (!identical(isolate(selected_county()), target_voiv)) {
      selected_county(target_voiv)
    }
  }, ignoreNULL = TRUE, ignoreInit = TRUE)

  filtered_stations <- reactive({
    req(stations())
    edr <- effective_date_range()
    req(length(edr) >= 2 && !any(is.na(edr)))

    st_data <- stations()
    res <- resolution_key()
    user_start <- edr[1]
    user_end <- edr[2]
    res_start_col <- paste0("date_start_", res)
    res_end_col <- paste0("date_end_", res)

    if (!res_end_col %in% names(st_data)) st_data[[res_end_col]] <- st_data$date_end
    if (!"date_end_hourly" %in% names(st_data)) st_data$date_end_hourly <- st_data$date_end
    if (!"date_end_daily" %in% names(st_data)) st_data$date_end_daily <- st_data$date_end
    if (!"date_end_monthly" %in% names(st_data)) st_data$date_end_monthly <- st_data$date_end

    st_data <- st_data %>%
      filter(
        !is.na(!!sym(res_start_col)),
        !!sym(res_start_col) <= user_end,
        is.na(!!sym(res_end_col)) | !!sym(res_end_col) >= user_start
      )

    # Filter by Polish Voivodeship (county_filter)
    cf <- selected_county()
    if (has_county_filter(cf) && "voivodeship" %in% names(st_data)) {
      st_data <- st_data %>%
        filter(!is.na(voivodeship) & voivodeship == as.character(cf[1]))
    }

    if (!"data_order" %in% names(st_data)) st_data$data_order <- NA_character_
    if (nrow(st_data) > 0) {
      data_order_trim <- tolower(trimws(st_data$data_order))
      params_by_data_order <- params_by_resolution[[res]]
      params_by_station_type <- c(
        Synoptic = params_by_data_order[["synop"]],
        Climatological = params_by_data_order[["klimat"]],
        Precipitation = params_by_data_order[["opad"]]
      )

      st_data$params_summary <- unname(params_by_data_order[data_order_trim])
      missing_params <- is.na(st_data$params_summary) | st_data$params_summary == ""
      st_data$params_summary[missing_params] <- unname(params_by_station_type[st_data$station_type[missing_params]])
      st_data$params_summary[is.na(st_data$params_summary) | st_data$params_summary == ""] <- "Unknown"
      st_data$station_uid <- paste(st_data$id, st_data$name, sep = "|")
    } else {
      st_data$params_summary <- character(0)
      st_data$station_uid <- character(0)
    }

    st_data
  })

  # Selectize for station search (populated from master stations(), filtered only by Voivodeship;
  # server = FALSE avoids client-side selectize.clear() / transient "" events on choice updates)
  observe({
    df <- stations()
    req(!is.null(df) && nrow(df) > 0)

    cf <- selected_county()
    if (has_county_filter(cf) && "voivodeship" %in% names(df)) {
      df <- df %>% filter(!is.na(voivodeship) & voivodeship == as.character(cf[1]))
    }

    # De-duplicate by station_uid so choices are unique
    df_unique <- df %>%
      distinct(station_uid, .keep_all = TRUE)

    # Create named choices: display "Name (ID)" but value is station_uid
    if (nrow(df_unique) > 0) {
      stn_labels <- ifelse(!is.na(df_unique$id) & nzchar(df_unique$id) & df_unique$id != "NA",
                           paste0(df_unique$name, " (", df_unique$id, ")"),
                           df_unique$name)
      choices <- setNames(df_unique$station_uid, stn_labels)
    } else {
      choices <- character(0)
    }

    curr_uid <- isolate(current_station_uid())
    selected_val <- if (is_valid_str(curr_uid) && curr_uid[1] %in% df_unique$station_uid) {
      as.character(curr_uid[1])
    } else {
      ""
    }
    arm_suppress_selectize(1.5)
    updateSelectizeInput(session, "station_selector",
      choices = c("All" = "", choices),
      selected = selected_val,
      server = FALSE
    )
  })

  # Helper: Compute map bounding box for current Voivodeship filter (or full Poland)
  get_active_map_bbox <- function(force_full_poland = FALSE) {
    default_bbox <- c(14.1, 49.0, 24.1, 54.9)
    if (isTRUE(force_full_poland)) return(default_bbox)

    cf <- isolate(selected_county())
    if (!has_county_filter(cf)) return(default_bbox)

    df_sub <- tryCatch(isolate(filtered_stations()), error = function(e) NULL)
    if (is.null(df_sub) || nrow(df_sub) == 0) {
      st_all <- tryCatch(isolate(stations()), error = function(e) NULL)
      if (!is.null(st_all) && "voivodeship" %in% names(st_all)) {
        df_sub <- st_all %>% filter(!is.na(voivodeship) & voivodeship == as.character(cf[1]))
      }
    }
    if (is.null(df_sub) || nrow(df_sub) == 0) return(default_bbox)

    lons <- suppressWarnings(as.numeric(df_sub$lon))
    lats <- suppressWarnings(as.numeric(df_sub$lat))
    valid <- !is.na(lons) & !is.na(lats)
    if (!any(valid)) return(default_bbox)

    min_lon <- min(lons[valid])
    max_lon <- max(lons[valid])
    min_lat <- min(lats[valid])
    max_lat <- max(lats[valid])
    lon_pad <- max(0.15, (max_lon - min_lon) * 0.15)
    lat_pad <- max(0.10, (max_lat - min_lat) * 0.15)

    c(min_lon - lon_pad, min_lat - lat_pad, max_lon + lon_pad, max_lat + lat_pad)
  }

  zoom_to_active_extent <- function(force_full_poland = FALSE, clear_highlight = FALSE) {
    bbox <- get_active_map_bbox(force_full_poland = force_full_poland)
    proxy <- mapgl::maplibre_proxy("map")
    if (isTRUE(clear_highlight)) {
      proxy <- proxy %>% mapgl::clear_layer("selected-highlight")
    }
    proxy %>% mapgl::fit_bounds(bbox = bbox, animate = TRUE)

    js_cmd <- sprintf("
      setTimeout(function() {
        if (typeof document !== 'undefined') {
          document.querySelectorAll('.maplibregl-popup').forEach(function(el) { el.remove(); });
        }
        var mapInstance = null;
        if (window.HTMLWidgets && HTMLWidgets.find) {
          var w = HTMLWidgets.find('#map');
          if (w && w.getMap) mapInstance = w.getMap();
        }
        if (!mapInstance) {
          var mapEl = document.getElementById('map');
          if (mapEl && mapEl.__mapgl) mapInstance = mapEl.__mapgl;
        }
        if (mapInstance) {
          mapInstance.resize();
          mapInstance.fitBounds([[%f, %f], [%f, %f]], { padding: 20, duration: 800 });
        }
      }, 150);
    ", bbox[1], bbox[2], bbox[3], bbox[4])
    shinyjs::runjs(js_cmd)
  }

  # --- Centralized Deselection State & Map Reset ---
  clear_station_selection <- function(jump_to_map = TRUE, reset_county = FALSE) {
    clear_suppress_selectize()
    client_station_synced(NULL)
    current_station_uid(NULL)
    station_fetch_error(NULL)
    station_data(NULL)
    loading_status(FALSE)
    station_fetching(FALSE)
    reset_fetch()

    if (isTRUE(reset_county) && has_county_filter(isolate(selected_county()))) {
      set_county_filter("All", update_input = TRUE, suppress_effect = TRUE)
    }

    sel <- isolate(input$station_selector)
    if (!is.null(sel) && length(sel) > 0 && !is.na(sel[1]) && nzchar(trimws(as.character(sel[1]))) && !identical(as.character(sel[1]), "All")) {
      updateSelectizeInput(session, "station_selector", selected = "")
    }

    # When deselecting a station while on Dashboard, jump to Map View
    curr_tab <- isolate(input$main_nav)
    will_jump <- isTRUE(jump_to_map) && !is.null(curr_tab) && length(curr_tab) > 0 && !is.na(curr_tab[1]) && identical(as.character(curr_tab[1]), "Dashboard")
    if (will_jump) {
      bslib::nav_select("main_nav", "Map View")
      broadcast_state(view_override = "map")
    } else {
      broadcast_state()
    }

    zoom_to_active_extent(force_full_poland = isTRUE(reset_county), clear_highlight = TRUE)
  }

  # React to Voivodeship filter changes: auto-deselect station only if outside selected Voivodeship
  observeEvent(selected_county(), {
    if (isTRUE(isolate(suppress_next_county_effect()))) {
      suppress_next_county_effect(FALSE)
      return()
    }

    target_voiv <- selected_county()
    has_filter <- has_county_filter(target_voiv)

    curr_uid <- isolate(current_station_uid())
    station_cleared <- FALSE
    if (has_filter && is_valid_str(curr_uid)) {
      st_all <- isolate(stations())
      st_row <- st_all %>% filter(station_uid == curr_uid[1]) %>% slice(1)
      if (nrow(st_row) == 0) {
        parsed <- parse_station_uid(curr_uid[1])
        if (!is.na(parsed$id) && nzchar(parsed$id)) {
          st_row <- st_all %>% filter(id == parsed$id) %>% slice(1)
        }
      }
      if (nrow(st_row) > 0 && "voivodeship" %in% names(st_row)) {
        if (!identical(as.character(st_row$voivodeship[1]), as.character(target_voiv[1]))) {
          clear_station_selection(jump_to_map = TRUE)
          station_cleared <- TRUE
        }
      }
    }

    if (!station_cleared) {
      if (!is_valid_str(isolate(current_station_uid()))) {
        zoom_to_active_extent(force_full_poland = !has_filter, clear_highlight = FALSE)
      }
      if (isolate(url_initialized())) {
        broadcast_state()
      }
    }
  }, ignoreInit = TRUE)

  observeEvent(input$clear_station_sidebar, {
    clear_station_selection(jump_to_map = TRUE)
  })

  observeEvent(input$clear_station_chip, {
    clear_station_selection(jump_to_map = TRUE)
  })

  # Station Chip UI Overlay on Map
  output$station_chip_ui <- renderUI({
    uid <- current_station_uid()
    if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) {
      return(NULL)
    }
    meta <- tryCatch(selected_station(), error = function(e) NULL)
    if (is.null(meta) || nrow(meta) == 0) return(NULL)

    elev_num <- if ("elevation" %in% names(meta) && !is.na(meta$elevation[[1]])) {
      suppressWarnings(as.numeric(as.character(meta$elevation[[1]])))
    } else {
      NA_real_
    }
    elev_val <- if (!is.na(elev_num)) paste0(" (", round(elev_num, 0), " m)") else ""
    name_val <- if ("name" %in% names(meta) && !is.na(meta$name[[1]])) as.character(meta$name[[1]]) else ""
    id_val <- if ("id" %in% names(meta) && !is.na(meta$id[[1]])) as.character(meta$id[[1]]) else ""
    chip_parts <- c()
    if (nzchar(name_val)) chip_parts <- c(chip_parts, enc2utf8(name_val))
    if (nzchar(id_val) && id_val != "NA") chip_parts <- c(chip_parts, id_val)
    base_label <- if (length(chip_parts) > 0) paste(chip_parts, collapse = " - ") else "Station"
    chip_label <- paste0(base_label, elev_val)

    tags$div(
      class = "station-floating-chip",
      tags$span(class = "chip-dot"),
      tags$span(class = "chip-text", title = chip_label, chip_label),
      tags$button(
        type = "button",
        class = "btn-chip-clear",
        onclick = "event.stopPropagation(); Shiny.setInputValue('clear_station_chip', Date.now(), {priority: 'event'});",
        tags$span("Deselect")
      )
    )
  })
  outputOptions(output, "station_chip_ui", suspendWhenHidden = FALSE)

  # Handle station selection from dropdown
  observeEvent(input$station_selector, {
    stn_id <- input$station_selector
    if (!is.null(stn_id) && length(stn_id) > 0 && !is.na(stn_id[1]) && nzchar(trimws(as.character(stn_id[1]))) && !identical(as.character(stn_id[1]), "All")) {
      uid <- as.character(stn_id[1])
      client_station_synced(uid)
      if (!identical(isolate(current_station_uid()), uid)) {
        clear_suppress_selectize()
        current_station_uid(uid)
        station_fetch_error(NULL)

        st <- selected_station()
        if (!is.null(st) && nrow(st) > 0) {
          cf <- isolate(selected_county())
          if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) {
            set_county_filter("All", update_input = TRUE, suppress_effect = TRUE)
          }
          highlight_selected_station(st, move_map = TRUE)
        }
        # Trigger broadcast
        broadcast_state()
        bslib::nav_select("main_nav", "Dashboard")
      }
    } else if (!is.null(stn_id) && length(stn_id) > 0 && !is.na(stn_id[1]) && identical(as.character(stn_id[1]), "All")) {
      clear_suppress_selectize()
      client_station_synced(NULL)
      if (!is.null(isolate(current_station_uid()))) {
        clear_station_selection(jump_to_map = TRUE)
      }
    } else {
      cur_uid <- isolate(current_station_uid())
      if (is.null(cur_uid) || !nzchar(trimws(as.character(cur_uid[1])))) {
        return()
      }
      if (isTRUE(suppress_selectize_empty()) ||
          !identical(as.character(isolate(client_station_synced())), as.character(cur_uid[1]))) {
        return()
      }
      client_station_synced(NULL)
      clear_station_selection(jump_to_map = TRUE)
    }
  }, ignoreInit = TRUE)

  selected_station <- reactive({
    uid <- current_station_uid()
    if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) {
      return(NULL)
    }

    # 1. First attempt direct match on filtered_stations by station_uid
    st_filt <- tryCatch(filtered_stations(), error = function(e) NULL)
    if (!is.null(st_filt) && "station_uid" %in% names(st_filt)) {
      row <- st_filt %>%
        filter(station_uid == uid) %>%
        slice(1)
      if (nrow(row) > 0) return(row)
    }

    # 2. Fall back to parsing UID and searching full stations()
    parsed <- parse_station_uid(uid)
    st <- stations()

    # If UID has a name, try matching name (and id if available)
    row <- NULL
    if (!is.na(parsed$name) && parsed$name != "" && parsed$name != "NA") {
      if (!is.na(parsed$id) && parsed$id != "" && parsed$id != "NA") {
        row <- st %>%
          filter(id == parsed$id, name == parsed$name) %>%
          slice(1)
      } else {
        row <- st %>%
          filter(name == parsed$name) %>%
          slice(1)
      }
    }

    # Match by ID alone if ID is valid and name match was not found
    if ((is.null(row) || nrow(row) == 0) && !is.na(parsed$id) && parsed$id != "" && parsed$id != "NA") {
      row <- st %>%
        filter(id == parsed$id) %>%
        slice(1)
    }

    if (!is.null(row) && nrow(row) > 0) {
      if (!"station_uid" %in% names(row)) {
        row$station_uid <- uid
      }
      return(row)
    }

    NULL
  })

  highlight_selected_station <- function(st_row, move_map = TRUE) {
    req(nrow(st_row) > 0)

    lon_val <- suppressWarnings(as.numeric(st_row$lon[1]))
    lat_val <- suppressWarnings(as.numeric(st_row$lat[1]))
    if (is.na(lon_val) || is.na(lat_val)) {
      return(invisible(NULL))
    }

    popup_html <- NULL
    if ("popup_content" %in% names(st_row)) {
      popup_candidate <- as.character(st_row$popup_content[1])
      if (!is.na(popup_candidate) && nzchar(popup_candidate)) {
        popup_html <- popup_candidate
      }
    }
    if (is.null(popup_html)) {
      popup_html <- build_station_popup(st_row, res = isolate(resolution_key()))
    }

    highlight_df <- data.frame(
      popup_content = popup_html,
      lon = lon_val,
      lat = lat_val,
      stringsAsFactors = FALSE
    )
    highlight_sf <- sf::st_as_sf(highlight_df, coords = c("lon", "lat"), crs = 4326)

    proxy <- maplibre_proxy("map")
    if (move_map) {
      proxy <- proxy %>% fly_to(center = c(lon_val, lat_val), zoom = 8)
    }

    proxy %>%
      clear_layer("selected-highlight") %>%
      add_circle_layer(
        id = "selected-highlight",
        source = highlight_sf,
        circle_color = "#e53935",
        circle_radius = 10,
        circle_stroke_color = "#b71c1c",
        circle_stroke_width = 2,
        circle_opacity = 0.45,
        tooltip = get_column("popup_content")
      )
  }

  output$station_count <- renderText({
    req(!is.null(filtered_stations()))
    paste(nrow(filtered_stations()), "stations displayed.")
  })

  # Initialize Map
  output$map <- renderMaplibre({
    maplibre(
      style = ofm_positron_style,
      center = c(19.1451, 51.9194),
      zoom = 5.5
    ) %>%
      add_navigation_control(show_compass = FALSE, visualize_pitch = FALSE, position = "top-left")
  })

  # Invalidate map size when switching to Map View tab
  observeEvent(input$main_nav, {
    if (!is.null(input$main_nav) && length(input$main_nav) > 0 && !is.na(input$main_nav[1]) && identical(as.character(input$main_nav[1]), "Map View")) {
      shinyjs::runjs("
        setTimeout(function() {
          var mapInstance = null;
          if (window.HTMLWidgets && HTMLWidgets.find) {
            var w = HTMLWidgets.find('#map');
            if (w && w.getMap) mapInstance = w.getMap();
          }
          if (!mapInstance) {
            var mapEl = document.getElementById('map');
            if (mapEl && mapEl.__mapgl) mapInstance = mapEl.__mapgl;
          }
          if (mapInstance) {
            mapInstance.resize();
          }
        }, 150);
      ")
    }
  })

  # Zoom to extent of all stations (home button)
  observeEvent(input$zoom_home, {
    clear_station_selection(jump_to_map = TRUE, reset_county = TRUE)
  })

  # --- Basemap Switching Logic ---
  label_layer_ids <- c(
    # OpenFreeMap Positron & Bright common labels
    "waterway_line_label", "water_name_point_label", "water_name_line_label",
    "highway-name-path", "highway-name-minor", "highway-name-major",
    "highway-shield-non-us", "highway-shield-us-interstate", "road_shield_us",
    "airport", "label_other", "label_village", "label_town", "label_state",
    "label_city", "label_city_capital", "label_country_3", "label_country_2", "label_country_1",
    # Bright specific labels (POIs & Directions)
    "road_oneway", "road_oneway_opposite", "poi_r20", "poi_r7", "poi_r1", "poi_transit",
    # Dash variants (sometimes used in different versions)
    "waterway-line-label", "water-name-point-label", "water-name-line-label",
    "highway-shield-non-us", "highway-shield-us-interstate", "road-shield-us",
    "label-other", "label-village", "label-town", "label-state",
    "label-city", "label-city-capital", "label-country-3", "label-country-2", "label-country-1",
    # Legacy/Carto/OSM label names (for compatibility)
    "place_villages", "place_town", "place_country_2", "place_country_1",
    "place_state", "place_continent", "place_city_r6", "place_city_r5",
    "place_city_dot_r7", "place_city_dot_r4", "place_city_dot_r2", "place_city_dot_z7",
    "place_capital_dot_z7", "place_capital", "roadname_minor", "roadname_sec",
    "roadname_pri", "roadname_major", "motorway_name", "watername_ocean",
    "watername_sea", "watername_lake", "watername_lake_line", "poi_stadium",
    "poi_park", "poi_zoo", "airport_label", "country-label", "state-label",
    "settlement-major-label", "settlement-minor-label", "settlement-subdivision-label",
    "road-label", "waterway-label", "natural-point-label", "poi-label", "airport-label"
  )

  # Layers to hide in Satellite (Hybrid) mode to let the raster shows through
  # This includes all non-symbol layers (background, water, roads, boundaries, etc.)
  non_label_layer_ids <- c(
    "background", "park", "water", "landcover_ice_shelf", "landcover_glacier",
    "landuse_residential", "landcover_wood", "waterway", "building",
    "tunnel_motorway_casing", "tunnel_motorway_inner", "aeroway-taxiway",
    "aeroway-runway-casing", "aeroway-area", "aeroway-runway",
    "road_area_pier", "road_pier", "highway_path", "highway_minor",
    "highway_major_casing", "highway_major_inner", "highway_major_subtle",
    "highway_motorway_casing", "highway_motorway_inner", "highway_motorway_subtle",
    "railway_transit", "railway_transit_dashline", "railway_service",
    "railway_service_dashline", "railway", "railway_dashline",
    "highway_motorway_bridge_casing", "highway_motorway_bridge_inner",
    "boundary_3", "boundary_2", "boundary_disputed"
  )

  apply_label_visibility <- function(proxy, show_labels) {
    visibility <- if (isTRUE(show_labels)) "visible" else "none"
    for (layer_id in label_layer_ids) {
      tryCatch(
        {
          proxy %>% set_layout_property(layer_id, "visibility", visibility)
        },
        error = function(e) {
          # Layer may not exist in current style, ignore silently
        }
      )
    }
  }

  observeEvent(input$basemap,
    {
      proxy <- maplibre_proxy("map")
      basemap <- input$basemap

      # Explicitly remove any previously added raster layers
      old_layers <- isolate(current_raster_layers())
      if (length(old_layers) > 0) {
        for (layer_id in old_layers) {
          proxy %>% clear_layer(layer_id)
        }
        current_raster_layers(character(0))
      }

      if (basemap %in% c("ofm_positron", "ofm_bright")) {
        # VECTOR LOGIC (OpenFreeMap styles)
        style_url <- switch(basemap,
          "ofm_positron" = ofm_positron_style,
          "ofm_bright" = ofm_bright_style
        )

        proxy %>%
          set_style(style_url, preserve_layers = FALSE)

        # For OpenFreeMap sandwich, we want stations below labels
        stations_before_id("waterway_line_label")

        current_session <- session
        selected_basemap <- basemap

        later::later(function() {
          tryCatch({
            if (is_session_closed(current_session)) return()
            shiny::withReactiveDomain(current_session, shiny::isolate({
              # Race condition check
              current_basemap <- input$basemap
              if (!identical(current_basemap, selected_basemap)) {
                return()
              }

              # Trigger re-render of stations and apply label visibility
              apply_label_visibility(maplibre_proxy("map"), input$show_labels)
              style_change_trigger(style_change_trigger() + 1)
            }))
          }, error = function(e) NULL)
        }, delay = 0.5)
      } else if (basemap == "sentinel") {
        # HYBRID LOGIC (EOX Sentinel-2 Satellite + OpenFreeMap Labels/Roads)
        # Use Positron as the base for labels/roads
        proxy %>%
          set_style(ofm_positron_style, preserve_layers = FALSE)

        current_session <- session
        selected_basemap <- basemap

        later::later(function() {
          tryCatch({
            if (is_session_closed(current_session)) return()
            shiny::withReactiveDomain(current_session, shiny::isolate({
              current_basemap <- input$basemap
              if (!identical(current_basemap, selected_basemap)) {
                return()
              }

              unique_suffix <- as.numeric(Sys.time()) * 1000
              source_id <- paste0("sentinel_source_", unique_suffix)
              layer_id <- paste0("sentinel_layer_", unique_suffix)

              # Add Sentinel layer at the very bottom (before 'background')
              maplibre_proxy("map") %>%
                add_raster_source(id = source_id, tiles = sentinel_url, tileSize = 256, attribution = sentinel_attribution) %>%
                add_layer(
                  id = layer_id,
                  type = "raster",
                  source = source_id,
                  paint = list("raster-opacity" = 1),
                  before_id = "background"
                )

              # Hide all non-label vector layers so only satellite + symbols show
              for (layer_id_kill in non_label_layer_ids) {
                tryCatch(
                  {
                    maplibre_proxy("map") %>% set_layout_property(layer_id_kill, "visibility", "none")
                  },
                  error = function(e) {
                    # Layer might not exist, ignore
                  }
                )
              }

              # Ensure labels according to user preference
              apply_label_visibility(maplibre_proxy("map"), input$show_labels)

              # Stations should be above the satellite layer
              stations_before_id("waterway_line_label")
              current_raster_layers(c(layer_id))
              style_change_trigger(style_change_trigger() + 1)
            }))
          }, error = function(e) NULL)
        }, delay = 0.5)
      }
    },
    ignoreInit = TRUE
  )

  # Auto-refetch and adjust date window when resolution changes (single authoritative handler)
  observeEvent(input$temporal_resolution,
    {
      req(input$temporal_resolution)
      res_val <- tolower(trimws(as.character(input$temporal_resolution[1])))
      if (!res_val %in% c("hourly", "daily", "monthly")) {
        return()
      }
      prev_res <- isolate(selected_resolution())
      if (!identical(prev_res, res_val)) {
        has_url_dates(FALSE)
        selected_resolution(res_val)
      }

      edr <- isolate(effective_date_range())
      if (length(edr) < 2 || any(is.na(edr))) return()
      start <- edr[1]
      end <- edr[2]
      if (start > end) {
        tmp_d <- start; start <- end; end <- tmp_d
      }

      today <- Sys.Date()
      max_date <- if (identical(res_val, "monthly")) latest_monthly_archive_date() else today

      if (identical(res_val, "monthly")) {
        res <- check_and_limit_dates(start, end, "monthly", anchor = "end", from_resolution_switch = TRUE)
        monthly_auto_shifted(isTRUE(res$clamped_monthly_archive))
      } else if (identical(prev_res, "monthly") && isTRUE(isolate(monthly_auto_shifted()))) {
        monthly_auto_shifted(FALSE)
        new_end <- today
        new_start <- new_end - (if (identical(res_val, "hourly")) 90 else 366)
        res <- list(start = new_start, end = new_end, limited = TRUE, silent_restore = TRUE, msg = "")
      } else {
        res <- check_and_limit_dates(start, end, res_val, anchor = "end", from_resolution_switch = TRUE)
      }

      if (isTRUE(res$limited)) {
        prev_dates(c(res$start, res$end))
        updateDateRangeInput(session, "date_range", start = res$start, end = res$end, max = max_date)
        if (!isTRUE(res$silent_restore) && nzchar(res$msg)) {
          showNotification(paste0("Range adjusted to ", res$msg, " for ", res_val, " resolution."), type = "warning")
        }
      } else {
        prev_dates(c(start, end))
        updateDateRangeInput(session, "date_range", max = max_date)
      }

      if (isTRUE(isolate(url_initialized()))) {
        broadcast_state()
      }
    },
    ignoreInit = TRUE
  )

  # Auto-refetch and Smart Limit when Date Range Changes (single authoritative handler)
  observeEvent(input$date_range,
    {
      req(input$date_range)
      if (length(input$date_range) < 2) return()

      current_dates <- input$date_range
      current_start <- tryCatch(as.Date(current_dates[1]), error = function(e) NA)
      current_end <- tryCatch(as.Date(current_dates[2]), error = function(e) NA)
      if (is.na(current_start) || is.na(current_end)) {
        return()
      }
      if (current_start > current_end) {
        tmp_d <- current_start; current_start <- current_end; current_end <- tmp_d
      }

      last_dates <- isolate(prev_dates())
      if (!is.null(last_dates) && length(last_dates) >= 2 && !any(is.na(last_dates))) {
        last_pair <- tryCatch(as.Date(last_dates[1:2]), error = function(e) c(NA, NA))
        if (!any(is.na(last_pair)) && identical(c(current_start, current_end), last_pair)) {
          # Programmatic echo from updateDateRangeInput — preserve monthly_auto_shifted flag
          if (isTRUE(isolate(url_initialized()))) {
            broadcast_state()
          }
          return()
        }
      }

      # Genuine user edit (or testServer setInputs) — clear monthly auto-shift and URL date locks
      monthly_auto_shifted(FALSE)
      has_url_dates(FALSE)

      anchor <- "end"
      if (!is.null(last_dates) && length(last_dates) >= 2 && !any(is.na(last_dates))) {
        last_start <- tryCatch(as.Date(last_dates[1]), error = function(e) NA)
        if (!is.na(last_start) && current_start != last_start) {
          anchor <- "start"
        }
      }

      active_res <- isolate(resolution_key())
      max_date <- if (identical(active_res, "monthly")) latest_monthly_archive_date() else Sys.Date()
      res <- check_and_limit_dates(current_start, current_end, active_res, anchor = anchor, from_resolution_switch = FALSE)

      if (isTRUE(res$limited)) {
        prev_dates(c(res$start, res$end))
        updateDateRangeInput(session, "date_range", start = res$start, end = res$end, max = max_date)
        showNotification(paste0("Range adjusted to ", res$msg, "."), type = "warning")
      } else {
        prev_dates(c(current_start, current_end))
      }

      if (isTRUE(isolate(url_initialized()))) {
        broadcast_state()
      }
    },
    ignoreInit = TRUE
  )

  # Toggle Labels visibility
  observeEvent(input$show_labels,
    {
      apply_label_visibility(maplibre_proxy("map"), input$show_labels)
    },
    ignoreInit = TRUE
  )

  # Add Stations Layer
  observe({
    req(!is.null(filtered_stations()))
    style_change_trigger()

    st_data <- filtered_stations()
    current_session <- session
    if (nrow(st_data) == 0) {
      later::later(function() {
        tryCatch({
          if (is_session_closed(current_session)) return()
          shiny::withReactiveDomain(current_session, shiny::isolate({
            maplibre_proxy("map") %>%
              clear_layer("stations_layer") %>%
              clear_layer("selected-highlight")
          }))
        }, error = function(e) NULL)
      }, delay = 1.2)
      return()
    }

    res <- resolution_key()
    resolution_label <- switch(res,
      hourly = "Hourly",
      daily = "Daily",
      monthly = "Monthly",
      "Daily"
    )

    st_data$popup_content <- vapply(
      seq_len(nrow(st_data)),
      function(i) build_station_popup(st_data[i, , drop = FALSE], res = res),
      FUN.VALUE = character(1)
    )

    st_sf <- st_as_sf(st_data, coords = c("lon", "lat"), crs = 4326)
    st_sf$circle_color <- "navy"
    st_sf$circle_radius <- 6
    st_sf$circle_stroke_width <- 0
    st_sf$circle_opacity <- 0.7
    before_id_value <- stations_before_id()

    later::later(function() {
      tryCatch({
        if (is_session_closed(current_session)) return()
        shiny::withReactiveDomain(current_session, shiny::isolate({
          maplibre_proxy("map") %>%
            clear_layer("stations_layer") %>%
            add_circle_layer(
              id = "stations_layer",
              source = st_sf,
              circle_color = get_column("circle_color"),
              circle_radius = get_column("circle_radius"),
              circle_stroke_width = get_column("circle_stroke_width"),
              circle_opacity = 0.7,
              tooltip = get_column("popup_content"),
              before_id = before_id_value
            )
        }))
      }, error = function(e) NULL)
    }, delay = 1.2)

    selected_uid <- isolate(current_station_uid())
    if (!is.null(selected_uid) && selected_uid != "") {
      sel <- st_data %>%
        filter(station_uid == selected_uid) %>%
        slice(1)
      if (nrow(sel) > 0) {
        later::later(function() {
          tryCatch({
            if (is_session_closed(current_session)) return()
            shiny::withReactiveDomain(current_session, shiny::isolate({
              highlight_selected_station(sel, move_map = FALSE)
            }))
          }, error = function(e) NULL)
        }, delay = 1.25)
      } else {
        later::later(function() {
          tryCatch({
            if (is_session_closed(current_session)) return()
            shiny::withReactiveDomain(current_session, shiny::isolate({
              maplibre_proxy("map") %>% clear_layer("selected-highlight")
            }))
          }, error = function(e) NULL)
        }, delay = 1.25)
      }
    }
  })

  # Selection from map click
  observeEvent(input$map_feature_click, {
    clicked <- input$map_feature_click
    if (is.null(clicked)) {
      return()
    }

    layer_name <- clicked$layer_id
    if (is.null(layer_name) || length(layer_name) == 0 || is.na(layer_name[1])) {
      layer_name <- clicked$layer
    }
    if (is.null(layer_name) || length(layer_name) == 0 || is.na(layer_name[1]) || !identical(as.character(layer_name[1]), "stations_layer")) {
      return()
    }

    props <- clicked$properties
    if (is.null(props)) {
      return()
    }

    uid <- props$station_uid
    if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) {
      id_val <- props$id
      name_val <- props$name
      if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1]) &&
          !is.null(name_val) && length(name_val) > 0 && !is.na(name_val[1])) {
        uid <- paste0(id_val[1], "|", name_val[1])
      } else if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1])) {
        uid <- as.character(id_val[1])
      }
    }
    if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) {
      return()
    }

    uid <- as.character(uid)[1]
    current_station_uid(uid)
    station_fetch_error(NULL)

    st <- selected_station()
    if (!is.null(st) && nrow(st) > 0) {
      cf <- isolate(selected_county())
      if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) {
        set_county_filter("All", update_input = TRUE, suppress_effect = TRUE)
      }
      highlight_selected_station(st, move_map = TRUE)
      broadcast_state()
    }
    arm_suppress_selectize(1.5)
    updateSelectizeInput(session, "station_selector", selected = uid)
    bslib::nav_select("main_nav", "Dashboard")
  })

  # Stations table with double-click selection
  output$stations_table <- DT::renderDataTable({
    req(!is.null(filtered_stations()), input$temporal_resolution)
    st_data <- filtered_stations()
    resolution_col <- paste0("date_start_", resolution_key())
    end_col <- paste0("date_end_", resolution_key())
    if (!end_col %in% names(st_data)) st_data[[end_col]] <- st_data$date_end
    if (!"voivodeship" %in% names(st_data)) st_data$voivodeship <- NA_character_

    display_df <- st_data %>%
      transmute(
        UID = station_uid,
        ID = id,
        Name = name,
        Voivodeship = voivodeship,
        `CBDH Code` = id_9,
        Type = station_type,
        Parameters = params_summary,
        Lat = round(lat, 4),
        Lon = round(lon, 4),
        `Elevation (m)` = elevation,
        `Data Start` = as.character(!!sym(resolution_col)),
        `Data End` = ifelse(is.na(!!sym(end_col)), "Present", as.character(!!sym(end_col)))
      )

    DT::datatable(
      display_df,
      selection = "none",
      rownames = FALSE,
      options = list(
        pageLength = 25,
        scrollX = TRUE,
        dom = "frtip",
        order = list(list(2, "asc")),
        columnDefs = list(list(visible = FALSE, targets = 0))
      ),
      class = "compact stripe hover",
      callback = DT::JS("
        table.on('dblclick', 'tr', function() {
          var rowData = table.row(this).data();
          if (rowData !== undefined && rowData !== null) {
            Shiny.setInputValue('table_station_dblclick', rowData[0], {priority: 'event'});
          }
        });
      ")
    )
  })

  observeEvent(input$table_station_dblclick, {
    uid <- input$table_station_dblclick
    req(uid)

    uid <- as.character(uid)[1]
    current_station_uid(uid)
    station_fetch_error(NULL)

    st <- selected_station()
    if (!is.null(st) && nrow(st) > 0) {
      cf <- isolate(selected_county())
      if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) {
        set_county_filter("All", update_input = TRUE, suppress_effect = TRUE)
      }
      highlight_selected_station(st, move_map = TRUE)
      broadcast_state(view_override = "dashboard-plots")
    }
    arm_suppress_selectize(1.5)
    updateSelectizeInput(session, "station_selector", selected = uid)
    bslib::nav_select("main_nav", "Dashboard")
  })

  reset_fetch <- function() {
    fetch_stage(0)
    station_fetch_message("")
    fetch_current_token(as.numeric(Sys.time()))
    session$sendCustomMessage("unfreezeUI", list())
  }

  # Cancel loading handler
  observeEvent(input$cancel_loading, {
    loading_status(FALSE)
    station_fetching(FALSE)
    reset_fetch()
    showNotification("Loading cancelled by user.", type = "warning")
  })

  # Group fetch inputs using authoritative server-clamped resolution & date range
  fetch_trigger <- reactive({
    list(
      uid = current_station_uid(),
      res = resolution_key(),
      dr = effective_date_range()
    )
  }) %>% debounce(500)

  # Fetch station data using the debounced trigger
  observeEvent(fetch_trigger(),
    {
      req(url_initialized()) # Ensure URL params are applied first
      uid <- current_station_uid()
      edr <- effective_date_range()
      req(uid, length(edr) >= 2 && !any(is.na(edr)))

      st <- selected_station()
      req(!is.null(st), nrow(st) > 0)

      station_data(NULL)
      station_fetching(TRUE)
      loading_status(TRUE)
      station_fetch_error(NULL)

      # Broadcast state on re-fetch
      broadcast_state()

      start_date <- edr[1]
      end_date <- edr[2]
      active_fetch_dates(c(start_date, end_date))
      res <- resolution_key()

      msg_init <- paste0("Initializing fetch for ", st$name[1], "...")
      station_fetch_message(msg_init)
      session$sendCustomMessage("freezeUI", list(
        text = msg_init,
        station = st$name[1]
      ))

      # Stage 1: Init - Find files queue
      filesQueue <- imgw_fetch_station_data(
        station_id = st$id[1],
        resolution = res,
        start_date = start_date,
        end_date = end_date,
        data_order = st$data_order[1],
        station_type = st$station_type[1],
        station_id_9 = st$id_9[1]
      )

      if (is.null(filesQueue) || nrow(filesQueue) == 0) {
        if (isTRUE(attr(filesQueue, "server_unreachable"))) {
          station_fetch_error("The IMGW data server (danepubliczne.imgw.pl) is currently unavailable. Please try again later.")
        } else if (identical(res, "monthly")) {
          station_fetch_error("No downloadable IMGW monthly archives were found for this station within the selected date range. Try widening the start date to an earlier year.")
        } else {
          station_fetch_error("No downloadable IMGW files were found for this station within the selected date range.")
        }
        station_fetching(FALSE)
        loading_status(FALSE)
        reset_fetch()
        if (!is.null(isolate(current_station_uid()))) {
          bslib::nav_select("main_nav", "Dashboard")
        }
        return()
      }

      fetch_queue(filesQueue)
      fetch_queue_idx(1)
      parsed_data_list(list())
      fetch_current_token(as.numeric(Sys.time()))

      fetch_stage(2) # Go to Next
    },
    ignoreInit = TRUE
  )

  # Stage 2: Next File
  observe({
    req(fetch_stage() == 2)
    q <- fetch_queue()
    req(!is.null(q) && nrow(q) > 0)
    idx <- fetch_queue_idx()

    if (idx > nrow(q)) {
      fetch_stage(6) # Merge
    } else {
      # UI Update
      item <- q[idx, ]
      msg <- sprintf("Fetching %s (%d/%d)...", basename(item$url), idx, nrow(q))
      station_fetch_message(msg)

      st <- selected_station()
      session$sendCustomMessage("freezeUI", list(
        text = msg,
        station = if (!is.null(st) && nrow(st) > 0) st$name[1] else ""
      ))

      fetch_stage(4) # Download
    }
  })

  # Stage 4: Download and Parse Configured File
  observe({
    req(fetch_stage() == 4)
    q <- fetch_queue()
    req(!is.null(q) && nrow(q) > 0)
    idx <- fetch_queue_idx()
    item <- q[idx, ]
    token <- fetch_current_token()
    current_session <- session
    st <- selected_station()
    res <- resolution_key()

    # Yield thread
    later::later(function() {
      tryCatch({
        if (is_session_closed(current_session)) return()
        shiny::withReactiveDomain(current_session, shiny::isolate({
          if (fetch_current_token() != token) {
            return()
          }

          parsed_df <- tryCatch(
            {
              imgw_read_station_zip_url(
                zip_url = item$url,
                resolution = res,
                source_type = item$source,
                station_id = st$id[1],
                station_id_9 = st$id_9[1]
              )
            },
            error = function(e) {
              message("Error fetching data piece: ", conditionMessage(e))
              NULL
            }
          )

          if (!is.null(parsed_df) && nrow(parsed_df) > 0) {
            p_list <- parsed_data_list()
            p_list[[length(p_list) + 1]] <- parsed_df
            parsed_data_list(p_list)
          }

          # Advance
          fetch_queue_idx(idx + 1)
          fetch_stage(2) # Back to Next
        }))
      }, error = function(e) {
        message("[Stage 4 later error] ", conditionMessage(e))
        if (!is_session_closed(current_session)) {
          tryCatch(shiny::withReactiveDomain(current_session, shiny::isolate({
            station_fetching(FALSE)
            loading_status(FALSE)
            fetch_stage(0)
            current_session$sendCustomMessage("unfreezeUI", list())
          })), error = function(err) NULL)
        }
      })
    }, delay = 0.05)
  })

  # Stage 6: Merge Files
  observe({
    req(fetch_stage() == 6)
    token <- fetch_current_token()
    current_session <- session
    st <- selected_station()
    afd <- isolate(active_fetch_dates())
    edr <- if (!is.null(afd) && length(afd) >= 2 && !any(is.na(afd))) afd else isolate(effective_date_range())
    start_date <- edr[1]
    end_date <- edr[2]
    res <- resolution_key()

    msg_merge <- "Merging datasets..."
    station_fetch_message(msg_merge)
    session$sendCustomMessage("freezeUI", list(
      text = msg_merge,
      station = st$name[1]
    ))

    later::later(function() {
      tryCatch({
        if (is_session_closed(current_session)) return()
        shiny::withReactiveDomain(current_session, shiny::isolate({
          if (fetch_current_token() != token) {
            return()
          }
          p_list <- parsed_data_list()

          merged_df <- tryCatch(
            {
              imgw_process_downloaded_parts(
                parts = p_list,
                station_id_value = st$id[1],
                station_id_9_value = st$id_9[1],
                resolution = res,
                start_date = start_date,
                end_date = end_date,
                data_order = st$data_order[1],
                station_type = st$station_type[1]
              )
            },
            error = function(e) {
              message("Error merging chunks: ", conditionMessage(e))
              NULL
            }
          )

          if (is.null(merged_df) || nrow(merged_df) == 0) {
            if (identical(res, "monthly")) {
              station_fetch_error("No monthly observations found in this date window. IMGW's published monthly archives lag behind daily/hourly feeds — try widening the start date to an earlier year.")
            } else {
              station_fetch_error("No valid data rows found after merging files within this date range.")
            }
            station_data(NULL)
          } else {
            station_data(merged_df)
          }

          station_fetching(FALSE)
          loading_status(FALSE)
          fetch_stage(0)
          fetch_current_token(as.numeric(Sys.time()))

          if (!is.null(merged_df) && nrow(merged_df) > 0) {
            # Show "Plotting data..." while plots render
            current_session$sendCustomMessage("freezeUI", list(
              text = "Plotting data...",
              station = st$name[1]
            ))

            # Unfreeze after Shiny flush + client-side plotly rendering
            current_session$onFlushed(function() {
              if (!is_session_closed(current_session)) {
                current_session$sendCustomMessage("waitForPlots", list())
              }
            }, once = TRUE)
          } else {
            current_session$sendCustomMessage("unfreezeUI", list())
          }

          # Navigate to Dashboard only if station is still selected
          if (!is.null(current_station_uid())) {
            bslib::nav_select("main_nav", "Dashboard", session = current_session)
            broadcast_state()
          }
        }))
      }, error = function(e) {
        message("[Stage 6 later error] ", conditionMessage(e))
        if (!is_session_closed(current_session)) {
          tryCatch(shiny::withReactiveDomain(current_session, shiny::isolate({
            station_fetching(FALSE)
            loading_status(FALSE)
            fetch_stage(0)
            current_session$sendCustomMessage("unfreezeUI", list())
          })), error = function(err) NULL)
        }
      })
    }, delay = 0.05)
  })

  # Listen for tab and subtab changes explicitly to broadcast
  observeEvent(input$main_nav, {
    req(url_initialized())
    broadcast_state()
  })
  observeEvent(input$dashboard_subtabs, {
    req(url_initialized())
    broadcast_state()
  })

  # Dashboard UI states
  output$dashboard_station_header <- renderUI({
    st <- selected_station()
    if (is.null(st)) {
      return(NULL)
    }

    loaded <- station_data()
    # Determine Resolution Badge
    res_label <- switch(resolution_key(),
      hourly = "Hourly",
      daily = "Daily",
      monthly = "Monthly",
      "Daily"
    )
    res_class <- if (res_label == "Hourly") "bg-primary" else "bg-success"

    # Data Range Text
    if (is.null(loaded) || nrow(loaded) == 0) {
      if (isTRUE(station_fetching())) {
        dates_text <- "Loading..."
      } else {
        dates_text <- "No data loaded"
      }
    } else {
      dates_text <- paste(min(loaded$date, na.rm = TRUE), "to", max(loaded$date, na.rm = TRUE))
      dates_text <- paste0(dates_text, " (", nrow(loaded), " rows)")
    }

    # Helper for NULL/NA
    val_safe <- function(x, suffix = "") {
      if (is.null(x) || is.na(x) || x == "") {
        return("-")
      }
      paste0(x, suffix)
    }

    # Render Card
    card(
      style = "margin-bottom: 20px; border-left: 5px solid #007bff;",
      card_body(
        padding = 15,
        layout_columns(
          fill = FALSE,
          # Col 1: Station
          div(
            strong("Station"), br(),
            span(st$name[1], style = "font-size: 1.1rem;"), br(),
            tags$small(class = "text-muted", paste("ID:", val_safe(st$id[1]), "| CBDH:", val_safe(st$id_9[1])))
          ),
          # Col 2: Location
          div(
            strong("Location"), br(),
            span(paste0(round(st$lat[1], 4), "\u00b0N, ", round(st$lon[1], 4), "\u00b0E")), br(),
            tags$small(
              class = "text-muted",
              paste0(
                if ("voivodeship" %in% names(st) && is_valid_str(st$voivodeship[1])) paste0("Voivodeship: ", st$voivodeship[1], " | ") else "",
                "Type: ", st$station_type[1]
              )
            )
          ),
          # Col 3: Technical
          div(
            strong("Technical"), br(),
            span(val_safe(st$elevation[1], " m")), br(),
            span(class = paste("badge", res_class), res_label)
          ),
          # Col 4: Period/Data
          div(
            strong("Data Selection"), br(),
            span(dates_text)
          ),
          # Col 5: Actions
          div(
            class = "d-flex align-items-center justify-content-end",
            downloadButton(
              "downloadData",
              label = "Export Excel",
              class = "btn-sm btn-primary",
              icon = icon("file-excel")
            )
          )
        )
      )
    )
  })

  # Helper to prepare plot & summary data with cleaned status flags and English column labels
  get_plot_df <- reactive({
    df <- station_data()
    req(df)

    # Apply IMGW status rules (flag "8" -> NA; monthly phenomenon-day flag "9" -> NA) before translation
    df_clean_flags <- if (exists("clean_imgw_status_flags", mode = "function")) clean_imgw_status_flags(df) else df

    # Translate columns upfront for plotting so we have English labels
    df_translated <- translate_imgw_columns(df_clean_flags)

    # Ensure DateTime column exists for plotting functions
    if (!"DateTime" %in% names(df_translated)) {
      if ("Date/Time" %in% names(df_translated)) {
        df_translated$DateTime <- df_translated$`Date/Time`
      } else if ("Date" %in% names(df_translated)) {
        df_translated$DateTime <- as.POSIXct(df_translated$Date, tz = "UTC")
      } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated) && "Day" %in% names(df_translated) && "Hour" %in% names(df_translated)) {
        df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, df_translated$Day, df_translated$Hour, sep = "-"), format = "%Y-%m-%d-%H", tz = "UTC")
      } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated) && "Day" %in% names(df_translated)) {
        df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, df_translated$Day, sep = "-"), format = "%Y-%m-%d", tz = "UTC")
      } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated)) {
        df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, "01", sep = "-"), format = "%Y-%m-%d", tz = "UTC")
      }
    }

    if (exists("clean_imgw_data", mode = "function")) {
      df_translated <- clean_imgw_data(df_translated)
    }

    df_translated
  })

  output$dashboard_plots_ui <- renderUI({
    df <- get_plot_df()
    req(df)

    res <- resolution_key()
    
    # -----------------------------
    # SUMMARY CARDS LOGIC
    # -----------------------------
    format_ext_time <- function(idx) {
        if (length(idx) == 0 || is.na(idx) || is.na(idx[1])) return("")
        if (idx[1] > nrow(df) || idx[1] < 1) return("")
        t <- df$DateTime[idx[1]]
        if (is.null(t) || is.na(t)) return("")
        if (res %in% c("hourly", "synop")) format(t, "%b %d, %H:%M") else if (res == "annual") format(t, "%Y") else if (res == "monthly") format(t, "%b %Y") else format(t, "%b %d, %Y")
    }

    format_val <- function(val, suffix="", digits=1, divisor=1) {
        if (is.null(val) || is.na(val) || is.infinite(val)) return("—")
        paste0(round(val/divisor, digits), suffix)
    }

    cards <- tagList()
    add_card <- function(title, value, subtext, icon, color_class) {
        cards <<- tagList(cards, div(
            class = paste("glass-card", color_class),
            div(class = "glass-card-icon", bsicons::bs_icon(icon)),
            div(
                class = "glass-card-content",
                div(class = "glass-card-title", title),
                div(class = "glass-card-value", value),
                div(class = "glass-card-subtext", HTML(subtext))
            )
        ))
    }

    # Temperature
    temp_col <- if (identical(res, "monthly") && "Mean Monthly Temp [°C]" %in% names(df)) {
      "Mean Monthly Temp [°C]"
    } else if (identical(res, "daily") && "Mean Daily Temp [°C]" %in% names(df)) {
      "Mean Daily Temp [°C]"
    } else if ("Temp [°C]" %in% names(df)) {
      "Temp [°C]"
    } else if ("Mean Daily Temp [°C]" %in% names(df)) {
      "Mean Daily Temp [°C]"
    } else if ("Mean Monthly Temp [°C]" %in% names(df)) {
      "Mean Monthly Temp [°C]"
    } else {
      NULL
    }
    if (!is.null(temp_col) && any(!is.na(df[[temp_col]]))) {
        latest <- tail(na.omit(df[[temp_col]]), 1)
        avg_t <- mean(df[[temp_col]], na.rm = TRUE)
        min_col <- if ("Min Temp [°C]" %in% names(df) && any(!is.na(df[["Min Temp [°C]"]]))) "Min Temp [°C]" else temp_col
        max_col <- if ("Max Temp [°C]" %in% names(df) && any(!is.na(df[["Max Temp [°C]"]]))) "Max Temp [°C]" else temp_col
        min_t <- min(df[[min_col]], na.rm=TRUE)
        max_t <- max(df[[max_col]], na.rm=TRUE)
        min_idx <- which.min(df[[min_col]])
        max_idx <- which.max(df[[max_col]])
        add_card("Temperature", format_val(latest, "°C"), 
                 sprintf("Avg: %s | Min: %s (%s) | Max: %s (%s)", 
                         format_val(avg_t, "°C"), format_val(min_t, "°C"), format_ext_time(min_idx), format_val(max_t, "°C"), format_ext_time(max_idx)),
                 "thermometer-half", "card-red")
    }

    # Precipitation
    p_col <- if ("Precip 6h [mm]" %in% names(df)) "Precip 6h [mm]" else if ("Daily Precip [mm]" %in% names(df)) "Daily Precip [mm]" else if ("Monthly Precip [mm]" %in% names(df)) "Monthly Precip [mm]" else NULL
    if (!is.null(p_col) && any(!is.na(df[[p_col]]))) {
        latest <- tail(na.omit(df[[p_col]]), 1)
        total_p <- if (res %in% c("annual", "monthly")) mean(df[[p_col]], na.rm = TRUE) else sum(df[[p_col]], na.rm = TRUE)
        p_label <- if (res %in% c("annual", "monthly")) "Avg" else "Total"
        max_p_col <- if ("Max Daily Precip [mm]" %in% names(df) && any(!is.na(df[["Max Daily Precip [mm]"]]))) "Max Daily Precip [mm]" else if ("Max Precip [mm]" %in% names(df) && any(!is.na(df[["Max Precip [mm]"]]))) "Max Precip [mm]" else p_col
        max_p <- max(df[[max_p_col]], na.rm = TRUE)
        max_idx <- which.max(df[[max_p_col]])
        add_card("Precipitation", format_val(latest, " mm"), 
                 sprintf("%s: %s | Peak: %s (%s)", p_label, format_val(total_p, " mm"), format_val(max_p, " mm"), format_ext_time(max_idx)),
                 "cloud-rain", "card-blue")
    }

    # Wind
    w_col <- if ("Wind Speed [m/s]" %in% names(df)) "Wind Speed [m/s]" else if ("Mean Wind Speed [m/s]" %in% names(df)) "Mean Wind Speed [m/s]" else NULL
    if (!is.null(w_col) && any(!is.na(df[[w_col]]))) {
        latest <- tail(na.omit(df[[w_col]]), 1)
        avg_w <- mean(df[[w_col]], na.rm=TRUE)
        max_w_col <- if ("Max Gust [m/s]" %in% names(df) && any(!is.na(df[["Max Gust [m/s]"]]))) "Max Gust [m/s]" else if ("Wind Gust [m/s]" %in% names(df) && any(!is.na(df[["Wind Gust [m/s]"]]))) "Wind Gust [m/s]" else w_col
        max_w <- max(df[[max_w_col]], na.rm=TRUE)
        max_idx <- which.max(df[[max_w_col]])
        add_card("Wind Speed", format_val(latest, " m/s"),
                 sprintf("Avg: %s | Max Gust: %s (%s)", format_val(avg_w, " m/s"), format_val(max_w, " m/s"), format_ext_time(max_idx)),
                 "wind", "card-emerald")
    }

    # Humidity
    h_col <- if ("Relative Humidity [%]" %in% names(df)) "Relative Humidity [%]" else if ("Mean Rel Humidity [%]" %in% names(df)) "Mean Rel Humidity [%]" else NULL
    if (!is.null(h_col) && any(!is.na(df[[h_col]]))) {
        latest <- tail(na.omit(df[[h_col]]), 1)
        avg_h <- mean(df[[h_col]], na.rm=TRUE)
        min_h <- min(df[[h_col]], na.rm=TRUE)
        min_idx <- which.min(df[[h_col]])
        add_card("Relative Humidity", format_val(latest, "%", 0),
                 sprintf("Avg: %s | Min: %s (%s)", format_val(avg_h, "%", 0), format_val(min_h, "%", 0), format_ext_time(min_idx)),
                 "droplet", "card-cyan")
    }

    # Pressure
    pr_col <- if ("Station Pressure [hPa]" %in% names(df) && any(!is.na(df[["Station Pressure [hPa]"]]))) {
      "Station Pressure [hPa]"
    } else if ("Sea Level Pressure [hPa]" %in% names(df) && any(!is.na(df[["Sea Level Pressure [hPa]"]]))) {
      "Sea Level Pressure [hPa]"
    } else {
      NULL
    }
    if (!is.null(pr_col) && any(!is.na(df[[pr_col]]))) {
        latest <- tail(na.omit(df[[pr_col]]), 1)
        avg_pr <- mean(df[[pr_col]], na.rm=TRUE)
        min_pr <- min(df[[pr_col]], na.rm=TRUE)
        max_pr <- max(df[[pr_col]], na.rm=TRUE)
        min_idx <- which.min(df[[pr_col]])
        max_idx <- which.max(df[[pr_col]])
        add_card(if(pr_col == "Station Pressure [hPa]") "Station Pressure" else "Sea Level Pressure", format_val(latest, " hPa", 0),
                 sprintf("Avg: %s | Range: %s (%s) - %s (%s)", format_val(avg_pr, " hPa", 0), format_val(min_pr, " hPa", 0), format_ext_time(min_idx), format_val(max_pr, " hPa", 0), format_ext_time(max_idx)),
                 "speedometer2", "card-purple")
    }

    # Snow
    s_col <- if ("Snow Depth [cm]" %in% names(df)) "Snow Depth [cm]" else NULL
    if (!is.null(s_col) && any(!is.na(df[[s_col]]))) {
        latest <- tail(na.omit(df[[s_col]]), 1)
        max_s <- max(df[[s_col]], na.rm=TRUE)
        max_idx <- which.max(df[[s_col]])
        fresh_col <- "Fresh Snow Depth [cm]"
        fresh_sum <- if (fresh_col %in% names(df) && any(!is.na(df[[fresh_col]]))) {
            if (res %in% c("annual", "monthly")) mean(df[[fresh_col]], na.rm=TRUE) else sum(df[[fresh_col]], na.rm=TRUE)
        } else 0
        fresh_label <- if (res %in% c("annual", "monthly")) "Avg Fresh" else "Fresh"
        add_card("Snow Cover", format_val(latest, " cm", 0),
                 sprintf("Peak: %s (%s) | %s: %s", format_val(max_s, " cm", 0), format_ext_time(max_idx), fresh_label, format_val(fresh_sum, " cm", 0)),
                 "snow", "card-sky")
    }

    # Sunshine
    sun_col <- if ("Sunshine [h]" %in% names(df)) "Sunshine [h]" else if ("Monthly Sunshine [h]" %in% names(df)) "Monthly Sunshine [h]" else NULL
    if (!is.null(sun_col) && any(!is.na(df[[sun_col]]))) {
        latest <- tail(na.omit(df[[sun_col]]), 1)
        total_sun <- if (res %in% c("annual", "monthly")) mean(df[[sun_col]], na.rm=TRUE) else sum(df[[sun_col]], na.rm=TRUE)
        sun_label <- if (res %in% c("annual", "monthly")) "Avg" else "Total"
        add_card("Sunshine", format_val(latest, " hrs", 1),
                 sprintf("%s: %s", sun_label, format_val(total_sun, " hrs", 1)),
                 "sun", "card-amber")
    }

    # Cloud Cover
    c_col <- if ("Total Cloud Cover [okta]" %in% names(df)) "Total Cloud Cover [okta]" else if ("Mean Cloud Cover [okta]" %in% names(df)) "Mean Cloud Cover [okta]" else NULL
    if (!is.null(c_col) && any(!is.na(df[[c_col]]))) {
        latest <- tail(na.omit(df[[c_col]]), 1)
        avg_c <- mean(df[[c_col]], na.rm=TRUE)
        add_card("Cloud Cover", format_val(latest, " /8", 1),
                 sprintf("Avg: %s", format_val(avg_c, " /8", 1)),
                 "clouds", "card-slate")
    }

    plot_list <- tagList()

    # Temperature
    temp_cols <- c("Temp [°C]", "Mean Daily Temp [°C]", "Mean Monthly Temp [°C]", "Max Temp [°C]", "Min Temp [°C]")
    has_temp <- any(temp_cols %in% names(df)) && any(vapply(intersect(temp_cols, names(df)), function(col) any(!is.na(df[[col]])), logical(1)))
    if (has_temp) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("temperature_plot", height = "320px")))
    }

    # Precipitation
    precip_col <- if ("Precip 6h [mm]" %in% names(df)) "Precip 6h [mm]" else if ("Daily Precip [mm]" %in% names(df)) "Daily Precip [mm]" else if ("Monthly Precip [mm]" %in% names(df)) "Monthly Precip [mm]" else NULL
    has_precip <- !is.null(precip_col) && !all(is.na(df[[precip_col]]))
    if (has_precip) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("precipitation_plot", height = "320px")))
    }

    # Wind
    wind_col <- if ("Wind Speed [m/s]" %in% names(df)) "Wind Speed [m/s]" else if ("Mean Wind Speed [m/s]" %in% names(df)) "Mean Wind Speed [m/s]" else NULL
    has_wind <- !is.null(wind_col) && !all(is.na(df[[wind_col]]))
    if (has_wind) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("wind_plot", height = "320px")))
    }

    # Humidity
    hum_col <- if ("Relative Humidity [%]" %in% names(df)) "Relative Humidity [%]" else if ("Mean Rel Humidity [%]" %in% names(df)) "Mean Rel Humidity [%]" else NULL
    has_hum <- !is.null(hum_col) && !all(is.na(df[[hum_col]]))
    if (has_hum) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("humidity_plot", height = "320px")))
    }

    # Pressure
    has_press <- any(vapply(
      intersect(c("Station Pressure [hPa]", "Sea Level Pressure [hPa]"), names(df)),
      function(col) any(!is.na(df[[col]])),
      logical(1)
    ))
    if (has_press) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("pressure_plot", height = "320px")))
    }

    # Sunshine
    sun_col <- if ("Sunshine [h]" %in% names(df)) "Sunshine [h]" else if ("Monthly Sunshine [h]" %in% names(df)) "Monthly Sunshine [h]" else NULL
    has_sun <- !is.null(sun_col) && !all(is.na(df[[sun_col]]))
    if (has_sun) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("sunshine_plot", height = "320px")))
    }

    # Solar Radiation / Actinometry
    has_solar <- any(vapply(
      intersect(c("Solar Radiation [MJ/m²]", "Actinometry [J/cm²]"), names(df)),
      function(col) any(!is.na(df[[col]])),
      logical(1)
    ))
    if (has_solar) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("solar_plot", height = "320px")))
    }

    # Snow
    snow_col <- if ("Snow Depth [cm]" %in% names(df)) "Snow Depth [cm]" else if ("Fresh Snow Depth [cm]" %in% names(df)) "Fresh Snow Depth [cm]" else NULL
    has_snow <- !is.null(snow_col) && !all(is.na(df[[snow_col]]))
    if (has_snow) {
      plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("snow_plot", height = "320px")))
    }

    date_range_str <- ""
    if (nrow(df) > 0) {
        date_range_str <- paste(
            format(min(df$DateTime, na.rm=TRUE), "%d %b %Y"), "-",
            format(max(df$DateTime, na.rm=TRUE), "%d %b %Y")
        )
    }

    tagList(
        if (length(cards) > 0) {
            latest_obs_str <- if (nrow(df) > 0) paste("— Latest values as of:", format_ext_time(nrow(df))) else ""
            div(
                class = "w-100",
                div(class = "summary-cards-header", paste("Station Observations Summary", if (nchar(date_range_str) > 0) paste0("(", date_range_str, ")") else "", latest_obs_str)),
                div(class = "summary-cards-container", cards)
            )
        } else NULL,
        div(class = "row g-3", plot_list)
    )
  })

  # Excel Download Handler
  output$downloadData <- downloadHandler(
    filename = function() {
      st <- selected_station()
      req(st)
      res <- resolution_key()
      file_id <- imgw_coalesce_code(
        if ("id" %in% names(st)) st$id[1] else NULL,
        if ("id_9" %in% names(st)) st$id_9[1] else NULL
      ) %||% imgw_slugify(st$name[1])
      sprintf("imgw_%s_%s_%s.xlsx", file_id, res, format(Sys.Date(), "%Y%m%d"))
    },
    content = function(file) {
      df <- station_data()
      req(df)

      # Use same translation as table
      df_export <- translate_imgw_columns(df)

      # Ensure Date/Time format is Excel friendly (POSIXct usually works, but string is safer if consistency needed)
      # writexl handles dates well, so we can keep them as is or format them.
      # Let's keep them as native types for Excel calculation potential.

      writexl::write_xlsx(df_export, path = file)
    }
  )


  output$temperature_plot <- renderPlotly({
    create_temperature_plot_imgw(get_plot_df(), resolution_key())
  })

  output$precipitation_plot <- renderPlotly({
    create_precipitation_plot_imgw(get_plot_df(), resolution_key())
  })

  output$wind_plot <- renderPlotly({
    res <- resolution_key()
    if (res == "hourly") {
      create_wind_rose_imgw(get_plot_df(), res)
    } else {
      create_wind_plot_imgw(get_plot_df(), res)
    }
  })

  output$pressure_plot <- renderPlotly({
    create_pressure_plot_imgw(get_plot_df(), resolution_key())
  })

  output$humidity_plot <- renderPlotly({
    create_humidity_plot_imgw(get_plot_df(), resolution_key())
  })

  output$sunshine_plot <- renderPlotly({
    create_sunshine_plot_imgw(get_plot_df(), resolution_key())
  })

  output$solar_plot <- renderPlotly({
    create_solar_plot_imgw(get_plot_df(), resolution_key())
  })

  output$snow_plot <- renderPlotly({
    create_snow_plot_imgw(get_plot_df(), resolution_key())
  })

  output$station_data_table <- DT::renderDataTable({
    df <- station_data()
    req(df)

    df_display <- as.data.frame(df, stringsAsFactors = FALSE)

    # 1. Combine flags with paired measurement values via explicit IMGW_STATUS_TO_VALUE map
    raw_cols <- names(df_display)
    status_candidates <- intersect(names(IMGW_STATUS_TO_VALUE), raw_cols)

    for (scol in status_candidates) {
      base_var <- IMGW_STATUS_TO_VALUE[[scol]]

      if (!is.null(base_var) && base_var %in% raw_cols) {
        vals <- df_display[[base_var]]
        flags <- df_display[[scol]]

        formatted_vals <- vapply(seq_along(vals), function(i) {
          v <- vals[i]
          f <- flags[i]

          v_is_empty <- is.na(v) || trimws(as.character(v)) == ""
          f_is_empty <- is.na(f) || trimws(as.character(f)) == ""

          if (v_is_empty && f_is_empty) {
            return(NA_character_)
          }

          v_str <- if (v_is_empty) "" else as.character(v)

          # Translate precipitation type
          if (!v_is_empty && base_var == "ropt") {
            v_str <- switch(v_str,
              "5" = "Dew / Frost / Rime / Fog",
              "6" = "Rain / Drizzle",
              "7" = "Sleet / Snow / Ice Pellets",
              "8" = "Hail / Ice Grains",
              "9" = "Mixed Sleet / Hail / Snow",
              v_str
            )
          } else if (!v_is_empty && base_var == "roop") {
            v_str <- switch(toupper(v_str),
              "S" = "Snow",
              "W" = "Rain / Water",
              "M" = "Mixed",
              "L" = "Lód / Ice",
              v_str
            )
          } else if (!v_is_empty && base_var %in% c("rosw", "Dew Occurrence", "dzbl", "Lightning [0/1]", "dzps", "Snow Cover [0/1]", "Snow Cover")) {
            if (v_str == "0") {
              v_str <- "No"
            } else if (v_str == "1") v_str <- "Yes"
          } else if (!v_is_empty && base_var %in% c("sgr", "sgrn", "Ground State [code]", "Ground State")) {
            v_str <- switch(toupper(v_str),
              "Z" = "Frozen",
              "R" = "Thawed",
              v_str
            )
          } else if (!v_is_empty && base_var %in% c("pksn", "Snow Depth [cm]")) {
            if (v_str == "997") {
              v_str <- "< 0.5"
            } else if (v_str == "998") {
              v_str <- "Patchy"
            } else if (v_str == "999") v_str <- "Unmeasurable"
          } else if (!v_is_empty && base_var %in% c("pogb", "pogu", "Current Weather [code]", "Past Weather [code]", "Current Weather", "Past Weather")) {
            if (exists("WMO_WEATHER_CODES")) {
              # Remove leading zeros to match the WMO_WEATHER_CODES index format
              num_key <- as.character(as.numeric(v_str))
              if (num_key %in% names(WMO_WEATHER_CODES)) {
                v_str <- WMO_WEATHER_CODES[[num_key]]
              }
            }
          }

          if (!f_is_empty) {
            f_val <- trimws(as.character(f))
            is_monthly_phenom_missing <- (f_val == "9") && (base_var %in% IMGW_MONTHLY_PHENOM_DAY_COLS)
            if (f_val == "8" || is_monthly_phenom_missing) {
              # Status "8" (no observation) / status "9" on monthly phenomenon counts: discard dummy 0
              v_str <- ""
              f_html <- "<span class='text-muted' style='font-size:0.85em;' title='Quality Flag'>no observations</span>"
            } else if (f_val == "9" && v_is_empty) {
              # Daily/standard status 9 ("brak zjawiska" = phenomenon absent -> 0)
              v_str <- "0"
              f_html <- ""
            } else {
              f_display <- switch(f_val,
                "9" = "0",
                paste0("[", f_val, "]")
              )

              # Only show as a superscript/muted flag if it's not "0"
              if (f_display == "0") {
                if (v_str == "") v_str <- "0"
                f_html <- ""
              } else {
                f_html <- paste0("<span class='text-muted' style='font-size:0.85em; margin-left:4px;' title='Quality Flag'>", f_display, "</span>")
              }
            }
          } else {
            f_html <- ""
          }

          paste0(v_str, f_html)
        }, character(1))

        df_display[[base_var]] <- formatted_vals
        df_display[[scol]] <- NULL
      }
    }

    # Fallback translation for precipitation type columns without status flags
    for (col in c("ropt", "Precip Type 6h")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          switch(trimws(as.character(v)),
            "5" = "Dew / Frost / Rime / Fog",
            "6" = "Rain / Drizzle",
            "7" = "Sleet / Snow / Ice Pellets",
            "8" = "Hail / Ice Grains",
            "9" = "Mixed Sleet / Hail / Snow",
            as.character(v)
          )
        }, character(1))
      }
    }

    for (col in c("roop", "Precip Type")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          switch(trimws(toupper(as.character(v))),
            "S" = "Snow",
            "W" = "Rain / Water",
            "M" = "Mixed",
            "L" = "Lód / Ice",
            as.character(v)
          )
        }, character(1))
      }
    }

    for (col in c("rosw", "Dew Occurrence", "dzbl", "Lightning [0/1]", "dzps", "Snow Cover [0/1]", "Snow Cover")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          val <- trimws(as.character(v))
          if (val == "0") {
            return("No")
          }
          if (val == "1") {
            return("Yes")
          }
          return(val)
        }, character(1))
      }
    }

    for (col in c("sgr", "sgrn", "Ground State [code]", "Ground State")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          switch(trimws(toupper(as.character(v))),
            "Z" = "Frozen",
            "R" = "Thawed",
            as.character(v)
          )
        }, character(1))
      }
    }

    for (col in c("pksn", "Snow Depth [cm]")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          val <- trimws(as.character(v))
          if (val == "997") {
            return("< 0.5")
          }
          if (val == "998") {
            return("Patchy")
          }
          if (val == "999") {
            return("Unmeasurable")
          }
          return(val)
        }, character(1))
      }
    }

    for (col in c("pogb", "pogu", "Current Weather [code]", "Past Weather [code]", "Current Weather", "Past Weather")) {
      if (col %in% names(df_display)) {
        df_display[[col]] <- vapply(df_display[[col]], function(v) {
          if (is.na(v) || trimws(as.character(v)) == "") {
            return("")
          }
          if (exists("WMO_WEATHER_CODES")) {
            num_key <- as.character(as.numeric(trimws(as.character(v))))
            if (num_key %in% names(WMO_WEATHER_CODES)) {
              return(WMO_WEATHER_CODES[[num_key]])
            }
          }
          return(as.character(v))
        }, character(1))
      }
    }

    # Use helper function for renaming
    df_display <- translate_imgw_columns(df_display)

    # Remove structural and status clutter from the UI table
    cols_to_remove <- c(
      "Station ID", "Station Name", "Year", "Month", "Day", "Hour", "Minute",
      "station_id", "station_name", "year", "month", "day", "hour", "minute",
      "Date", "date", "Source", "source", "Source File", "source_file",
      "Resolution", "resolution", "Source Rank", "source_rank"
    )
    df_display <- df_display[, !names(df_display) %in% cols_to_remove, drop = FALSE]

    # Hide columns that are ALL NA or empty
    empty_cols <- names(df_display)[vapply(df_display, function(x) {
      if (is.character(x)) {
        all(is.na(x) | x == "")
      } else {
        all(is.na(x))
      }
    }, logical(1))]
    if (length(empty_cols) > 0) {
      df_display <- df_display[, !names(df_display) %in% empty_cols, drop = FALSE]
    }

    # Clean up any leftover status columns
    status_cols <- grep("^Status:", names(df_display), value = TRUE)
    if (length(status_cols) > 0) {
      df_display <- df_display[, !names(df_display) %in% status_cols, drop = FALSE]
    }

    list_cols <- vapply(df_display, is.list, logical(1))
    if (any(list_cols)) {
      df_display[list_cols] <- lapply(df_display[list_cols], function(x) {
        vapply(x, function(v) paste(v, collapse = ", "), character(1))
      })
    }
    if ("Date/Time" %in% names(df_display)) {
      df_display$`Date/Time` <- format(df_display$`Date/Time`, "%Y-%m-%d %H:%M:%S")
    }

    # Reorder columns by meteorological relevance
    col_priority_patterns <- c(
      "Date/Time",
      # Temperature
      "Temp \\[", "Max Temp", "Min Temp", "Mean.*Temp", "Dew Point",
      "Wet Bulb",
      # Precipitation
      "Precip", "Rain Duration", "Snow Duration", "Rain\\+Snow",
      # Pressure
      "Station Pressure", "Sea Level Pressure", "Pressure Tend", "Pressure Change",
      # Humidity
      "Relative Humidity", "Vapour Pressure", "Humidity Deficit",
      # Wind
      "Wind Speed", "Wind Dir", "Wind Gust", "Max Gust", "Gust Hour", "Gust Minute",
      "Wind >=",
      # Sunshine / Radiation
      "Sunshine", "Actinometry",
      # Snow
      "Snow Depth", "Snow Water", "Fresh Snow", "Snow Plot", "Snow Type",
      "Snow Cover",
      # Clouds / Visibility
      "Cloud", "Visibility", "Auto Visibility",
      # Ground / Soil temp
      "Ground State", "Soil Temp", "Lower Isotherm", "Upper Isotherm",
      # Ice / misc
      "Ice Indicator", "Ventilation",
      # Phenomena durations
      "Hail", "Fog", "Mist", "Rime", "Glaze", "Blizzard", "Haze",
      "Thunder", "Dew", "Frost", "Lightning",
      # Weather codes
      "Current Weather", "Past Weather", "Precip Type"
    )

    current_cols <- names(df_display)
    ordered_cols <- character(0)
    for (pat in col_priority_patterns) {
      matches <- grep(pat, current_cols, ignore.case = TRUE, value = TRUE)
      matches <- setdiff(matches, ordered_cols)
      ordered_cols <- c(ordered_cols, matches)
    }
    remaining <- setdiff(current_cols, ordered_cols)
    df_display <- df_display[, c(ordered_cols, remaining), drop = FALSE]

    DT::datatable(
      df_display,
      escape = FALSE,
      options = list(
        pageLength = 25,
        scrollX = TRUE,
        dom = "frtip",
        order = if ("Date/Time" %in% names(df_display)) list(list(which(names(df_display) == "Date/Time") - 1, "desc")) else list(list(0, "asc"))
      ),
      rownames = FALSE,
      class = "compact stripe hover"
    )
  })

  output$dashboard_content <- renderUI({
    uid <- current_station_uid()
    if (is.null(uid) || uid == "") {
      return(
        tags$div(
          style = "height: 560px; display: flex; align-items: center; justify-content: center; color: #999;",
          "Select a station from the map or Stations Info table to load data."
        )
      )
    }

    if (isTRUE(station_fetching())) {
      return(
        tags$div(
          style = "padding: 20px;",
          uiOutput("dashboard_station_header"),
          tags$div(
            class = "alert alert-info d-flex align-items-center gap-2",
            tags$div(class = "spinner-border spinner-border-sm", role = "status"),
            tags$span(station_fetch_message())
          )
        )
      )
    }

    err <- station_fetch_error()
    if (!is.null(err) && nzchar(err)) {
      return(
        tags$div(
          style = "padding: 20px;",
          uiOutput("dashboard_station_header"),
          tags$div(class = "alert alert-warning", err)
        )
      )
    }

    df <- station_data()
    if (is.null(df) || nrow(df) == 0) {
      return(
        tags$div(
          style = "padding: 20px;",
          uiOutput("dashboard_station_header"),
          tags$div(class = "alert alert-secondary", "No data loaded for the current selection.")
        )
      )
    }

    tagList(
      uiOutput("dashboard_station_header"),
      navset_card_pill(
        id = "dashboard_subtabs",
        nav_panel(
          title = "Plots",
          uiOutput("dashboard_plots_ui")
        ),
        nav_panel(
          title = "Data",
          div(
            style = "margin-top: 10px;",
            DT::dataTableOutput("station_data_table")
          )
        )
      )
    )
  })
}