File size: 131,905 Bytes
3fee36c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
# server.R for EuroMeteo Explorer

# Helper function for label generation
generate_station_label <- function(name, id, country, start_date, end_date, detailed_summary, resolution_info, val = NULL, label_name = "Observation", unit = "", missing_label = NULL, missing_color = "#8A8F98") {
    tryCatch(
        {
            val_html <- ""
            if (!is.null(val) && !is.na(val)) {
                # Determine color based on label_name
                color <- if (grepl("Temperature", label_name, ignore.case = TRUE)) {
                    if (exists("temp_to_color")) temp_to_color(val) else "#0056b3"
                } else if (grepl("Precipitation", label_name, ignore.case = TRUE)) {
                    if (exists("precip_to_color")) precip_to_color(val) else "#0056b3"
                } else if (grepl("Pressure", label_name, ignore.case = TRUE)) {
                    if (exists("pressure_to_color")) pressure_to_color(val) else "#0056b3"
                } else if (grepl("Wind Speed", label_name, ignore.case = TRUE)) {
                    if (exists("wind_speed_to_color")) wind_speed_to_color(val) else "#0056b3"
                } else {
                    "#0056b3"
                }

                val_html <- paste0(
                    "<div style='margin: 12px 0; padding: 10px; background: ", color, "10; border: 1px solid ", color, "30; border-radius: 8px; text-align: center; box-shadow: inset 0 1px 2px rgba(0,0,0,0.05);'>",
                    "<div style='font-size: 0.75em; color: #666; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; margin-bottom: 4px;'>", htmltools::htmlEscape(label_name), "</div>",
                    "<div style='font-size: 2em; font-weight: 900; color: ", color, "; line-height: 1; display: flex; align-items: baseline; justify-content: center;'>",
                    round(val, 1),
                    "<span style='font-size: 0.5em; margin-left: 3px; font-weight: 600;'>", htmltools::htmlEscape(unit), "</span>",
                    "</div>",
                    "</div>"
                )
            } else if (!is.null(missing_label) && !is.na(missing_label)) {
                color <- missing_color
                val_html <- paste0(
                    "<div style='margin: 12px 0; padding: 10px; background: ", color, "10; border: 1px solid ", color, "30; border-radius: 8px; text-align: center; box-shadow: inset 0 1px 2px rgba(0,0,0,0.05);'>",
                    "<div style='font-size: 0.75em; color: #666; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; margin-bottom: 4px;'>", htmltools::htmlEscape(label_name), "</div>",
                    "<div style='font-size: 1.4em; font-weight: 800; color: ", color, "; line-height: 1; display: flex; align-items: baseline; justify-content: center;'>",
                    htmltools::htmlEscape(missing_label),
                    "</div>",
                    "</div>"
                )
            }

            paste0(
                "<div style='font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif; min-width: 250px; max-width: 300px; padding: 4px;'>",
                # Header Section
                "<div style='border-bottom: 2px solid #f0f0f0; padding-bottom: 10px; margin-bottom: 10px;'>",
                "<div style='font-size: 1.15em; font-weight: 800; color: #1a1a1a; line-height: 1.3; margin-bottom: 6px;'>", htmltools::htmlEscape(name), "</div>",
                "<div style='display: flex; justify-content: space-between; align-items: center;'>",
                "<span style='font-size: 0.8em; color: #0056b3; font-weight: 700; background: #eef4ff; padding: 3px 8px; border-radius: 20px; border: 1px solid #d0e1ff;'>", htmltools::htmlEscape(country), "</span>",
                "<span style='font-size: 0.75em; color: #888; font-family: monospace; background: #f5f5f5; padding: 2px 5px; border-radius: 4px;'>", htmltools::htmlEscape(id), "</span>",
                "</div>",
                "</div>",

                # Value Section (if available)
                val_html,

                # Parameters & Status Section
                "<div style='background: #fafafa; border-radius: 8px; padding: 10px; border: 1px solid #f0f0f0;'>",
                "<div style='font-size: 0.75em; color: #777; font-weight: 700; margin-bottom: 6px; text-transform: uppercase; display: flex; align-items: center; gap: 4px;'>",
                "<span style='width: 8px; height: 8px; background: #28a745; border-radius: 50%; display: inline-block;'></span> Status & Capabilities",
                "</div>",
                "<div style='font-size: 0.85em; color: #333; line-height: 1.5;'>",
                resolution_info,
                "</div>",
                "</div>",
                "</div>",
                "</div>"
            )
        },
        error = function(e) {
            paste0("<div style='padding:10px;'><b>", htmltools::htmlEscape(name), "</b><br><small color='#888'>(", id, ")</small></div>")
        }
    )
}

server <- function(input, output, session) {
    # Helper to get target time anchored to sidebar end date
    get_target_time <- function(hours_val) {
        req(input$date_range)
        end_d <- input$date_range[2]

        # Consistent UTC time for comparison
        now_utc <- lubridate::now("UTC")
        today_utc <- as.Date(now_utc)

        if (as.Date(end_d) >= today_utc) {
            # Today: anchor to current hour with 30-min buffer
            base_time <- lubridate::floor_date(now_utc, "hour")

            # If current minute < 30, data for this hour is likely sparse.
            # Shift anchor back by 1 hour.
            if (lubridate::minute(now_utc) < 30) {
                base_time <- base_time - 3600
            }
        } else {
            # Past date: anchor to 23:00 of that day
            base_time <- as.POSIXct(end_d, tz = "UTC") + (23 * 3600)
        }
        base_time - (as.numeric(hours_val) * 3600)
    }

    # --- Reactive Values ---
    current_station_id <- reactiveVal(NULL)
    station_data <- reactiveVal(NULL) # The loaded data
    loading_status <- reactiveVal(FALSE)
    loading_diagnostics <- reactiveVal("")
    map_fetch_token <- reactiveVal(0)
    map_fetch_active <- reactiveVal(FALSE)
    map_render_pending <- reactiveVal(FALSE)
    map_render_token <- reactiveVal(NULL)
    plot_render_pending <- reactiveVal(FALSE)  # Guard: TRUE while dashboard plots are rendering
    fetch_pending <- reactiveVal(FALSE)        # Guard: TRUE between clicking station and fetch start
    initial_map_bootstrap <- reactiveVal(TRUE)
    bootstrap_active <- reactiveVal(TRUE)      # Keeps overlay until stations are rendered
    initial_stations_queued <- reactiveVal(FALSE) # Track if stations have been queued for rendering
    previous_station_choices <- reactiveVal(NULL) # Track previous choices to avoid blink
    url_initialized <- reactiveVal(FALSE) # Track if URL params have been applied
    current_resolution <- reactiveVal("Hourly") # Internal default resolution
    previous_date_range <- reactiveVal(NULL) # Track for 3-month constraint
    pending_url_country <- reactiveVal(NULL) # Country from URL to apply when stations load
    pending_url_station <- reactiveVal(NULL) # Station ref from URL to apply when stations load

    # MapLibre Reactive Values
    style_change_trigger <- reactiveVal(0) # Trigger station re-render after style change
    map_initialized <- reactiveVal(FALSE) # Track if map bounds have been set
    stations_before_id <- reactiveVal("waterway_line_label") # Default OFM label layer for initial station ordering
    current_raster_layers <- reactiveVal(character(0)) # Track dynamically added raster layers
    basemap_debounced <- shiny::debounce(reactive(input$basemap), 200)

    # Date Range Constraint (Max 3 months)
    observeEvent(input$date_range, {
        req(input$date_range)
        new_range <- input$date_range
        prev_range <- previous_date_range()

        # Initialize if NULL
        if (is.null(prev_range)) {
            previous_date_range(new_range)
            return()
        }

        # Check if range is > 31 days (~1 month)
        diff_days <- as.numeric(difftime(new_range[2], new_range[1], units = "days"))

        if (diff_days > 31) {
            # Determine which date changed
            if (!identical(new_range[2], prev_range[2])) {
                # End date changed, shift start date forward
                new_start <- new_range[2] - 31
                updateDateRangeInput(session, "date_range", start = new_start)
            } else if (!identical(new_range[1], prev_range[1])) {
                # Start date changed, shift end date backward
                new_end <- new_range[1] + 31
                updateDateRangeInput(session, "date_range", end = new_end)
            }
        } else {
            # Update tracking value only if valid
            previous_date_range(new_range)
        }
    })

    # Track last selected department to prevent auto-zoom on resolution change
    last_dept <- reactiveVal("All")

    # Map bounds for Europe (MeteoGate) - Broadened to zoom out one level
    map_bounds <- list(
        lat_min = 30.0,
        lat_max = 75.0,
        lng_min = -25.0,
        lng_max = 55.0
    )


    station_internal_cols <- c(
        "station_id", "station_name", "standard_name", "value", "param_name",
        "level", "method", "period", "period_seconds", "method_rank", "level_rank",
        "temp", "rh", "wind_dir", "pressure", "pressure_sea", "pressure_station", "precip", "solar_global", "dew_point"
    )

    get_station_display_cols <- function(df) {
        all_cols <- names(df)
        display_cols <- all_cols[!(all_cols %in% station_internal_cols)]

        alias_map <- attr(df, "preferred_alias_map")
        if (!is.null(alias_map) && length(alias_map) > 0) {
            alias_names <- names(alias_map)
            for (alias in alias_names) {
                if (is.null(alias) || is.na(alias) || !nzchar(alias)) next
                if (!(alias %in% display_cols)) next

                variant_col <- alias_map[[alias]]
                if (is.null(variant_col) || is.na(variant_col) || !nzchar(variant_col)) next
                if (variant_col %in% display_cols && variant_col != alias) {
                    display_cols <- setdiff(display_cols, alias)
                }
            }
        }

        # Remove columns that are true value-duplicates over the current selection.
        # Keep the one with the shortest name (usually the most general/clean one).
        display_cols <- display_cols[order(nchar(display_cols))]

        kept_cols <- character(0)
        for (col in display_cols) {
            if (col == "datetime") {
                kept_cols <- c(kept_cols, col)
                next
            }

            is_duplicate <- FALSE
            for (prev_col in kept_cols) {
                if (prev_col == "datetime") next

                v1 <- df[[col]]
                v2 <- df[[prev_col]]
                if (length(v1) != length(v2)) next

                same <- if (is.numeric(v1) && is.numeric(v2)) {
                    (is.na(v1) & is.na(v2)) | (!is.na(v1) & !is.na(v2) & abs(v1 - v2) <= 1e-9)
                } else {
                    (is.na(v1) & is.na(v2)) | (!is.na(v1) & !is.na(v2) & as.character(v1) == as.character(v2))
                }

                if (all(same)) {
                    is_duplicate <- TRUE
                    break
                }
            }

            if (!is_duplicate) {
                kept_cols <- c(kept_cols, col)
            }
        }

        # Restore original order but filter to kept ones
        final_cols <- all_cols[all_cols %in% kept_cols]
        display_cols <- final_cols[final_cols %in% display_cols]

        # Apply custom weather column sorting (Grouping and Precipitation order)
        display_cols <- sort_weather_columns(display_cols)

        display_cols
    }

    format_wind_speed_decimals <- function(df, digits = 1) {
        if (is.null(df) || nrow(df) == 0) {
            return(df)
        }

        wind_cols <- names(df)[grepl("^(wind_speed|wind_gust|wind_speed_of_gust)", names(df))]
        if (length(wind_cols) == 0) {
            return(df)
        }

        for (col in wind_cols) {
            if (is.numeric(df[[col]])) {
                df[[col]] <- round(df[[col]], digits)
            }
        }

        df
    }

    queue_map_render <- function(message = "Plotting stations...") {
        if (!isTRUE(isolate(map_render_pending()))) {
            return()
        }

        token <- isolate(map_render_token())
        if (is.null(token)) {
            map_render_pending(FALSE)
            return()
        }

        session$sendCustomMessage("awaitMapRender", list(
            mapId = "map",
            token = token,
            text = message
        ))
    }

    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
                }
            )
        }
    }

    # Helper: Parse URL query string
    parse_url_params <- function(query_string) {
        if (is.null(query_string) || query_string == "" || query_string == "?") {
            return(list())
        }
        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
    }

    # Helper: Broadcast current state to parent page
    broadcast_state <- function(view_override = NULL) {
        # Get scalar values from current selection
        sid <- current_station_id()
        st_meta <- NULL
        if (!is.null(sid)) {
            # Use all_stations() to lookup metadata
            # We use isolate to prevent cyclic dependencies if called from an observer
            # asking for this data
            all <- isolate(all_stations())
            if (!is.null(all)) {
                st_meta <- all %>% filter(id == sid)
            }
        }

        station_id <- if (!is.null(st_meta) && nrow(st_meta) > 0) as.character(st_meta$id[1]) else NULL
        station_name <- if (!is.null(st_meta) && nrow(st_meta) > 0) as.character(st_meta$name[1]) else NULL
        s_country <- if (!is.null(st_meta) && nrow(st_meta) > 0) {
            as.character(st_meta$country[1])
        } else if (!is.null(input$country_selector) && length(input$country_selector) > 0 && !("All Countries" %in% input$country_selector)) {
            paste(input$country_selector, collapse = ", ")
        } else {
            NULL
        }


        resolution <- current_resolution()

        main_tab <- 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 <- input$dashboard_subtabs
                if (!is.null(subtab) && subtab == "Data") {
                    "dashboard-data"
                } else {
                    "dashboard-plots"
                }
            } else {
                "map"
            }
        } else {
            "map"
        }

        # Build date range values for the payload
        dr_start <- if (!is.null(input$date_range[1])) as.character(input$date_range[1]) else NULL
        dr_end   <- if (!is.null(input$date_range[2])) as.character(input$date_range[2]) else NULL

        # Build list of stations for the selected country (for dynamic text rendering in parent)
        c_stations <- NULL
        if (!is.null(s_country) && s_country != "All Countries") {
            st_all <- all_stations()
            if (!is.null(st_all) && nrow(st_all) > 0) {
                c_sub <- st_all[st_all$country == s_country, ]
                
                # Filter by selected parameter to match SSR behavior (only show valid stations)
                if (!is.null(input$map_parameter) && "available_params" %in% names(c_sub)) {
                    param_regex <- if (input$map_parameter == "precipitation_amount") {
                        "precipitation_amount|rainfall_amount"
                    } else {
                        input$map_parameter
                    }
                    c_sub <- c_sub[grepl(param_regex, c_sub$available_params, ignore.case = TRUE), ]
                }
                
                if (nrow(c_sub) > 0) {
                    c_stations <- lapply(seq_len(nrow(c_sub)), function(i) list(name = c_sub$name[i], id = c_sub$id[i]))
                }
            }
        }

        session$sendCustomMessage("updateParentURL", list(
            station = station_name, # Use Name instead of ID for URL
            stationName = station_name,
            stationId = station_id,
            country = s_country,
            countryStations = c_stations,
            resolution = resolution,
            view = view,
            parameter = input$map_parameter,
            start = dr_start,
            end = dr_end,
            hours_ago = if (!is.null(input$time_slider)) input$time_slider else 0,
            time_label = if (!is.null(input$time_slider)) {
                target_time <- get_target_time(input$time_slider)
                format(target_time, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
            } else {
                format(get_target_time(0), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
            }
        ))

        # Update the URL in the address bar (for standalone usage)
        hours_val <- if (!is.null(input$time_slider)) input$time_slider else 0
        query_parts <- c()
        if (!is.null(station_name)) query_parts <- c(query_parts, paste0("station=", URLencode(station_name)))
        if (!is.null(s_country)) query_parts <- c(query_parts, paste0("country=", URLencode(s_country)))
        query_parts <- c(
            query_parts,
            paste0("resolution=", URLencode(resolution)),
            paste0("view=", URLencode(view)),
            paste0("parameter=", URLencode(if (is.null(input$map_parameter)) "air_temperature" else input$map_parameter))
        )
        query_string <- paste0("?", paste(query_parts, collapse = "&"))
        updateQueryString(query_string, mode = "push")
    }

    # Observer: Apply URL params on app startup
    observe({
        req(!url_initialized())

        query <- session$clientData$url_search
        params <- parse_url_params(query)

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

        # Apply resolution
        if (!is.null(params$resolution) && params$resolution %in% c("Hourly", "Daily", "6-min", "Monthly")) {
            current_resolution(params$resolution)
        }

        # Apply parameter
        if (!is.null(params$parameter)) {
            updateSelectInput(session, "map_parameter", selected = params$parameter)
        }

        # Apply hours_ago
        if (!is.null(params$hours_ago)) {
            val <- as.numeric(params$hours_ago)
            if (!is.na(val) && val >= 0 && val <= 23) {
                updateSliderInput(session, "time_slider", value = val)
            }
        }

        # Apply date range with clamping
        # Constraints: min=2026-03-05, max=today, max 31-day span
        if (!is.null(params$start) || !is.null(params$end)) {
            min_date <- as.Date("2026-03-05")
            max_date <- Sys.Date()
            max_span <- 31L

            # Parse and clamp start
            start_val <- if (!is.null(params$start)) {
                d <- tryCatch(as.Date(params$start), error = function(e) NULL)
                if (!is.null(d) && !is.na(d)) max(min(d, max_date), min_date) else NULL
            } else NULL

            # Parse and clamp end
            end_val <- if (!is.null(params$end)) {
                d <- tryCatch(as.Date(params$end), error = function(e) NULL)
                if (!is.null(d) && !is.na(d)) max(min(d, max_date), min_date) else NULL
            } else NULL

            # Ensure start <= end, and enforce max 90-day range
            if (!is.null(start_val) && !is.null(end_val)) {
                if (start_val > end_val) {
                    # Swap
                    tmp <- start_val; start_val <- end_val; end_val <- tmp
                }
                if (as.integer(end_val - start_val) > max_span) {
                    start_val <- end_val - max_span
                    start_val <- max(start_val, min_date)
                }
            } else if (!is.null(start_val) && is.null(end_val)) {
                end_val <- min(start_val + max_span, max_date)
            } else if (is.null(start_val) && !is.null(end_val)) {
                start_val <- max(end_val - max_span, min_date)
            }

            if (!is.null(start_val) && !is.null(end_val)) {
                updateDateRangeInput(session, "date_range",
                    start = start_val, end = end_val)
            }
        }

        # Apply country filter from URL — defer until station data is ready
        if (!is.null(params$country)) {
            selected_country <- trimws(strsplit(params$country, ",")[[1]][1])
            pending_url_country(selected_country)
        }

        # Apply station selection — defer until station data is available
        if (!is.null(params$station)) {
            pending_url_station(params$station)
        }

        # Apply view/tab navigation
        if (!is.null(params$view)) {
            view <- params$view
            if (view == "map") {
                nav_select("main_nav", "Map View")
            } else if (view == "station-info") {
                nav_select("main_nav", "Stations Info")
                # Dismiss startup overlay — map loading is not needed for this view
                bootstrap_active(FALSE)
                initial_map_bootstrap(FALSE)
                session$sendCustomMessage("unfreezeUI", list(force = TRUE))
            } else if (view %in% c("dashboard-plots", "dashboard-data")) {
                # DON'T switch to Dashboard immediately — station_data() is still
                # NULL, so the placeholder would show.  The station fetch handler
                # will navigate to Dashboard after data loads.  Just dismiss the
                # startup "Loading base map..." overlay so the user sees the fetch
                # progress overlay instead.
                bootstrap_active(FALSE)
                initial_map_bootstrap(FALSE)
                # Store target subtab so we can switch to it after data loads
                if (view == "dashboard-data") {
                    session$userData$pending_dashboard_subtab <- "Data"
                }
            }
        }

        url_initialized(TRUE)
    })

    # Observer: Broadcast State Changes
    observe({
        input$station_selector
        input$main_nav
        input$dashboard_subtabs
        current_station_id()
        input$map_parameter
        input$time_slider
        input$country_selector
        input$date_range

        # Debounce slightly to avoid rapid-fire updates?
        # Or just rely on reactive flush.
        # Check initialization
        req(url_initialized())

        # Broadcast
        broadcast_state()
    })

    # Observer: Handle in-app navigation from parent page (postMessage)
    # When a user clicks an internal EuroMeteo link, the parent page
    # intercepts the click (preserving real href for SEO) and sends a
    # postMessage → app.js → Shiny.setInputValue('parent_navigate', ...).
    # This observer applies the navigation WITHOUT reloading the iframe.
    observeEvent(input$parent_navigate, {
        msg <- input$parent_navigate
        req(msg)

        param_shiny <- msg$parameterShiny
        country_slug <- msg$countrySlug
        station_slug <- msg$stationSlug
        station_id <- msg$stationId

        message(sprintf("[parent_navigate] param=%s country=%s station=%s id=%s",
            ifelse(is.null(param_shiny), "NULL", param_shiny),
            ifelse(is.null(country_slug), "NULL", country_slug),
            ifelse(is.null(station_slug), "NULL", station_slug),
            ifelse(is.null(station_id), "NULL", station_id)))

        # 1) Apply parameter change if different from current
        if (!is.null(param_shiny) && !identical(param_shiny, input$map_parameter)) {
            updateSelectInput(session, "map_parameter", selected = param_shiny)
        }

        # 2) Resolve country slug → country name using station metadata
        st <- all_stations()
        country_name <- NULL
        if (!is.null(country_slug) && !is.null(st)) {
            countries <- unique(st$country)
            for (cname in countries) {
                if (eurometeo_slugify(cname) == country_slug) {
                    country_name <- cname
                    break
                }
            }
        }

        # 3) Route based on what was clicked
        if (!is.null(station_id) || !is.null(station_slug)) {
            # ── Station-level navigation ──
            target_id <- station_id
            if (is.null(target_id) && !is.null(station_slug) && !is.null(st)) {
                target_id <- resolve_station_ref(st, station_slug)
            }

            if (!is.null(target_id)) {
                # Check if country needs to change
                current_country <- input$country_selector
                country_needs_change <- !is.null(country_name) &&
                    (is.null(current_country) ||
                     length(current_country) == 0 ||
                     !identical(as.character(current_country), country_name))

                if (country_needs_change) {
                    # Country must change first → use pending pattern.
                    # The country change triggers filtered_stations() to recompute,
                    # which triggers the station choice observer that consumes
                    # pending_url_station and selects the station.
                    pending_url_country(country_name)
                    pending_url_station(target_id)
                    updateSelectizeInput(session, "country_selector",
                        selected = country_name)
                } else {
                    # Country is already correct (or no country specified).
                    # Directly set the station selector — this triggers the
                    # station_selector observer → current_station_id → fetch → Dashboard.
                    # No need for pending_url_station since filtered_stations()
                    # won't change (and the station choice observer wouldn't re-run).
                    updateSelectizeInput(session, "station_selector",
                        selected = target_id)
                }
            } else {
                # Station not found — fall back to country-level navigation
                if (!is.null(country_name)) {
                    current_station_id(NULL)
                    station_data(NULL)
                    updateSelectizeInput(session, "station_selector",
                        selected = character(0))
                    updateSelectizeInput(session, "country_selector",
                        selected = country_name)
                    nav_select("main_nav", "Map View")
                }
            }
        } else if (!is.null(country_name)) {
            # ── Country-only navigation — clear station, zoom to country ──
            current_station_id(NULL)
            station_data(NULL)
            updateSelectizeInput(session, "station_selector",
                selected = character(0))
            updateSelectizeInput(session, "country_selector",
                selected = country_name)
            nav_select("main_nav", "Map View")
        } else {
            # ── Parameter-only navigation — clear everything, zoom to Europe ──
            current_station_id(NULL)
            station_data(NULL)
            updateSelectizeInput(session, "station_selector",
                selected = character(0))
            updateSelectizeInput(session, "country_selector",
                selected = "All Countries")
            nav_select("main_nav", "Map View")
        }

        # Broadcast updated state back to parent (refines title/context)
        broadcast_state()
    }, ignoreInit = TRUE)

    # Default Date Range Init - REMOVED

    current_index <- reactive({
        NULL
    })

    # Raw station coordinates (available before full post-processing)
    # Used to compute bounding boxes for observation fetches immediately.
    raw_station_coords <- reactiveVal(NULL)

    # Fully augmented station data (after OSCAR, country reconciliation, resolution_info)
    all_stations_val <- reactiveVal(NULL)
    all_stations <- reactive({ all_stations_val() })

    station_poll_interval_ms <- 180 * 60 * 1000
    station_load_generation <- reactiveVal(0)

    # Two-phase station loading:
    #   Phase 1 (this observer): Fetch raw coords -> publish immediately -> viewport observer fires
    #   Phase 2 (later callback): Full post-processing -> all_stations_val updated
    observe({
        # Periodic re-check
        invalidateLater(station_poll_interval_ms)
        gen <- isolate(station_load_generation()) + 1
        station_load_generation(gen)

        t0 <- proc.time()[["elapsed"]]

        # Phase 1: Raw coords (fast — cache hit or API call)
        raw <- get_meteogate_stations_raw()
        raw_station_coords(raw)
        message(sprintf("[perf] raw_station_coords published in %.2fs", proc.time()[["elapsed"]] - t0))

        # Phase 2: Full post-processing — scheduled after reactive flush so the
        # viewport observer can fire with the raw coords in between.
        current_session <- shiny::getDefaultReactiveDomain()
        later::later(function() {
            shiny::withReactiveDomain(current_session, {
                # Guard against stale callbacks
                if (isolate(station_load_generation()) != gen) return()

                result <- get_meteogate_stations()
                message(sprintf("[perf] all_stations ready in %.2fs", proc.time()[["elapsed"]] - t0))
                all_stations_val(result)
            })
        }, delay = 0.01)
    })

    # --- Freeze UI During Data Loading ---
    # Disable all interactive controls (except map hovering) while parsing data
    observe({
        is_loading <- loading_status()

        # List of input IDs to disable/enable
        inputs_to_toggle <- c(
            "station_selector",
            "country_selector",
            "date_range",
            "zoom_home",
            "main_nav",
            "download_hourly"
        )

        if (is_loading) {
            for (inp in inputs_to_toggle) {
                shinyjs::disable(inp)
            }
        } else {
            for (inp in inputs_to_toggle) {
                shinyjs::enable(inp)
            }
        }
    })

    # Initialize / Update Country Selector Choices based on Data Availability
    observe({
        st <- all_stations()
        req(st)

        # Get Current Observation Data to filter countries
        obs <- viewport_obs_data()

        # Calculate available countries
        # If we have data, filter strictly to countries present in the data
        # If data is NULL (loading/error), fall back to all countries to avoid empty list during transitions
        country_list <- if (!is.null(obs) && nrow(obs) > 0) {
            # Filter stations that have data
            ids_with_data <- unique(obs$station_id)
            visible_stations <- st %>% filter(id %in% ids_with_data)
            sort(unique(visible_stations$country))
        } else {
            # Fallback
            sort(unique(st$country))
        }

        # Add 'All Countries' as the first option
        countries <- c("All Countries", country_list)

        # Update input (preserve selection if possible)
        # Use isolate() to avoid reactive dependency on the selector itself (prevents blink loop)
        pending <- isolate(pending_url_country())
        current_sel <- isolate(input$country_selector)

        if (!is.null(pending)) {
            countries <- unique(c(countries, pending))
            selected <- pending
        } else {
            selected <- current_sel
        }

        updateSelectizeInput(session, "country_selector", choices = countries, selected = selected, server = TRUE)
    })

    # ── Zoom helper (reused by sidebar selection and URL deep link) ──
    zoom_to_country <- function(country_name, animate = TRUE) {
        df <- all_stations()
        req(df, map_initialized())

        if (!is.null(country_name) && length(country_name) > 0 && !("All Countries" %in% country_name)) {
            df_subset <- df %>% filter(country %in% country_name)

            if (nrow(df_subset) > 0) {
                lons <- range(df_subset$longitude, na.rm = TRUE)
                lats <- range(df_subset$latitude, na.rm = TRUE)

                if (nrow(df_subset) == 1) {
                    if (animate) {
                        maplibre_proxy("map") %>%
                            fly_to(center = c(df_subset$longitude[1], df_subset$latitude[1]), zoom = 12)
                    } else {
                        maplibre_proxy("map") %>%
                            fit_bounds(c(df_subset$longitude[1] - 0.1, df_subset$latitude[1] - 0.1,
                                         df_subset$longitude[1] + 0.1, df_subset$latitude[1] + 0.1),
                                       animate = FALSE)
                    }
                } else {
                    maplibre_proxy("map") %>%
                        fit_bounds(c(lons[1], lats[1], lons[2], lats[2]), animate = animate)
                }
            }
        } else {
            # All Countries -> Zoom to Default Bounds
            maplibre_proxy("map") %>%
                fit_bounds(
                    c(map_bounds$lng_min, map_bounds$lat_min, map_bounds$lng_max, map_bounds$lat_max),
                    animate = animate
                )
        }
    }

    # Helper: resolve a station reference (ID, name, or slug) to a station ID
    resolve_station_ref <- function(stations, station_ref) {
        if (is.null(stations) || nrow(stations) == 0 || is.null(station_ref)) return(NULL)
        station_ref <- trimws(as.character(station_ref))

        # Try exact match on ID or name first
        match <- stations %>% filter(as.character(id) == station_ref | as.character(name) == station_ref)

        # Fallback: match by slugified name (URL passes slugs like "ranua-airfield")
        if (nrow(match) == 0 && exists("eurometeo_slugify")) {
            match <- stations %>%
                filter(eurometeo_slugify(as.character(name)) == station_ref)
        }

        if (nrow(match) == 0) return(NULL)
        match$id[1]
    }

    # NOTE: Station deep-link is applied through the station choice observer
    # (DWD pattern) — see the "Initialize / Update Station Selector Choices"
    # observer below.  This avoids the race where setting current_station_id()
    # before updateSelectizeInput caused the station_selector observer to skip
    # via the prev_id guard, which prevented highlight_selected_station() from
    # being called.

    # Dedicated observer for URL country deep-link zoom (waits for map/stations)
    observe({
        country <- pending_url_country()
        req(country)

        # If a station deep-link is also pending, let it take priority
        if (!is.null(pending_url_station())) {
            return()
        }

        req(all_stations())
        req(map_initialized())
        req(input$map_rendered)
        req(identical(input$country_selector, country))

        current_station_id(NULL)
        updateSelectizeInput(session, "station_selector", selected = character(0))

        zoom_to_country(country, animate = FALSE)

        pending_url_country(NULL)
        # Now that the country zoom is applied, dismiss the overlay
        unfreeze_ui_if_idle()
    })

    # Auto-Zoom on Country Selection (sidebar interaction — animated)
    observeEvent(input$country_selector, {
        req(map_initialized())

        # Skip if a station deep-link is pending — the station takes priority
        if (!is.null(pending_url_station())) {
            return()
        }

        pending <- pending_url_country()
        if (!is.null(pending)) {
            return() # URL deep-link observer will handle this
        }

        # If a specific country is selected (not "All Countries"), clear the
        # active station and switch to Map View so the user sees the zoom.
        if (!is.null(input$country_selector) &&
            length(input$country_selector) > 0 &&
            !("All Countries" %in% input$country_selector)) {
            current_station_id(NULL)
            station_data(NULL)
            updateSelectizeInput(session, "station_selector", selected = character(0))

            # If not already on Map View, switch first and defer the zoom so the
            # map container is visible before MapLibre tries to fit bounds.
            if (!identical(input$main_nav, "Map View")) {
                nav_select("main_nav", "Map View")
                country_to_zoom <- input$country_selector
                shinyjs::delay(300, {
                    zoom_to_country(country_to_zoom, animate = TRUE)
                })
            } else {
                zoom_to_country(input$country_selector, animate = TRUE)
            }
        } else {
            # "All Countries" selected — clear any active station
            current_station_id(NULL)
            station_data(NULL)
            updateSelectizeInput(session, "station_selector", selected = character(0))

            # Switch to Map View if currently on Dashboard/Stations Info
            if (!identical(input$main_nav, "Map View")) {
                nav_select("main_nav", "Map View")
                shinyjs::delay(300, {
                    zoom_to_country("All Countries", animate = TRUE)
                })
            } else {
                zoom_to_country(input$country_selector, animate = TRUE)
            }
        }
    }, ignoreInit = TRUE)


    filtered_stations <- reactive({
        req(all_stations(), current_resolution())

        df <- as.data.frame(all_stations())

        # Filter by country (matches DWD's state filter pattern)
        if (!is.null(input$country_selector) &&
            length(input$country_selector) > 0 &&
            !("All Countries" %in% input$country_selector)) {
            df <- df %>% filter(country %in% input$country_selector)
        }

        df
    })

    filtered_stations_sf <- reactive({
        df <- filtered_stations()
        req(df)

        df <- df %>% filter(!is.na(latitude) & !is.na(longitude))
        if (nrow(df) == 0) {
            return(sf::st_as_sf(df, coords = c("longitude", "latitude"), crs = 4326, remove = FALSE))
        }

        sf::st_as_sf(df, coords = c("longitude", "latitude"), crs = 4326, remove = FALSE)
    })

    # Render Time Slider dynamically (Numeric 0-23, anchored to selected end date)
    output$time_slider_ui <- renderUI({
        req(input$date_range)

        tagList(
            sliderInput(
                "time_slider",
                label = NULL,
                min = 0,
                max = 23,
                value = 3,
                step = 1,
                ticks = TRUE,
                width = "100%"
            ),
            tags$script(HTML("
                setTimeout(function() {
                    var el = $('#time_slider');
                    if (el.length && el.data('ionRangeSlider')) {
                        el.data('ionRangeSlider').update({
                            prettify: function(n) { return n === 0 ? '0' : '-' + n; }
                        });
                    }
                }, 100);
            "))
        )
    })

    # Initialize / Update Station Selector Choices
    # DWD pattern: station deep-link is applied HERE through the choice update,
    # which triggers input$station_selector → station_selector observer →
    # current_station_id() + highlight_selected_station().
    observe({
        df <- filtered_stations()
        req(df)

        # Create choices: "Station Name (ID)" = "ID"
        # Defensive: Ensure atomic vectors
        ids <- as.character(df$id)
        names <- paste0(as.character(df$name), " (", ids, ")")

        if (length(ids) > 0) {
            new_choices <- setNames(ids, names)
        } else {
            new_choices <- character(0)
        }

        # Only update if choices have actually changed (compare IDs)
        prev_choices <- previous_station_choices()
        new_ids <- sort(unname(new_choices))
        prev_ids <- if (!is.null(prev_choices)) sort(unname(prev_choices)) else NULL

        existing_sel <- isolate(input$station_selector)
        current_sel <- existing_sel

        # If current_station_id() has been explicitly cleared (e.g., user
        # selected "All Countries"), do NOT preserve the stale input value.
        # The updateSelectizeInput(selected = character(0)) may not have
        # reached the client yet, so input$station_selector still holds
        # the old station ID. Respect the server-side clearing.
        if (is.null(isolate(current_station_id())) && is.null(isolate(pending_url_station()))) {
            current_sel <- character(0)
        }

        # Apply station from URL deep-link (DWD pattern).
        # Only apply once the target station appears in the filtered choices,
        # meaning the country filter has settled first.
        url_station <- isolate(pending_url_station())
        if (!is.null(url_station)) {
            target_id <- resolve_station_ref(isolate(all_stations()), url_station)
            if (!is.null(target_id) && target_id %in% ids) {
                if (!identical(existing_sel, target_id)) {
                    current_sel <- target_id
                }
                # NOTE: Do NOT clear pending_url_station here.
                # It is cleared in the station_selector observer after
                # the station is confirmed selected. This keeps the
                # country_selector guard active until the full chain completes.
            }
        }

        if (is.null(prev_ids) || !identical(new_ids, prev_ids) || !identical(current_sel, existing_sel)) {
            updateSelectizeInput(session, "station_selector",
                choices = new_choices,
                selected = current_sel,
                server = TRUE
            )
            previous_station_choices(new_choices)
        }
    })

    # --- Selection Logic via Dropdown ---
    observeEvent(input$station_selector, {
        req(input$station_selector)
        id_val <- input$station_selector

        # Find station details
        # Check filtered_stations first to get resolution_info
        s_meta <- filtered_stations() %>% filter(id == id_val)

        if (nrow(s_meta) == 0) {
            # Fallback to all_stations if not in current filter
            s_meta <- all_stations() %>% filter(id == id_val)
            # Add dummy resolution_info if missing
            if (!("resolution_info" %in% names(s_meta))) {
                s_meta$resolution_info <- "Data status unavailable for current filter"
            }
        }
        req(nrow(s_meta) > 0)

        lat_val <- s_meta$latitude[1]
        lng_val <- s_meta$longitude[1]

        # Set ID
        # Optimization: If ID is same as current, do not re-trigger date resets or map moves
        # This prevents circular loops where Date Filter -> Filtered List -> Update Selector -> Trigger Observer -> Reset Date
        prev_id <- current_station_id()
        if (!is.null(prev_id) && prev_id == id_val) {
            return()
        }

        current_station_id(id_val)

        # Clear URL deep-link state once the station is confirmed selected
        # (completing the DWD-style chain: URL → country → choices → selector)
        if (!is.null(isolate(pending_url_station()))) {
            target_id <- resolve_station_ref(isolate(all_stations()), isolate(pending_url_station()))
            if (!is.null(target_id) && identical(id_val, target_id)) {
                pending_url_station(NULL)
                pending_url_country(NULL)
            }
        }

        # Try to get temperature from view session
        obs <- viewport_obs_data()
        match <- if (!is.null(obs)) obs %>% filter(station_id == id_val) else NULL
        current_temp <- if (!is.null(match) && nrow(match) > 0) match$temp[1] else NULL
        current_param_name <- if (!is.null(match) && nrow(match) > 0 && "param_name" %in% names(match)) {
            match$param_name[1]
        } else {
            NA_character_
        }

        # Generate label for highlight
        current_param <- isolate(input$map_parameter)
        if (is.null(current_param)) current_param <- "air_temperature"
        param_label <- if (current_param == "precipitation_amount") "Precipitation" else "Air Temperature"
        param_unit <- if (current_param == "precipitation_amount") "mm" else "°C"
        missing_label <- if (current_param == "precipitation_amount") "No precip available at this hour" else NULL

        res_info <- if ("resolution_info" %in% names(s_meta)) s_meta$resolution_info[1] else "Data status unavailable"
        if (is.null(res_info) || is.na(res_info)) res_info <- "Data status unavailable for current filter"

        label_name <- if (current_param == "precipitation_amount") {
            format_precip_label(current_param_name, param_label)
        } else {
            param_label
        }

        lbl <- generate_station_label(
            s_meta$name[1], s_meta$id[1], s_meta$country[1],
            s_meta$start_date[1], s_meta$end_date[1], s_meta$detailed_summary[1],
            res_info,
            val = current_temp,
            label_name = label_name,
            unit = param_unit,
            missing_label = missing_label
        )

        # Highlight & Zoom using helper
        highlight_selected_station(maplibre_proxy("map"), lng_val, lat_val, lbl)

        # NOTE: Date reset removed to preserve user context
    })

    start_map_fetch <- function(message) {
        if (isTRUE(isolate(loading_status()))) {
            return(NULL)
        }

        token <- isolate(map_fetch_token()) + 1
        map_fetch_token(token)
        map_fetch_active(TRUE)
        map_render_pending(TRUE)
        map_render_token(token)

        # Keep the very first map-data fetch non-blocking so the basemap can appear
        # as soon as MapLibre has rendered it. Later map fetches still use the overlay.
        if (!isTRUE(isolate(initial_map_bootstrap()))) {
            session$sendCustomMessage("freezeUI", list(text = message, allowCancel = FALSE))
        }

        token
    }

    end_map_fetch <- function(token) {
        if (is.null(token)) {
            return()
        }

        if (isolate(map_fetch_token()) != token) {
            return()
        }

        map_fetch_active(FALSE)
        if (!isTRUE(isolate(bootstrap_active())) && !isTRUE(isolate(loading_status())) && !isTRUE(isolate(map_render_pending())) && !isTRUE(isolate(fetch_pending())) && is.null(isolate(pending_url_country()))) {
            session$sendCustomMessage("unfreezeUI", list())
        }
    }

    unfreeze_ui_if_idle <- function() {
        if (!isTRUE(isolate(bootstrap_active())) && !isTRUE(isolate(loading_status())) && !isTRUE(isolate(map_fetch_active())) && !isTRUE(isolate(map_render_pending())) && !isTRUE(isolate(plot_render_pending())) && !isTRUE(isolate(fetch_pending())) && is.null(isolate(pending_url_country()))) {
            session$sendCustomMessage("unfreezeUI", list())
        }
    }

    observeEvent(input$map_rendered,
        {
            req(input$map_rendered)
            token <- suppressWarnings(as.numeric(input$map_rendered$token))
            current_token <- isolate(map_render_token())
            if (is.na(token) || is.null(current_token) || token != current_token) {
                return()
            }

            map_render_pending(FALSE)
            if (isTRUE(isolate(initial_map_bootstrap()))) {
                initial_map_bootstrap(FALSE)
            }

            # Clear bootstrap_active as soon as the base map has finished rendering!
            # This allows the base map to be visible immediately, while station observations load in the background.
            if (isTRUE(isolate(bootstrap_active()))) {
                bootstrap_active(FALSE)
            }

            # Safety net: hide inline loading indicator if still visible
            session$sendCustomMessage("hideMapLoading", list())

            if (!isTRUE(isolate(bootstrap_active())) && !isTRUE(isolate(loading_status())) && !isTRUE(isolate(map_fetch_active())) && !isTRUE(isolate(fetch_pending())) && is.null(isolate(pending_url_country()))) {
                session$sendCustomMessage("unfreezeUI", list())
            }
        },
        ignoreInit = TRUE
    )

    # Observer: Dismiss startup overlay as soon as basemap tiles render.
    # This decouples the overlay from the station data fetch, so users see
    # the interactive basemap immediately while stations load in the background.
    observeEvent(input$basemap_loaded, {
        if (!isTRUE(isolate(bootstrap_active()))) return()

        bootstrap_active(FALSE)
        initial_map_bootstrap(FALSE)

        # Dismiss the full-screen overlay immediately
        session$sendCustomMessage("unfreezeUI", list(force = TRUE))

        # Show lightweight inline indicator on the map
        session$sendCustomMessage("showMapLoading", list(text = "Loading stations..."))
    }, ignoreInit = TRUE, once = TRUE)

    # Viewport temperature data (shared by map + sidebar)
    viewport_obs_data <- reactiveVal(NULL)

    # Decoupled observer: uses raw_station_coords for bounds computation
    # so the observation fetch fires as soon as coordinates are available,
    # before the full post-processing pipeline (OSCAR, country reconciliation,
    # resolution augmentation) completes.
    observe({
        # Use raw coords for bounds — available before all_stations() finishes
        raw_df <- raw_station_coords()
        req(raw_df, current_resolution(), input$map_parameter, !is.null(input$time_slider))

        hours_ago <- input$time_slider

        # Calculate target_time using helper
        target_time <- get_target_time(hours_ago)

        # input$map_parameter already returns the value like "air_temperature" or "precipitation_amount"
        param_slug <- input$map_parameter
        selected_param_ui <- case_when(
            param_slug == "air_temperature" ~ "Air Temperature",
            param_slug == "precipitation_amount" ~ "Precipitation",
            param_slug == "air_pressure_at_mean_sea_level" ~ "Sea Level Pressure",
            param_slug == "wind_speed" ~ "Wind Speed",
            TRUE ~ "Data"
        )

        # Calculate bounds from raw station coordinates (includes overseas territories
        # like Greenland, Réunion, French Guiana, Azores, Canary Islands, etc.)
        # The tiled parallel fetch in fetch_temperature_for_area() handles the
        # large bbox by splitting into tiles and pruning empty-ocean tiles.
        if (nrow(raw_df) > 0) {
            lats <- range(raw_df$latitude, na.rm = TRUE)
            lons <- range(raw_df$longitude, na.rm = TRUE)

            # Add small buffer
            bounds <- list(
                lat_min = lats[1] - 0.1,
                lat_max = lats[2] + 0.1,
                lng_min = lons[1] - 0.1,
                lng_max = lons[2] + 0.1
            )
        } else {
            if (!isTRUE(map_initialized())) {
                viewport_obs_data(NULL)
                return()
            }
            bounds <- map_bounds
        }

        # Use filtered_stations for the station list if available, otherwise raw
        df <- isolate(tryCatch(filtered_stations(), error = function(e) raw_df))

        time_label <- format(target_time, "%Y-%m-%d %H:%M UTC")
        map_fetch_message <- paste0("Fetching map ", selected_param_ui, " (", time_label, ")...")
        fetch_token <- start_map_fetch(map_fetch_message)
        if (is.null(fetch_token)) {
            return()
        }

        current_session <- shiny::getDefaultReactiveDomain()
        later::later(function() {
            shiny::withReactiveDomain(current_session, {
                if (isolate(map_fetch_token()) != fetch_token) {
                    return()
                }

                result <- tryCatch(
                    get_observations_for_viewport(
                        zoom = 10, # Force high zoom logic (no decimation)
                        bounds = bounds,
                        target_time = target_time,
                        stations = df,
                        param_name = param_slug
                    ),
                    error = function(e) NULL
                )

                if (isolate(map_fetch_token()) != fetch_token) {
                    return()
                }

                viewport_obs_data(result)
                end_map_fetch(fetch_token)
            })
        }, delay = 0.05)
    })

    # Station Count
    output$station_count_filtered <- renderText({
        n <- nrow(filtered_stations())
        paste(n, "stations found")
    })

    # Temperature data info
    output$temp_data_info <- renderUI({
        hours_ago <- if (!is.null(input$time_slider)) input$time_slider else return(NULL)
        obs_data <- viewport_obs_data()

        if (is.null(obs_data) || nrow(obs_data) == 0) {
            return(tags$small(style = "color: #888;", "No temperature data available in view"))
        }

        # Get the average observation time for this hour
        avg_time <- mean(obs_data$datetime, na.rm = TRUE)
        time_str <- format(avg_time, "%Y-%m-%d %H:%M UTC")

        div(
            style = "font-size: 0.85em; color: #555; margin-top: 5px;",
            tags$span(
                style = "display: flex; align-items: center; gap: 5px;",
                bsicons::bs_icon("thermometer-half", size = "1em"),
                paste0("Showing: ", nrow(obs_data), " stations")
            ),
            div(style = "margin-left: 20px; font-weight: 500;", time_str),
            div(
                style = "margin-left: 20px;",
                tags$small(
                    style = "color: #888;",
                    if (hours_ago == 0) "Current observations" else paste0(hours_ago, " hour(s) ago")
                )
            ),
            div(
                style = "margin-top: 8px; display: flex; align-items: flex-start; gap: 6px; color: #0056b3;",
                bsicons::bs_icon("info-circle"),
                tags$span("Tip: Click map points to view detailed weather plots.")
            )
        )
    })

    # Time slider label
    output$selected_time_label <- renderText({
        hours_ago <- if (!is.null(input$time_slider)) input$time_slider else return("")
        target_time <- get_target_time(hours_ago)
        format(target_time, "%Y-%m-%d %H:00 UTC", tz = "UTC")
    })

    # --- Map ---
    output$map <- renderMaplibre({
        maplibre(
            style = "https://tiles.openfreemap.org/styles/positron",
            center = c(10, 50),
            zoom = 4
        ) %>%
            add_navigation_control(show_compass = FALSE, visualize_pitch = FALSE, position = "top-left")
    })

    # Initialize map bounds only once
    observe({
        req(!map_initialized())
        req(input$map_zoom)

        if (is.null(pending_url_country())) {
            maplibre_proxy("map") %>%
                fit_bounds(
                    c(map_bounds$lng_min, map_bounds$lat_min, map_bounds$lng_max, map_bounds$lat_max)
                )
        }

        map_initialized(TRUE)
    })

    # Zoom to extent of all filtered stations
    observeEvent(input$zoom_home, {
        df <- filtered_stations()
        req(df)
        if (nrow(df) > 0) {
            # Calculate bounds
            lons <- range(df$longitude, na.rm = TRUE)
            lats <- range(df$latitude, na.rm = TRUE)

            # Calculate geographic extent
            lon_span <- lons[2] - lons[1]
            lat_span <- lats[2] - lats[1]

            # If only one station, zoom to it with a small buffer
            if (nrow(df) == 1) {
                maplibre_proxy("map") %>%
                    fly_to(center = c(df$longitude[1], df$latitude[1]), zoom = 12)
            } else if (lon_span > 60 || lat_span > 40) {
                # Stations are globally distributed (former colonies) - use world view
                # Center on France but zoom out to see the whole world
                maplibre_proxy("map") %>%
                    fly_to(center = c(2.2137, 20), zoom = 2)
            } else {
                maplibre_proxy("map") %>%
                    fit_bounds(c(lons[1], lats[1], lons[2], lats[2]), animate = TRUE)
            }
        }
    })

    # Fix Map Rendering on Tab Switch + re-highlight selected station
    # When a station is selected and the user switches to Map View, JS applies
    # the highlight after resizing the map. This avoids R reactive timing issues.
    observeEvent(input$main_nav, {
        if (input$main_nav == "Map View") {
            shinyjs::runjs("
                (function() {
                    var mapEl = document.getElementById('map');
                    if (!mapEl || !mapEl.__mapgl) return;
                    var map = mapEl.__mapgl;
                    map.resize();

                    // Check for pending station highlight stored by R
                    var h = window.__pendingStationHighlight;
                    if (h) {
                        window.__pendingStationHighlight = null;
                        setTimeout(function() {
                            map.flyTo({ center: [h.lng, h.lat], zoom: 9 });

                            // Remove existing highlight layer/source
                            if (map.getLayer('selected-highlight')) map.removeLayer('selected-highlight');
                            if (map.getSource('selected-highlight')) map.removeSource('selected-highlight');

                            map.addSource('selected-highlight', {
                                type: 'geojson',
                                data: {
                                    type: 'Feature',
                                    geometry: { type: 'Point', coordinates: [h.lng, h.lat] },
                                    properties: { popup_content: h.label || '' }
                                }
                            });
                            map.addLayer({
                                id: 'selected-highlight',
                                type: 'circle',
                                source: 'selected-highlight',
                                paint: {
                                    'circle-color': 'red',
                                    'circle-radius': 12,
                                    'circle-stroke-color': 'red',
                                    'circle-stroke-width': 3,
                                    'circle-opacity': 0.4
                                }
                            });
                        }, 300);
                    }
                })();
            ")
        }
    }, ignoreInit = TRUE)

    # --- Basemap Switching ---
    observeEvent(
        basemap_debounced(),
        {
            basemap <- basemap_debounced()
            proxy <- maplibre_proxy("map")

            if (basemap %in% c("ofm_positron", "ofm_bright")) {
                # VECTOR LOGIC (OpenFreeMap styles)
                style_url <- switch(basemap,
                    "ofm_positron" = "https://tiles.openfreemap.org/styles/positron",
                    "ofm_bright" = "https://tiles.openfreemap.org/styles/bright"
                )

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

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

                current_session <- shiny::getDefaultReactiveDomain()
                selected_basemap <- basemap

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

                        # Trigger re-render of stations and apply label visibility
                        apply_label_visibility(maplibre_proxy("map"), isolate(input$show_labels))
                        style_change_trigger(isolate(style_change_trigger()) + 1)
                    })
                }, delay = 0.35)
            } 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 <- shiny::getDefaultReactiveDomain()
                selected_basemap <- basemap

                later::later(function() {
                    shiny::withReactiveDomain(current_session, {
                        current_basemap <- isolate(input$basemap)
                        if (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')
                        # Actually, we'll hide background and put it just above it if needed,
                        # but 'background' is typically the absolute first.
                        maplibre_proxy("map") %>%
                            add_raster_source(id = source_id, tiles = c(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"), isolate(input$show_labels))

                        # Stations should be above the satellite layer
                        # In Positron, waterway_line_label is the lowest symbol.
                        # Our stations are already set to render before waterway_line_label if the ID exists.
                        stations_before_id("waterway_line_label")
                        style_change_trigger(isolate(style_change_trigger()) + 1)
                    })
                }, delay = 0.5)
            }
        },
        ignoreInit = TRUE
    )

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

    observeEvent(current_resolution(),
        {
            station_data(NULL)
            parsed_data_list(list())

            # Only block UI if we have a station selected (fetch will occur)
            if (!is.null(current_station_id())) {
                loading_status(TRUE)
            }
        },
        priority = 1000,
        ignoreInit = TRUE
    )

    # Track the last viewport_obs_data identity to skip redundant repaints.
    # The observer is triggered by multiple reactive dependencies; without this
    # guard the stations are painted 3 times on startup.
    last_painted_obs_gen <- reactiveVal("")
    obs_data_gen <- reactiveVal(0L)
    observe({
        viewport_obs_data()
        obs_data_gen(isolate(obs_data_gen()) + 1L)
    })

    # Update Markers
    observe({
        df <- filtered_stations_sf()
        req(df, current_resolution())

        # Wait for map to be ready before adding markers
        req(map_initialized())

        # During URL hydration, wait until the selector state has caught up before
        # painting station markers. Otherwise the map briefly paints the previous
        # or all-country station set and then repaints the deep-linked country.
        pending_country <- isolate(pending_url_country())
        if (!is.null(pending_country)) {
            selected_country <- input$country_selector
            if (is.null(selected_country) ||
                length(selected_country) == 0 ||
                !identical(as.character(selected_country[1]), as.character(pending_country))) {
                return()
            }
        }

        # For station deep-links, wait until the normal station selector observer
        # has confirmed the selected station. This keeps the URL path aligned with
        # sidebar selection and avoids an intermediate country-only map repaint.
        # NOTE: isolate to avoid reactive dependency — this guard is checked
        # passively; the observer is re-triggered by filtered_stations_sf and
        # viewport_obs_data changes, not by pending_url_station itself.
        pending_station <- isolate(pending_url_station())
        if (!is.null(pending_station)) {
            target_id <- resolve_station_ref(isolate(all_stations()), pending_station)
            if (is.null(target_id) || !identical(isolate(current_station_id()), target_id)) {
                return()
            }
        }

        # Avoid painting with stale observation data while a fresh map fetch is
        # already in flight; the observer will rerun when the fetch completes.
        if (isTRUE(map_fetch_active())) {
            return()
        }

        # Skip redundant repaints: if viewport_obs_data hasn't changed since
        # the last successful paint, and filtered_stations hasn't changed, skip.
        current_obs_gen <- obs_data_gen()

        # Build a lightweight fingerprint: station IDs + obs data generation.
        # This prevents 2-3 repaints during startup where the same station set
        # is re-emitted because of country selector population cascades.
        station_ids_hash <- paste(sort(df$id), collapse = "|")
        paint_fingerprint <- paste0(station_ids_hash, "::", current_obs_gen)
        if (identical(paint_fingerprint, isolate(last_painted_obs_gen()))) {
            message("[station-paint] Skipped redundant repaint (same fingerprint)")
            return()
        }

        # Add dependency on style_change_trigger to re-add layer after style change
        style_change_trigger()

        # Get current parameter for labels/filters
        current_param <- isolate(input$map_parameter)
        if (is.null(current_param)) current_param <- "air_temperature"
        is_precip <- current_param == "precipitation_amount"
        is_pressure <- current_param == "air_pressure_at_mean_sea_level"
        is_wind <- current_param == "wind_speed"
        is_wind <- current_param == "wind_speed"

        param_label <- case_when(
            is_precip ~ "Precipitation",
            is_pressure ~ "Sea Level Pressure",
            is_wind ~ "Wind Speed",
            TRUE ~ "Air Temperature"
        )
        param_unit <- case_when(
            is_precip ~ "mm",
            is_pressure ~ "hPa",
            is_wind ~ "m/s",
            TRUE ~ "°C"
        )
        missing_label <- case_when(
            is_precip ~ "No precip available at this hour",
            is_pressure ~ "No pressure available",
            is_wind ~ "No wind available",
            TRUE ~ NA_character_
        )

        # Fetch observations for the selected hour with zoom-based sampling
        obs_data <- viewport_obs_data()

        if (!is.null(obs_data) && nrow(obs_data) > 0) {
            # Merge temperature data with stations
            df <- df %>%
                left_join(obs_data, by = c("id" = "station_id"))
            if (!"param_name" %in% names(df)) {
                df$param_name <- NA_character_
            }
        } else {
            df$temp <- NA_real_
            df$param_name <- NA_character_
            if (!is_precip) {
                # If no observations available for temperature, show nothing
                maplibre_proxy("map") %>% clear_layer("stations")
                initial_stations_queued(TRUE)
                queue_map_render()
                return()
            }
        }

        if (!is_precip) {
            # Filter to only stations with temperature data
            df <- df %>% filter(!is.na(temp))
        }

        if (nrow(df) == 0) {
            maplibre_proxy("map") %>% clear_layer("stations")
            initial_stations_queued(TRUE)
            queue_map_render()
            return()
        }

        if (is_precip) {
            df <- df %>% mutate(label_name = format_precip_label(param_name, param_label))
        } else {
            df$label_name <- param_label
        }

        use_detailed_tooltips <- isTRUE(input$detailed_tooltips)
        if (use_detailed_tooltips) {
            # Full hover cards (slower)
            df <- df %>% mutate(
                tooltip_content = purrr::pmap_chr(
                    list(name, id, country, start_date, end_date, detailed_summary, resolution_info, temp, label_name),
                    function(name, id, country, start_date, end_date, detailed_summary, resolution_info, val, label_name) {
                        generate_station_label(name, id, country, start_date, end_date, detailed_summary, resolution_info,
                            val = val, label_name = label_name, unit = param_unit, missing_label = missing_label
                        )
                    }
                )
            )
        } else {
            # Lightweight hover cards — minimal HTML, no heavy styling
            # This reduces the GeoJSON payload by ~70% compared to styled divs
            label_name_vec <- df$label_name
            value_text <- if (is_precip) {
                fallback_text <- if (!is.null(missing_label) && !is.na(missing_label)) missing_label else "No data"
                ifelse(!is.na(df$temp), paste0(round(df$temp, 1), " ", param_unit), fallback_text)
            } else {
                paste0(round(df$temp, 1), " ", param_unit)
            }

            df$tooltip_content <- paste0(
                "<b>", htmltools::htmlEscape(df$name), "</b>",
                " <span style='color:#666'>", htmltools::htmlEscape(df$country), "</span>",
                "<br>", htmltools::htmlEscape(label_name_vec), ": <b>", htmltools::htmlEscape(value_text), "</b>"
            )
        }

        if (nrow(df) > 0) {
            # Sort by value (higher values drawn on top)
            df <- df %>% arrange(!is.na(temp), temp)

            # Replace NA temps with sentinel for MapLibre expression
            df$temp[is.na(df$temp)] <- -999

            # Build MapLibre step expression for client-side coloring
            color_expr <- get_maplibre_color_expr(current_param, "temp")

            # Trim to only columns MapLibre needs (reduces serialization time)
            map_data <- df %>%
                select(id, name, country, temp, tooltip_content, geometry)

            before_layer_id <- isolate(stations_before_id())

            # Add thin border for precipitation to distinguish light dots from map
            stroke_width <- if (current_param == "precipitation_amount") 0.5 else 0

            maplibre_proxy("map") %>%
                clear_layer("stations") %>%
                add_circle_layer(
                    id = "stations",
                    source = map_data,
                    circle_color = color_expr,
                    circle_radius = 7,
                    circle_stroke_color = "#333333",
                    circle_stroke_width = stroke_width,
                    circle_opacity = 0.8,
                    tooltip = get_column("tooltip_content"),
                    before_id = before_layer_id
                )

            # Re-highlight selected station if present (to update label with new resolution)
            sid <- isolate(current_station_id())
            if (!is.null(sid)) {
                sel_row <- df %>% filter(id == sid)
                if (nrow(sel_row) > 0) {
                    # Restore NA for display
                    sel_temp <- if (sel_row$temp[1] <= -999) NA_real_ else sel_row$temp[1]
                    sel_label <- generate_station_label(
                        sel_row$name[1], sel_row$id[1], sel_row$country[1],
                        sel_row$start_date[1], sel_row$end_date[1], sel_row$detailed_summary[1],
                        sel_row$resolution_info[1],
                        val = sel_temp,
                        label_name = sel_row$label_name[1],
                        unit = param_unit,
                        missing_label = missing_label
                    )
                    highlight_selected_station(maplibre_proxy("map"), sel_row$longitude[1], sel_row$latitude[1], sel_label, move_map = FALSE)
                } else {
                    maplibre_proxy("map") %>% clear_layer("selected-highlight")
                }
            }

            initial_stations_queued(TRUE)
            queue_map_render()
            last_painted_obs_gen(paint_fingerprint)
            # Hide inline loading indicator (stations are now visible on the map)
            session$sendCustomMessage("hideMapLoading", list())
            message(sprintf("[station-paint] Painted %d stations (obs_gen=%d)", nrow(df), current_obs_gen))
        }
    })

    # Centralized Selection Highlight Observer
    # Ensures the red highlight circle and its hover label are always in sync with current data/filters
    observe({
        id_val <- current_station_id()
        if (is.null(id_val)) {
            maplibre_proxy("map") %>% clear_layer("selected-highlight")
            return()
        }

        # Get meta from filtered_stations if possible
        s_meta <- filtered_stations() %>% filter(id == id_val)
        if (nrow(s_meta) == 0) {
            s_meta <- all_stations() %>% filter(id == id_val)
        }

        # Skip if no meta found at all
        req(nrow(s_meta) > 0)

        # Try to get temperature from view session
        obs <- viewport_obs_data()
        match <- if (!is.null(obs)) obs %>% filter(station_id == id_val) else NULL
        current_temp <- if (!is.null(match) && nrow(match) > 0) match$temp[1] else NULL
        current_param_name <- if (!is.null(match) && nrow(match) > 0 && "param_name" %in% names(match)) {
            match$param_name[1]
        } else {
            NA_character_
        }

        # Generate Label
        current_param <- isolate(input$map_parameter)
        if (is.null(current_param)) current_param <- "air_temperature"
        is_precip <- current_param == "precipitation_amount"
        is_pressure <- current_param == "air_pressure_at_mean_sea_level"
        is_wind <- current_param == "wind_speed"
        is_wind <- current_param == "wind_speed"

        param_label <- case_when(
            is_precip ~ "Precipitation",
            is_pressure ~ "Sea Level Pressure",
            is_wind ~ "Wind Speed",
            TRUE ~ "Air Temperature"
        )
        param_unit <- case_when(
            is_precip ~ "mm",
            is_pressure ~ "hPa",
            is_wind ~ "m/s",
            TRUE ~ "°C"
        )
        missing_label <- case_when(
            is_precip ~ "No precip available at this hour",
            is_pressure ~ "No pressure available",
            is_wind ~ "No wind available",
            TRUE ~ NA_character_
        )

        res_info <- if ("resolution_info" %in% names(s_meta)) s_meta$resolution_info[1] else "Data status unavailable"
        if (is.null(res_info) || is.na(res_info)) res_info <- "Data status unavailable for current filter"

        label_name <- if (current_param == "precipitation_amount") {
            format_precip_label(current_param_name, param_label)
        } else {
            param_label
        }

        lbl <- generate_station_label(
            s_meta$name[1], s_meta$id[1], s_meta$country[1],
            s_meta$start_date[1], s_meta$end_date[1], s_meta$detailed_summary[1],
            res_info,
            val = current_temp,
            label_name = label_name,
            unit = param_unit,
            missing_label = missing_label
        )

        # Update Highlight Marker
        highlight_selected_station(maplibre_proxy("map"), s_meta$longitude[1], s_meta$latitude[1], lbl, move_map = FALSE)
    })


    # --- Selection Logic ---
    observeEvent(input$map_feature_click, {
        clicked_data <- input$map_feature_click
        # Check if the click was on the "stations" layer
        if (!is.null(clicked_data) && (isTRUE(clicked_data$layer_id == "stations") || isTRUE(clicked_data$layer == "stations"))) {
            id_val <- clicked_data$properties$id

            # Set ID
            current_station_id(id_val)

            # Highlight & Zoom explicitly (to ensure animation)
            s_meta <- filtered_stations() %>% filter(id == id_val)
            if (nrow(s_meta) == 0) {
                s_meta <- all_stations() %>% filter(id == id_val)
            }

            if (nrow(s_meta) > 0) {
                # Try to get temperature
                current_temp <- clicked_data$properties$temp
                current_param_name <- clicked_data$properties$param_name
                if (is.null(current_temp) || is.null(current_param_name) || is.na(current_param_name)) {
                    obs <- viewport_obs_data()
                    match <- if (!is.null(obs)) obs %>% filter(station_id == id_val) else NULL
                    if (is.null(current_temp) && !is.null(match) && nrow(match) > 0) {
                        current_temp <- match$temp[1]
                    }
                    if ((is.null(current_param_name) || is.na(current_param_name)) && !is.null(match) && nrow(match) > 0 && "param_name" %in% names(match)) {
                        current_param_name <- match$param_name[1]
                    }
                }
                if (is.null(current_param_name)) {
                    current_param_name <- NA_character_
                }

                res_info <- if ("resolution_info" %in% names(s_meta)) s_meta$resolution_info[1] else "Data status unavailable"
                if (is.null(res_info) || is.na(res_info)) res_info <- "Data status unavailable for current filter"

                current_param <- isolate(input$map_parameter)
                if (is.null(current_param)) current_param <- "air_temperature"
                param_label <- if (current_param == "precipitation_amount") "Precipitation" else "Air Temperature"
                param_unit <- if (current_param == "precipitation_amount") "mm" else "°C"
                missing_label <- if (current_param == "precipitation_amount") "No precip available at this hour" else NULL

                label_name <- if (current_param == "precipitation_amount") {
                    format_precip_label(current_param_name, param_label)
                } else {
                    param_label
                }

                lbl <- generate_station_label(
                    s_meta$name[1], s_meta$id[1], s_meta$country[1],
                    s_meta$start_date[1], s_meta$end_date[1], s_meta$detailed_summary[1],
                    res_info,
                    val = current_temp,
                    label_name = label_name,
                    unit = param_unit,
                    missing_label = missing_label
                )

                highlight_selected_station(maplibre_proxy("map"), s_meta$longitude[1], s_meta$latitude[1], lbl, move_map = TRUE)
            }

            # Force fetch
            fetch_trigger(fetch_trigger() + 1)

            # Sync dropdown
            updateSelectizeInput(session, "station_selector", selected = id_val)
        }
    })


    # --- Immediate State Clearing to Prevent Main Thread Blocking ---
    # When inputs change, clear data IMMEDIATELY to prevent plots from
    # rendering old data with new settings (e.g. Daily data -> Monthly plots)
    # This covers the 500ms debounce gap and prevents app freezing on HuggingFace free tier.
    observeEvent(current_resolution(),
        {
            station_data(NULL)
            parsed_data_list(list())

            # Only block UI if we have a station selected (fetch will occur)
            if (!is.null(current_station_id())) {
                loading_status(TRUE)
            }
        },
        priority = 1000,
        ignoreInit = TRUE
    )

    observeEvent(current_station_id(),
        {
            station_data(NULL)
            parsed_data_list(list())

            # Only block UI if a valid station is selected
            if (!is.null(current_station_id())) {
                fetch_pending(TRUE)
                loading_status(TRUE)
                session$sendCustomMessage("freezeUI", list(text = "Fetching station data...", allowCancel = TRUE))
                session$sendCustomMessage("updateFetchProgress", list(
                    percent = 5,
                    status = "Preparing request...",
                    indeterminate = TRUE,
                    visible = TRUE
                ))
            }
        },
        priority = 1000,
        ignoreInit = TRUE
    )

    # --- Async Fetching State Machine ---

    # State Variables
    fetch_stage <- reactiveVal(0) # 0=Idle, 1=Init, 2=NextFile, 3=Head, 4=Download, 5=Parse, 6=Merge
    fetch_message <- reactiveVal("Idle")
    fetch_queue <- reactiveVal(list()) # List of targets (url, etc.)
    fetch_queue_idx <- reactiveVal(0)
    parsed_data_list <- reactiveVal(list()) # Accumulate dataframes

    # Progress Tracking
    fetch_total_size <- reactiveVal(0)
    fetch_current_pos <- reactiveVal(0)
    fetch_current_token <- reactiveVal(NULL) # To invalidate stale sessions
    fetch_temp_file <- reactiveVal(NULL)
    fetch_trigger <- reactiveVal(0) # Counter to force fetch
    fetch_last_processed_request <- reactiveVal(NULL) # Track last processed request (list) to detect new requests

    # Fetch timing (lower values = faster response after click)
    fetch_debounce_ms <- 150
    fetch_ui_flush_delay <- 0.05

    # Short-lived in-session cache to speed up repeat station clicks
    station_cache_ttl <- 600 # 10 minutes (matches data update cycle)
    station_cache_max <- 20
    station_cache <- reactiveVal(list())

    cache_key_for <- function(station_id, resolution) {
        paste0(station_id, "|", resolution)
    }

    get_cached_station <- function(key) {
        cache <- isolate(station_cache())
        entry <- cache[[key]]
        if (is.null(entry) || is.null(entry$ts) || is.null(entry$df)) {
            return(NULL)
        }
        age <- as.numeric(difftime(Sys.time(), entry$ts, units = "secs"))
        if (!is.finite(age) || age > station_cache_ttl) {
            cache[[key]] <- NULL
            station_cache(cache)
            return(NULL)
        }
        entry$df
    }

    set_cached_station <- function(key, df) {
        cache <- isolate(station_cache())
        cache[[key]] <- list(ts = Sys.time(), df = df)
        if (length(cache) > station_cache_max) {
            times <- vapply(cache, function(x) as.numeric(x$ts), numeric(1))
            drop_n <- length(cache) - station_cache_max
            drop_keys <- names(sort(times))[seq_len(drop_n)]
            if (length(drop_keys) > 0) {
                cache[drop_keys] <- NULL
            }
        }
        station_cache(cache)
    }

    # Updated Trigger (Responds to Date Range Filter)
    window_reactive <- reactive({
        ft <- fetch_trigger()

        # Use Sidebar Date Range
        req(input$date_range)

        # Start at 00:00 of selected start date
        start_t <- as.POSIXct(input$date_range[1], tz = "UTC")

        # End date logic: if today, use current time; otherwise end of selected day
        end_d <- input$date_range[2]
        if (end_d >= Sys.Date()) {
            end_t <- lubridate::floor_date(Sys.time(), "10 minutes")
        } else {
            end_t <- as.POSIXct(end_d, tz = "UTC") + (24 * 3600) - 1
        }

        list(id = current_station_id(), start = start_t, end = end_t, trigger = ft)
    })
    window_debounced <- window_reactive %>% debounce(fetch_debounce_ms)

    # Helper to get current station name
    get_station_name <- function() {
        sid <- current_station_id()
        if (is.null(sid)) {
            return("")
        }
        st <- all_stations() %>% filter(id == sid)
        if (nrow(st) > 0) st$name[1] else sid
    }

    reset_fetch <- function(msg = NULL) {
        fetch_stage(0)
        # Invalidate token to kill pending async tasks
        fetch_current_token(as.numeric(Sys.time()))

        plot_render_pending(FALSE)
        loading_status(FALSE)
        fetch_pending(FALSE)
        session$sendCustomMessage("updateFetchProgress", list(visible = FALSE))
        if (!is.null(msg)) loading_diagnostics(msg)
        tmp <- fetch_temp_file()
        if (!is.null(tmp) && file.exists(tmp)) unlink(tmp)
        fetch_temp_file(NULL)
        parsed_data_list(list())
        # Unfreeze UI when fetch is reset/cancelled
        unfreeze_ui_if_idle()
    }

    # Handle Cancel from Freeze Window
    observeEvent(input$cancel_loading, {
        plot_render_pending(FALSE)
        reset_fetch("Cancelled by user")
        showNotification("Loading cancelled by user.", type = "warning")
    })

    # Handle plot rendering completion (sent by JS waitForPlots handler)
    observeEvent(input$plot_render_done, {
        plot_render_pending(FALSE)
    })


    # Stage 1: Initialization and Fetch
    observe({
        req(window_debounced()$start, window_debounced()$end)

        current_request <- window_debounced()

        # If no station selected, ensure UI is unfrozen
        if (is.null(current_request$id)) {
            unfreeze_ui_if_idle()
            return()
        }

        last_request <- fetch_last_processed_request()

        # Skip if we've already processed this exact request
        if (!is.null(last_request) && identical(current_request, last_request)) {
            return()
        }

        # Mark processed
        fetch_last_processed_request(current_request)

        # Basic setup
        station_id <- isolate(window_debounced()$id)

        st_meta <- isolate(all_stations()) %>% filter(id == station_id)
        if (nrow(st_meta) == 0) {
            reset_fetch("Station not found.")
            return()
        }

        # Store station location in JS for pending map highlight
        # (applied when the user navigates to Map View)
        session$sendCustomMessage("setPendingHighlight", list(
            lng = st_meta$longitude[1],
            lat = st_meta$latitude[1],
            label = paste0("<b>", htmltools::htmlEscape(st_meta$name[1]), "</b>")
        ))

        res_key <- tolower(isolate(current_resolution()))
        cache_key <- cache_key_for(station_id, res_key)
        cached_df <- get_cached_station(cache_key)
        if (!is.null(cached_df)) {
            fetch_pending(FALSE)
            station_data(cached_df)
            loading_diagnostics(paste0("Loaded ", nrow(cached_df), " records from cache."))
            updateNavbarPage(session, "main_nav", selected = "Dashboard")
            # Switch to Data subtab if URL requested dashboard-data
            if (!is.null(session$userData$pending_dashboard_subtab)) {
                shinyjs::delay(200, {
                    shinyjs::runjs("$('#dashboard_subtabs a[data-value=\"Data\"]').tab('show');")
                })
                session$userData$pending_dashboard_subtab <- NULL
            }
            # Show rendering message BEFORE clearing loading_status to prevent overlay flash
            session$sendCustomMessage("updateFetchProgress", list(visible = FALSE))
            plot_render_pending(TRUE)
            session$sendCustomMessage("freezeUI", list(text = "Rendering plots...", allowCancel = TRUE))
            loading_status(FALSE)
            session$onFlushed(function() {
                session$sendCustomMessage("waitForPlots", list())
            }, once = TRUE)
            return()
        }

        s_name <- st_meta$name[1]
        s_country_fetch <- st_meta$country[1]
        msg <- paste0("Fetching data for ", s_name, " (", s_country_fetch, ")...")
        loading_diagnostics(msg)
        fetch_message(msg)
        loading_status(TRUE)
        session$sendCustomMessage("freezeUI", list(text = msg, allowCancel = TRUE))
        session$sendCustomMessage("updateFetchProgress", list(
            percent = 5,
            status = paste0("Preparing fetch for ", s_name, "..."),
            indeterminate = TRUE,
            visible = TRUE
        ))
        fetch_pending(FALSE)
        fetch_stage(1)  # Mark fetch as active (reset_fetch sets this back to 0)

        run_station_fetch <- function() {
            # Check if cancelled before starting
            if (isolate(fetch_stage()) == 0) return()

            tryCatch(
                {
                    s_date <- current_request$start
                    e_date <- current_request$end

                    # Fetch Data
                    df <- read_meteogate_data(station_id, s_date, e_date, session = session)

                    # Check if cancelled during fetch
                    if (isolate(fetch_stage()) == 0) return()

                    if (is.null(df) || nrow(df) == 0) {
                        loading_diagnostics("No data returned from API.")
                        station_data(NULL)
                    } else {
                        set_cached_station(cache_key, df)
                        station_data(df)
                        loading_diagnostics(paste0("Loaded ", nrow(df), " records."))
                        # Navigate to Dashboard
                        updateNavbarPage(session, "main_nav", selected = "Dashboard")
                        # Switch to Data subtab if URL requested dashboard-data
                        if (!is.null(session$userData$pending_dashboard_subtab)) {
                            shinyjs::delay(200, {
                                shinyjs::runjs("$('#dashboard_subtabs a[data-value=\"Data\"]').tab('show');")
                            })
                            session$userData$pending_dashboard_subtab <- NULL
                        }
                    }
                },
                error = function(e) {
                    loading_diagnostics(paste("Error:", e$message))
                    station_data(NULL)
                }
            )

            # Check if cancelled during fetch — don't trigger render overlay
            if (isolate(fetch_stage()) == 0) return()

            # Show rendering message BEFORE clearing loading_status to prevent overlay flash
            session$sendCustomMessage("updateFetchProgress", list(visible = FALSE))
            plot_render_pending(TRUE)
            session$sendCustomMessage("freezeUI", list(text = "Rendering plots...", allowCancel = TRUE))
            loading_status(FALSE)
            session$onFlushed(function() {
                session$sendCustomMessage("waitForPlots", list())
            }, once = TRUE)
        }

        # Use later to allow UI flush
        later::later(function() {
            # If cancelled before this deferred callback fires, bail out
            if (isolate(fetch_stage()) == 0) return()

            api_cutoff <- Sys.time() - lubridate::hours(24)
            prefetch_status <- if (current_request$start < api_cutoff) {
                "Querying archive..."
            } else {
                paste0("Fetching latest API data for ", s_name, "...")
            }

            session$sendCustomMessage("updateFetchProgress", list(
                status = prefetch_status,
                visible = TRUE,
                indeterminate = TRUE,
                text = msg,
                allowCancel = TRUE
            ))

            session$onFlushed(function() {
                later::later(run_station_fetch, 0)
            }, once = TRUE)
        }, fetch_ui_flush_delay)
    })

    # Placeholder observers for removed stages to prevent errors if logic still triggers them
    # But strictly speaking we just removed the logic setting them.


    # Output logic for Panel
    output$is_loading <- reactive({
        loading_status()
    })
    outputOptions(output, "is_loading", suspendWhenHidden = FALSE)

    output$station_ready <- reactive({
        !is.null(station_data())
    })
    outputOptions(output, "station_ready", suspendWhenHidden = FALSE)

    output$data_diagnostics <- renderUI({
        HTML(loading_diagnostics())
    })

    output$has_diag <- reactive({
        nzchar(loading_diagnostics())
    })
    outputOptions(output, "has_diag", suspendWhenHidden = FALSE)

    # Station Meta
    output$panel_station_name <- renderText({
        req(current_station_id())
        s <- all_stations() %>% filter(id == current_station_id())
        if (nrow(s) > 0) paste0(s$name[1], " (", s$id[1], ")") else current_station_id()
    })

    output$panel_station_meta <- renderText({
        req(current_station_id())
        s <- all_stations() %>% filter(id == current_station_id())
        if (nrow(s) > 0) {
            paste0(
                s$state[1], " | ",
                "Lat: ", s$latitude[1], " | Lon: ", s$longitude[1], " | Elev: ", s$elevation[1], "m"
            )
        } else {
            ""
        }
    })
    # --- Plots ---
    # Shared reactive: applies modal date filtering on top of station_data().
    # Each renderPlotly below depends on plot_df() independently. Shiny's
    # output suspension ensures a renderPlotly only executes when its
    # corresponding plotlyOutput() is present in the DOM (i.e., when
    # details_tabs renderUI included it because the station has that data).
    # This avoids generating all 15 charts synchronously on every station click.
    plot_df <- reactive({
        df <- station_data()
        req(df)

        # Filter by Date Range from Modal (local processing)
        if (!is.null(input$modal_date_start) && !is.null(input$modal_date_end)) {
            df <- df %>% filter(
                datetime >= as.POSIXct(input$modal_date_start),
                datetime <= as.POSIXct(input$modal_date_end) + days(1)
            )
        }
        df
    })

    # Standalone plots for grid layout
    output$temp_single_plot <- renderPlotly({
        create_temperature_single_plot(plot_df())
    })
    output$humidity_plot <- renderPlotly({
        create_humidity_single_plot(plot_df())
    })

    # Individual solar/precip plots
    output$solar_radiation_plot <- renderPlotly({
        create_solar_radiation_plot(plot_df())
    })
    output$sunshine_duration_plot <- renderPlotly({
        create_sunshine_plot(plot_df())
    })
    output$etp_plot <- renderPlotly({
        create_etp_plot(plot_df())
    })
    output$precipitation_only_plot <- renderPlotly({
        create_precipitation_only_plot(plot_df(), resolution = tolower(current_resolution()))
    })
    output$snow_plot <- renderPlotly({
        create_snow_plot(plot_df())
    })
    output$ground_temp_plot <- renderPlotly({
        create_ground_temp_plot(plot_df())
    })
    output$soil_temp_plot <- renderPlotly({
        create_soil_temp_plot(plot_df())
    })
    output$wind_2m_gust_plot <- renderPlotly({
        create_wind_2m_gust_plot(plot_df())
    })

    # Pressure, Wind Time Series, Cloud, Visibility
    output$pressure_plot <- renderPlotly({
        create_pressure_plot(plot_df())
    })
    output$wind_time_series <- renderPlotly({
        create_wind_time_series_plot(plot_df())
    })
    output$cloud_cover_plot <- renderPlotly({
        create_cloud_cover_plot(plot_df())
    })
    output$visibility_plot <- renderPlotly({
        create_visibility_plot(plot_df())
    })

    output$wind_rose <- renderPlotly({
        create_wind_rose_plot(plot_df())
    })

    output$weathergami_plot <- renderPlotly({
        create_weathergami_plot(plot_df())
    })

    # Tables
    output$hourly_data_table <- DT::renderDataTable({
        req(station_data())
        res <- tolower(current_resolution())

        df_display <- station_data()
        df_display <- format_wind_speed_decimals(df_display, digits = 1)
        display_cols <- get_station_display_cols(df_display)
        units <- attr(df_display, "units")

        # Always format datetime with hours and minutes for accuracy
        df_display <- df_display %>% mutate(datetime = format(datetime, "%Y-%m-%d %H:%M"))

        # Ensure datetime is at the beginning if it exists
        if ("datetime" %in% display_cols) {
            display_cols <- c("datetime", setdiff(display_cols, "datetime"))
        }

        # Create readable labels for all columns (including units if available)
        pretty_labels <- sapply(seq_along(display_cols), function(i) {
            col <- display_cols[i]
            # Convert name to title case
            label <- col %>%
                gsub("_", " ", .) %>%
                stringr::str_to_title()

            # Special case for Datetime
            if (col == "datetime") {
                return(if (res == "daily") "Date" else "Date/Time")
            }

            # Append unit in square brackets if available for this parameter
            if (!is.null(units) && !is.null(units[[col]])) {
                label <- paste0(label, " [", units[[col]], "]")
            }
            return(label)
        }, USE.NAMES = FALSE)

        # Render the table with all available data
        datatable(df_display %>% select(all_of(display_cols)),
            colnames = pretty_labels,
            extensions = "FixedColumns",
            options = list(
                pageLength = 15,
                scrollX = TRUE,
                fixedColumns = list(leftColumns = 1),
                initComplete = JS("
                    function(settings, json) {
                        if (window.innerWidth <= 768) {
                            $(this.api().table().header()).find('th').each(function() {
                                var txt = $(this).text();
                                var abbrevMap = {
                                    'Precipitation Amount': 'Precip',
                                    'Air Temperature': 'Temp',
                                    'Wind Speed': 'Wind',
                                    'Wind Direction': 'Dir',
                                    'Relative Humidity': 'RH',
                                    'Solar Radiation': 'Solar',
                                    'Cloud Cover': 'Cloud',
                                    'Visibility': 'Vis',
                                    'Snow Depth': 'Snow D',
                                    'Snow Fresh': 'Snow F',
                                    'Sunshine Duration': 'Sun Dur',
                                    'Date/Time': 'Time'
                                };
                                for (var key in abbrevMap) {
                                    if (txt.indexOf(key) >= 0) {
                                        $(this).text(txt.replace(key, abbrevMap[key]));
                                        break;
                                    }
                                }
                            });
                        }
                    }
                ")
            )
        )
    })

    # Parameter Definitions UI - shows only available parameters for this station
    output$param_definitions_ui <- renderUI({
        req(current_resolution(), station_data(), current_station_id())
        res <- tolower(current_resolution())
        df <- station_data()
        sid <- current_station_id()

        # Get Metadata for this station
        # Get Metadata for this station
        st_meta <- all_stations() %>% filter(id == sid)

        expected_str <- NA_character_
        if (res == "hourly" && "params_hourly" %in% names(st_meta)) {
            expected_str <- st_meta$params_hourly[1]
        } else if (res == "daily" && "params_daily" %in% names(st_meta)) {
            expected_str <- st_meta$params_daily[1]
        } else if (res == "10-min" && "params_10min" %in% names(st_meta)) {
            expected_str <- st_meta$params_10min[1]
        } else if (res == "monthly" && "params_monthly" %in% names(st_meta)) expected_str <- st_meta$params_monthly[1]

        # Identify available columns (same logic as the table)
        display_cols <- get_station_display_cols(df)

        # Determine which columns have non-NA data
        has_data <- sapply(display_cols, function(col) {
            any(!is.na(df[[col]]))
        })

        available_cols <- display_cols[has_data]

        available_labels <- available_cols %>%
            gsub("_", " ", .) %>%
            stringr::str_to_title()

        # Clean up Datetime
        if (length(available_labels) > 0 && available_labels[1] == "Datetime") {
            available_labels[1] <- if (res == "daily") "Date" else "Date/Time"
        }

        ui_elements <- list()

        if (length(available_labels) > 0) {
            ui_elements[[length(ui_elements) + 1]] <- div(
                style = "background-color: #d4edda; border: 1px solid #28a745; border-radius: 5px; padding: 10px; margin-bottom: 5px; font-size: 0.85rem;",
                tags$strong(bsicons::bs_icon("check-circle"), " Available: "),
                paste(available_labels, collapse = " | ")
            )
        }

        if (!is.null(expected_str) && !is.na(expected_str) && nzchar(expected_str)) {
            ui_elements[[length(ui_elements) + 1]] <- div(
                style = "background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 5px; padding: 10px; margin-bottom: 5px; font-size: 0.85rem;",
                tags$strong(bsicons::bs_icon("info-circle"), " Metadata Expected Parameters: "),
                expected_str
            )
        }

        if (length(ui_elements) == 0) {
            return(div(
                style = "background-color: #f8d7da; border: 1px solid #dc3545; border-radius: 5px; padding: 10px; margin-bottom: 15px; font-size: 0.85rem;",
                bsicons::bs_icon("x-circle"), " No data found for this station and resolution."
            ))
        }

        tagList(ui_elements)
    })

    # Download Handler
    output$download_hourly <- downloadHandler(
        filename = function() {
            id <- current_station_id()
            res <- if (!is.null(current_resolution())) tolower(current_resolution()) else "data"
            if (is.null(id)) {
                paste0("meteo_data_", res, ".xlsx")
            } else {
                paste0("meteo_station_", id, "_", res, ".xlsx")
            }
        },
        content = function(file) {
            req(station_data())
            # writexl handles dates nicely natively.
            out_df <- station_data() %>% format_wind_speed_decimals(digits = 1)
            write_xlsx(out_df, path = file)
        }
    )

    # Info Callout Card
    output$station_info_header <- renderUI({
        id <- current_station_id()
        if (is.null(id)) {
            return(NULL)
        }

        # Fetch basic meta directly from the base list to avoid blocking on index loading
        # This ensures the header stays visible during resolution switch
        stations_base <- get_meteogate_stations()
        meta <- stations_base %>% dplyr::filter(id == !!id)
        if (nrow(meta) == 0) {
            # Try from enriched list just in case
            meta <- all_stations() %>% dplyr::filter(id == !!id)
            if (nrow(meta) == 0) {
                return(NULL)
            }
        }

        s_name <- meta$name[1]
        s_state <- meta$country[1]
        s_elev <- meta$elevation[1]

        # Dynamic Badge Logic
        res_label <- current_resolution()
        res_class <- if (tolower(res_label) == "hourly") "bg-primary" else "bg-success"

        # Data Range
        df <- station_data()
        if (is.null(df) || nrow(df) == 0) {
            dates_text <- "No data loaded"
        } else {
            date_range <- range(as.Date(df$datetime), na.rm = TRUE)
            dates_text <- paste(date_range[1], "to", date_range[2])
        }

        # Unified Info Card
        card(
            style = "margin-bottom: 20px; border-left: 5px solid #007bff;",
            card_body(
                padding = 15,
                layout_columns(
                    fill = FALSE,
                    col_widths = breakpoints(sm = c(6, 6, 6, 6, 12), lg = c(3, 2, 2, 3, 2)),
                    # Col 1: Station
                    div(
                        strong("Station"), br(),
                        span(paste0(s_name, " (", s_state, ")"), style = "font-size: 1.1rem;"), br(),
                        tags$small(class = "text-muted", paste("ID:", id))
                    ),
                    # Col 2: Location
                    div(
                        strong("Location"), br(),
                        span(s_state), br(),
                        tags$small(class = "text-muted", paste0(meta$latitude[1], "°N, ", meta$longitude[1], "°E"))
                    ),
                    # Col 3: Elevation & Resolution
                    div(
                        strong("Technical"), br(),
                        span(paste0(s_elev, " m")), br(),
                        span(class = paste("badge", res_class), res_label)
                    ),
                    # Col 4: Period
                    div(
                        strong("Data Selection"), br(),
                        span(dates_text)
                    ),
                    # Col 5: Actions
                    div(
                        class = "d-flex align-items-center justify-content-end",
                        downloadButton(
                            "download_hourly",
                            label = "Export Excel",
                            class = "btn-sm btn-primary",
                            icon = icon("file-excel")
                        )
                    )
                )
            )
        )
    })

    output$table <- DT::renderDataTable({
        # React to changes in parameter and time (via viewport_obs_data)
        obs_data <- viewport_obs_data()
        current_param <- input$map_parameter
        if (is.null(current_param)) current_param <- "air_temperature"

        # Determine column label based on parameter
        param_label <- switch(current_param,
            "air_temperature" = "Temperature (°C)",
            "precipitation_amount" = "Precipitation (mm)",
            "air_pressure_at_mean_sea_level" = "Pressure (hPa)",
            "wind_speed" = "Wind Speed (m/s)",
            "Value"
        )

        # Base metadata
        base_stations <- filtered_stations() %>%
            mutate(
                display_params = sapply(available_params, function(p) get_resolution_params(tolower(current_resolution()), p))
            )

        # Keep only stations with data for selected parameter + selected time step
        if (!is.null(obs_data) && nrow(obs_data) > 0) {
            obs_filtered <- obs_data %>%
                filter(!is.na(station_id), !is.na(temp)) %>%
                group_by(station_id) %>%
                arrange(desc(datetime)) %>%
                slice(1) %>%
                ungroup() %>%
                select(station_id, temp)
        } else {
            obs_filtered <- data.frame(
                station_id = character(0),
                temp = numeric(0),
                stringsAsFactors = FALSE
            )
        }

        # obs_data has columns: station_id, temp (value), datetime, param_name
        # We join on id = station_id and keep only matched stations
        df_stations <- base_stations %>%
            inner_join(obs_filtered, by = c("id" = "station_id")) %>%
            rename(!!param_label := temp)

        # Select columns for display
        # We put the value column after Elevation
        df_stations <- df_stations %>%
            select(
                "Station ID" = id,
                "Name" = name,
                "Country" = country,
                "Region" = region,
                "Elevation" = elevation,
                !!param_label,
                "Parameters" = display_params
            )

        datatable(df_stations,
            selection = "none",
            rownames = FALSE,
            options = list(
                pageLength = 25,
                scrollX = TRUE,
                columnDefs = list(
                    list(
                        targets = c(0, 6),
                        visible = JS("window.innerWidth > 768")
                    )
                )
            ),
            callback = JS("
                table.on('dblclick', 'tr', function() {
                    var rowData = table.row(this).data();
                    if (rowData !== undefined && rowData !== null) {
                        var stationId = rowData[0];
                        Shiny.setInputValue('table_station_dblclick', stationId, {priority: 'event'});
                        if (typeof window.collapseSidebarOnMobile === 'function') window.collapseSidebarOnMobile();
                    }
                });
                // Single-tap selection on mobile
                if (window.innerWidth <= 768) {
                    table.on('click', 'tr', function() {
                        var rowData = table.row(this).data();
                        if (rowData !== undefined && rowData !== null) {
                            var stationId = rowData[0];
                            Shiny.setInputValue('table_station_dblclick', stationId, {priority: 'event'});
                            if (typeof window.collapseSidebarOnMobile === 'function') window.collapseSidebarOnMobile();
                        }
                    });
                }
            ")
        )
    })

    # Selection from Table - Double Click (uses station ID directly)
    observeEvent(input$table_station_dblclick, {
        raw_id <- as.character(input$table_station_dblclick)
        req(raw_id)
        station_id <- trimws(raw_id)

        # Immediate tab switch for responsiveness
        updateNavbarPage(session, "main_nav", selected = "Dashboard")

        # Set ID and trigger fetch immediately
        current_station_id(station_id)
        # Force fetch state machine to re-evaluate
        fetch_trigger(fetch_trigger() + 1)

        # Sync dropdown (sidebar)
        updateSelectizeInput(session, "station_selector", selected = station_id)

        # Try to find metadata for map highlight
        s <- NULL
        df <- filtered_stations()
        if (!is.null(df)) {
            s <- df %>% filter(as.character(id) == station_id)
        }

        if (is.null(s) || nrow(s) == 0) {
            # Try all stations
            s <- all_stations() %>% filter(as.character(id) == station_id)
        }

        # Only proceed with map interactions if we found metadata
        if (!is.null(s) && nrow(s) > 0) {
            lat_val <- s$latitude[1]
            lng_val <- s$longitude[1]

            # Generate Label for marker
            res_info <- if ("resolution_info" %in% names(s)) s$resolution_info[1] else "Data status unavailable"
            if (is.null(res_info) || is.na(res_info)) res_info <- "Data status unavailable for current filter"

            # Try to get temperature from view session for the label
            obs <- viewport_obs_data()
            match <- if (!is.null(obs)) obs %>% filter(station_id == station_id) else NULL
            current_temp <- if (!is.null(match) && nrow(match) > 0) match$temp[1] else NULL
            current_param_name <- if (!is.null(match) && nrow(match) > 0 && "param_name" %in% names(match)) {
                match$param_name[1]
            } else {
                NA_character_
            }

            current_param <- isolate(input$map_parameter)
            if (is.null(current_param)) current_param <- "air_temperature"
            param_label <- if (current_param == "precipitation_amount") "Precipitation" else "Air Temperature"
            param_unit <- if (current_param == "precipitation_amount") "mm" else "°C"
            missing_label <- if (current_param == "precipitation_amount") "No precip available at this hour" else NULL

            label_name <- if (current_param == "precipitation_amount") {
                format_precip_label(current_param_name, param_label)
            } else {
                param_label
            }

            lbl <- generate_station_label(
                s$name[1], s$id[1], s$country[1],
                s$start_date[1], s$end_date[1], s$detailed_summary[1],
                res_info,
                val = current_temp,
                label_name = label_name,
                unit = param_unit,
                missing_label = missing_label
            )

            highlight_selected_station(maplibre_proxy("map"), lng_val, lat_val, lbl)
        }
    })

    # Dynamic Plots Panel - All plots in grid format (no tabs)
    # Only display plots that have data available
    output$details_tabs <- renderUI({
        req(current_resolution())
        res <- tolower(current_resolution())
        df <- station_data()
        req(df)

        # Clean data first to ensure flags (e.g. 9999) are treated as NA for availability checks
        df <- clean_weather_data(df)

        # Check data availability for each parameter
        has_temp <- ("temp" %in% names(df) && any(!is.na(df$temp))) ||
            ("temp_min" %in% names(df) && any(!is.na(df$temp_min))) ||
            ("temp_max" %in% names(df) && any(!is.na(df$temp_max)))

        has_rh <- ("rh" %in% names(df) && any(!is.na(df$rh)))

        # For humidity plot, need either RH or ability to calculate dew point
        has_humidity_data <- has_rh || (has_temp && has_rh)

        has_wind <- ("wind_speed" %in% names(df) && any(!is.na(df$wind_speed))) ||
            ("wind_gust" %in% names(df) && any(!is.na(df$wind_gust)))

        has_pressure <- ("pressure" %in% names(df) && any(!is.na(df$pressure)))

        has_cloud <- ("cloud_cover" %in% names(df) && any(!is.na(df$cloud_cover)))

        has_precip <- ("precip" %in% names(df) && any(!is.na(df$precip)))

        has_snow <- ("snow_fresh" %in% names(df) && any(df$snow_fresh > 0, na.rm = TRUE)) ||
            ("snow_depth" %in% names(df) && any(df$snow_depth > 0, na.rm = TRUE))

        has_ground_temp <- ("temp_min_ground" %in% names(df) && any(!is.na(df$temp_min_ground))) ||
            ("temp_min_50cm" %in% names(df) && any(!is.na(df$temp_min_50cm)))

        has_soil_temp <- ("soil_temp_10cm" %in% names(df) && any(!is.na(df$soil_temp_10cm))) ||
            ("soil_temp_20cm" %in% names(df) && any(!is.na(df$soil_temp_20cm))) ||
            ("soil_temp_50cm" %in% names(df) && any(!is.na(df$soil_temp_50cm)))

        has_wind_2m_gust <- ("wind_speed_2m" %in% names(df) && any(!is.na(df$wind_speed_2m))) ||
            ("wind_gust_inst" %in% names(df) && any(!is.na(df$wind_gust_inst)))

        has_solar <- ("solar_global" %in% names(df) && any(!is.na(df$solar_global)))

        has_sunshine <- ("sunshine_duration" %in% names(df) && any(!is.na(df$sunshine_duration)))

        has_etp <- ("etp" %in% names(df) && any(!is.na(df$etp)))

        has_wind_dir <- ("wind_dir" %in% names(df) && any(!is.na(df$wind_dir))) && has_wind

        has_pressure_data <- ("pressure" %in% names(df) && any(!is.na(df$pressure))) ||
            ("pressure_sea" %in% names(df) && any(!is.na(df$pressure_sea))) ||
            ("pressure_station" %in% names(df) && any(!is.na(df$pressure_station))) # Check generic pressure for fallback

        has_vis <- ("visibility" %in% names(df) && any(!is.na(df$visibility)))

        has_daily_temp <- ("temp_min" %in% names(df) && any(!is.na(df$temp_min))) &&
            ("temp_max" %in% names(df) && any(!is.na(df$temp_max)))

        # Build list of available plots
        plot_list <- tagList()

        # Temperature plot (standalone with Tmin/Tmax for daily)
        if (has_temp) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("temp_single_plot", height = "320px")))
        }

        # Humidity plot (separate plot for RH and dew point)
        if (has_humidity_data) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("humidity_plot", height = "320px")))
        }

        # Individual precipitation plot (no snow)
        if (has_precip) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("precipitation_only_plot", height = "320px")))
        }

        if (has_snow) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("snow_plot", height = "320px")))
        }

        # Ground Temperature Plot (New)
        if (has_ground_temp) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("ground_temp_plot", height = "320px")))
        }

        # Soil Temperature Plot (New)
        if (has_soil_temp) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("soil_temp_plot", height = "320px")))
        }

        # Pressure Plot (New)
        if (has_pressure_data) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("pressure_plot", height = "320px")))
        }

        # Cloud Cover Plot (New)
        if (has_cloud) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("cloud_cover_plot", height = "320px")))
        }

        # Wind Time Series Plot (New) - Speed & Gust
        if (has_wind) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("wind_time_series", height = "320px")))
        }

        # Wind 2m & Instant Gust (New)
        if (has_wind_2m_gust) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("wind_2m_gust_plot", height = "320px")))
        }

        # Visibility Plot (New)
        if (has_vis) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("visibility_plot", height = "320px")))
        }

        # Solar radiation (separate)
        if (has_solar) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("solar_radiation_plot", height = "320px")))
        }

        # Sunshine duration (separate)
        if (has_sunshine) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("sunshine_duration_plot", height = "320px")))
        }

        # ETP (separate)
        if (has_etp) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("etp_plot", height = "320px")))
        }

        # Conditional: Wind Rose for hourly, Weathergami for daily
        if (res == "hourly" && has_wind_dir) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("wind_rose", height = "450px")))
        }
        if (res == "daily" && has_daily_temp) {
            plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("weathergami_plot", height = "320px")))
        }

        # Wrap in grid container
        div(
            class = "row g-3",
            style = "padding: 10px;",
            plot_list
        )
    })

    # Map Legend (Dynamic)
    output$map_legend <- renderUI({
        obs <- viewport_obs_data()
        param_type <- input$map_parameter

        if (is.null(param_type) || param_type == "air_temperature") {
            # Temperature Legend - ECMWF palette (sh_all_fM50t58i2)
            # Use fixed 2°C intervals from -50°C to 58°C
            ecmwf_breaks <- seq(-50, 58, by = 2)

            # Determine displayed range based on data
            t_max <- 40
            t_min <- -20

            if (!is.null(obs) && nrow(obs) > 0) {
                current_range <- range(obs$temp, na.rm = TRUE)
                # Round to nearest ECMWF interval
                t_max <- ceiling(current_range[2] / 2) * 2
                t_min <- floor(current_range[1] / 2) * 2
                t_max <- min(58, t_max)
                t_min <- max(-50, t_min)
            }

            # Filter ECMWF breaks to displayed range
            temps <- ecmwf_breaks[ecmwf_breaks >= t_min & ecmwf_breaks <= t_max]
            temps <- rev(temps)

            tagList(
                div(class = "legend-title", "[°C]"),
                lapply(temps, function(t) {
                    color <- temp_to_color(t)
                    # Show label for key values
                    show_label <- t %% 8 == 0 | t == 0
                    div(
                        class = "legend-item",
                        div(class = "legend-color", style = paste0("background-color: ", color, "; opacity: 0.8;")),
                        if (show_label) div(class = "legend-label", t)
                    )
                })
            )
        } else if (param_type == "air_pressure_at_mean_sea_level") {
            # Pressure Legend - ECMWF Style (5hPa steps)
            p_stops <- seq(960, 1040, by = 5)

            # Determine range to display based on data (snap to 5hPa)
            display_min <- 960
            display_max <- 1040

            if (!is.null(obs) && nrow(obs) > 0) {
                # Calculate data range
                rng <- range(obs$temp, na.rm = TRUE)
                # Snap to nearest 5
                d_min_snap <- floor(rng[1] / 5) * 5
                d_max_snap <- ceiling(rng[2] / 5) * 5

                # Constrain to palette limits
                display_min <- max(960, d_min_snap)
                display_max <- min(1040, d_max_snap)

                # Ensure valid range
                if (display_max < display_min) display_max <- display_min
            }

            # Filter stops for display
            display_stops <- p_stops[p_stops >= display_min & p_stops <= display_max]
            # Reverse for vertical legend (High at top usually, but here we list Top->Bottom)
            # Standard legend usually lists high values at top? Or low values?
            # Existing code for Temp does High->Low (Warm->Cold).
            # For Pressure, let's do High->Low (Red->Purple)
            display_stops <- rev(display_stops)

            tagList(
                div(class = "legend-title", "[hPa]"),
                lapply(display_stops, function(p) {
                    # Legend item represents the bin starting at p?
                    # Since our palette is discrete intervals, let's show the color for the value p
                    color <- pressure_to_color(p)

                    # Show label for every step (since 5hPa is coarse enough)
                    div(
                        class = "legend-item",
                        div(class = "legend-color", style = paste0("background-color: ", color, "; opacity: 0.9;")),
                        div(class = "legend-label", p)
                    )
                })
            )
        } else if (param_type == "wind_speed") {
            # Wind Speed Legend - ECMWF Style (Discrete steps)
            # Define standard steps
            w_stops <- c(0.5, 2, 4, 6, 10, 15, 20, 25, 30, 40, 50)

            # Determine max to display
            display_max <- 30
            if (!is.null(obs) && nrow(obs) > 0) {
                rng <- range(obs$temp, na.rm = TRUE)
                w_max_data <- rng[2]
                # Find appropriate max stop
                display_max <- w_stops[findInterval(w_max_data, w_stops) + 1]
                if (is.na(display_max)) display_max <- 50
                display_max <- max(15, display_max) # Show at least up to 15m/s
            }

            # Filter stops
            display_stops <- w_stops[w_stops <= display_max]

            # High -> Low
            display_stops <- rev(display_stops)

            tagList(
                div(class = "legend-title", "[m/s]"),
                lapply(display_stops, function(w) {
                    # For legend, show color corresponding to the bin *ending* at w?
                    # Or starting?
                    # Palette logic: findInterval(val, stops)
                    # So value 12 is >10 and <15.
                    # We want to show the color for the bin represented by 'w'.
                    # Let's pick a value slightly below w for the color look up if looking downwards?
                    # Actually, our stops are upper bounds of the lower bins?
                    # stops <- c(0.5, 2, 4...)
                    # Val 1.5 -> idx 2 (between 0.5 and 2)

                    # Simpler: just pass 'w' to wind_speed_to_color.
                    # If w=10, it returns color for 10-15 bin? No.
                    # wind_speed_to_color(10) -> idx 5 (stops=...6, 10...)
                    # 10 is the upper bound of 6-10? findInterval(10, ...6, 10) is index corresponding to 6.
                    # Let's rely on wind_speed_to_color(w) returning the color for the "w" level.

                    color <- wind_speed_to_color(w)

                    div(
                        class = "legend-item",
                        div(class = "legend-color", style = paste0("background-color: ", color, "; opacity: 0.9;")),
                        div(class = "legend-label", w)
                    )
                })
            )
        } else {
            # Precipitation Legend
            p_max <- 50
            p_min <- 0

            if (!is.null(obs) && nrow(obs) > 0) {
                current_range <- range(obs$temp, na.rm = TRUE)
                p_max <- ceiling(current_range[2] / 5) * 5
                p_min <- 0
                p_max <- min(50, max(5, p_max))
            }

            precip_stops <- c(0, 0.1, 1, 5, 10, 25, 50)
            precip_stops <- precip_stops[precip_stops <= p_max]
            precip_stops <- rev(precip_stops)

            tagList(
                div(class = "legend-title", "[mm]"),
                lapply(precip_stops, function(p) {
                    color <- precip_to_color(p)
                    div(
                        class = "legend-item",
                        div(class = "legend-color", style = paste0("background-color: ", color, "; opacity: 0.8;")),
                        div(class = "legend-label", p)
                    )
                })
            )
        }
    })

    # Downloads
    output$download_data <- downloadHandler(
        filename = function() {
            paste0("meteo_station_", current_station_id(), ".csv")
        },
        content = function(file) {
            out_df <- station_data() %>% format_wind_speed_decimals(digits = 1)
            write_csv(out_df, file)
        }
    )
}