File size: 131,145 Bytes
3a82336
a159716
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a159716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755ad83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01fe9a9
 
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da8d7b2
3a82336
 
da8d7b2
3a82336
 
da8d7b2
3a82336
 
da8d7b2
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a159716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
 
 
 
a159716
3a82336
 
 
 
f9386fc
 
 
 
 
 
 
 
 
 
 
 
18b5aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9386fc
3a82336
 
 
 
 
 
 
 
 
f9386fc
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bebb952
 
5b69312
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa21d71
 
 
 
 
 
dedefab
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a159716
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755ad83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
01fe9a9
 
 
 
 
755ad83
3a82336
 
 
 
 
 
f9386fc
3a82336
 
 
 
 
f9386fc
3a82336
 
 
f9386fc
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da8d7b2
 
 
 
 
3a82336
 
 
 
 
 
 
 
da8d7b2
3a82336
 
 
da8d7b2
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18b5aed
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18b5aed
 
3a82336
 
 
18b5aed
3a82336
18b5aed
3a82336
18b5aed
3a82336
18b5aed
3a82336
18b5aed
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a159716
3a82336
 
 
a159716
 
3a82336
 
 
a159716
 
 
 
 
 
 
 
 
 
3a82336
a159716
3a82336
 
 
a159716
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86c05e4
 
abae764
3a82336
a159716
 
dedefab
0bb888e
82900b3
fa21d71
bebb952
3a82336
 
 
18b5aed
 
 
3a82336
fa21d71
 
a159716
 
bebb952
 
 
fa21d71
bebb952
 
 
fa21d71
 
a159716
fa21d71
 
bebb952
 
 
 
a159716
bebb952
a159716
 
fa21d71
bebb952
bee9a1c
abae764
3a82336
 
 
 
 
 
 
 
 
 
 
 
18b5aed
3a82336
 
 
 
 
 
 
 
 
bebb952
 
 
18b5aed
 
bebb952
 
18b5aed
bebb952
 
 
 
 
a159716
 
18b5aed
 
a159716
 
 
 
 
 
 
 
 
 
 
 
 
 
c1a1a65
 
 
a159716
 
 
 
 
 
18b5aed
a159716
 
 
 
 
bebb952
a159716
 
 
 
18b5aed
a159716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bebb952
3a82336
a159716
3a82336
 
18b5aed
3a82336
a159716
3a82336
 
a159716
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
bebb952
3a82336
bebb952
3a82336
a159716
3a82336
 
18b5aed
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bebb952
3a82336
0bb888e
abae764
 
0bb888e
abae764
 
0bb888e
 
 
abae764
0bb888e
abae764
0bb888e
 
abae764
dedefab
fa21d71
dedefab
 
18b5aed
dedefab
bee9a1c
dedefab
abae764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bee9a1c
 
0bb888e
abae764
bee9a1c
 
abae764
bee9a1c
 
 
 
 
0bb888e
bee9a1c
 
 
 
 
 
 
 
abae764
 
bee9a1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bb888e
bee9a1c
 
 
 
 
 
 
 
 
0bb888e
bee9a1c
 
dedefab
abae764
0bb888e
 
 
abae764
 
 
0bb888e
abae764
dedefab
 
 
 
0bb888e
 
 
 
 
dedefab
 
0bb888e
 
dedefab
0bb888e
 
 
 
 
 
 
 
dedefab
0bb888e
 
 
 
dedefab
0bb888e
 
 
 
 
 
bee9a1c
0bb888e
bee9a1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bb888e
bee9a1c
 
 
 
 
 
 
 
dedefab
 
0bb888e
dedefab
 
 
 
 
abae764
 
dedefab
3a82336
fa21d71
3a82336
 
18b5aed
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abae764
0bb888e
abae764
 
 
 
 
 
 
86c05e4
abae764
86c05e4
abae764
86c05e4
 
 
 
 
 
 
abae764
86c05e4
 
 
abae764
 
82900b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
86c05e4
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
fa21d71
 
 
 
 
18b5aed
fa21d71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
fa21d71
3a82336
 
18b5aed
3a82336
 
 
 
 
 
 
 
 
 
fa21d71
3a82336
 
18b5aed
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75813ed
3a82336
 
 
 
 
 
 
 
f9386fc
3a82336
 
 
a159716
75813ed
3a82336
 
a159716
f9386fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01fe9a9
 
 
 
 
 
 
 
f9386fc
 
 
 
3a82336
 
 
01fe9a9
3a82336
 
f9386fc
 
 
 
3a82336
 
 
 
 
 
 
 
 
 
 
 
 
f9386fc
 
 
 
 
 
 
 
3a82336
f9386fc
18b5aed
3a82336
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en" data-variant="__INFERENCE_BACKEND__">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=1280" />
<title>FlutIQ — flood risk advisor</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,300;9..40,400;9..40,500;9..40,600;9..40,700&family=JetBrains+Mono:wght@400;500;600&family=Instrument+Serif:ital@0;1&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<style>
  :root {
    --bg: #F6F4EE;
    --surface: #FFFFFF;
    --ink: #161616;
    --ink-2: #3A3A3A;
    --ink-3: #6B7280;
    --ink-4: #9CA3AF;
    --line: rgba(22,22,22,0.10);
    --line-2: rgba(22,22,22,0.06);
    --accent: #2B6FD4;
    --accent-2: #6FA8DD;
    --accent-soft: #E6EFF8;
    --teal: #0F8A6A;
    --teal-soft: #DDF1E9;
    --amber: #D4881E;
    --amber-soft: #FAEED4;
    --coral: #EE6A3D;
    --coral-soft: #FCE2D5;
    --purple: #6E5FD8;
    --purple-soft: #ECE9F9;
    --pink: #E84F86;
    --pink-soft: #FCE2EB;
    --lemon: #F2D24A;
    --lemon-soft: #FBF1C7;
    --map-bg: #EAF1F0;
    --map-water: #BFD7E8;
    --map-park: #D4E5C8;
    --map-road: #F8F5EE;
    --map-stroke: rgba(22,22,22,0.14);
  }

  /* FlutIQ Edge variant — Ollama / on-device inference. Green accent
     palette signals "running locally" at a glance. The four hardcoded
     gradient stops below mirror the blue gradients elsewhere in the
     stylesheet, just shifted to a teal-green family. */
  html[data-variant="ollama"] {
    --accent: #0F8A6A;
    --accent-2: #4FB793;
    --accent-soft: #DDF1E9;
  }
  html[data-variant="ollama"] .wordmark .glyph {
    background: radial-gradient(circle at 30% 25%, #A8E0CC 0%, var(--accent) 55%, #074C3A 100%);
  }
  html[data-variant="ollama"] .droplet {
    background: radial-gradient(circle at 32% 28%, #BFE8D5 0%, var(--accent) 55%, #074C3A 100%);
  }
  html[data-variant="ollama"] .search-submit {
    background: linear-gradient(135deg, var(--accent) 0%, #074C3A 100%);
  }
  html[data-variant="ollama"] .center-pin {
    background: radial-gradient(circle at 30% 25%, #BFE8D5 0%, var(--accent) 55%, #074C3A 100%);
  }

  body::before {
    content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 0;
    background:
      radial-gradient(700px 500px at 6% 8%, rgba(43,111,212,0.05), transparent 60%),
      radial-gradient(600px 420px at 96% 92%, rgba(15,138,106,0.05), transparent 60%);
  }
  body.dark::before {
    background:
      radial-gradient(700px 500px at 6% 8%, rgba(111,168,221,0.10), transparent 60%),
      radial-gradient(600px 420px at 96% 92%, rgba(79,184,154,0.10), transparent 60%);
  }
  #app { position: relative; z-index: 1; }
  * { box-sizing: border-box; }
  html, body { margin: 0; padding: 0; background: var(--bg); color: var(--ink); font-family: 'DM Sans', system-ui, sans-serif; -webkit-font-smoothing: antialiased; }
  body { min-height: 100vh; }
  ::selection { background: var(--accent); color: #fff; }
  button { font-family: inherit; }
  .mono { font-family: 'JetBrains Mono', ui-monospace, monospace; font-feature-settings: "ss01"; }
  .serif { font-family: 'Instrument Serif', Georgia, serif; }

  #app { min-height: 100vh; display: flex; flex-direction: column; }
  .app-chrome {
    height: 52px;
    border-bottom: 0.5px solid var(--line);
    display: flex; align-items: center; justify-content: space-between;
    padding: 0 24px;
    background: var(--surface);
    position: sticky; top: 0; z-index: 30;
  }
  .wordmark { display: flex; align-items: center; gap: 10px; font-weight: 500; letter-spacing: -0.01em; }
  .wordmark .glyph {
    width: 26px; height: 26px; border-radius: 50%;
    background: radial-gradient(circle at 30% 25%, #9CC9FF 0%, var(--accent) 55%, #1A4FA0 100%);
    box-shadow: inset 0 -4px 6px rgba(0,0,0,0.18), 0 2px 6px rgba(43,111,212,0.35);
    display: grid; place-items: center; color: #fff;
    font-family: 'Instrument Serif', serif; font-size: 14px; font-style: italic; font-weight: 500;
    position: relative;
    animation: bob 4s ease-in-out infinite;
  }
  .wordmark .glyph::after {
    content: ""; position: absolute; top: 4px; left: 6px;
    width: 6px; height: 4px; border-radius: 50%;
    background: rgba(255,255,255,0.85); filter: blur(0.4px);
  }
  @keyframes bob { 0%,100% { transform: translateY(0) rotate(-2deg); } 50% { transform: translateY(-2px) rotate(2deg); } }
  .chrome-meta { display: flex; align-items: center; gap: 16px; font-size: 12px; color: var(--ink-3); }
  .chrome-meta .pill { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px; border: 0.5px solid var(--line); border-radius: 999px; background: transparent; color: inherit; cursor: pointer; }
  .chrome-meta .pill.static { cursor: default; }
  .chrome-meta .pill.active { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
  .chrome-meta .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--teal); }
  .chrome-meta .icon-btn { display: inline-grid; place-items: center; width: 28px; height: 28px; border-radius: 8px; border: 0.5px solid var(--line); background: var(--surface); color: var(--ink-3); cursor: pointer; }
  .chrome-meta .icon-btn:hover { color: var(--ink); border-color: var(--ink-3); }

  .screen { animation: fade 320ms ease both; }
  @keyframes fade { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
  @keyframes pulseSoft { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } }
  @keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }
  @keyframes barFill { from { width: 0; } }

  .search-wrap { flex: 1; display: grid; place-items: center; padding: 64px 24px 96px; position: relative; }
  .search-card { width: 100%; max-width: 720px; position: relative; z-index: 2; }

  .mascot-cluster { position: absolute; pointer-events: none; }
  .mascot-cluster.tl { top: 80px; left: 8%; }
  .mascot-cluster.tr { top: 120px; right: 6%; }
  .mascot-cluster.br { bottom: 60px; right: 12%; }
  .droplet {
    width: 44px; height: 56px;
    background: radial-gradient(circle at 32% 28%, #BCDBFF 0%, var(--accent) 55%, #1A4FA0 100%);
    border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
    transform: rotate(-8deg);
    box-shadow: inset 0 -8px 10px rgba(0,0,0,0.18), 0 8px 22px rgba(43,111,212,0.28);
    position: relative;
    animation: floaty 6s ease-in-out infinite;
  }
  .droplet::before {
    content: ""; position: absolute; top: 8px; left: 10px;
    width: 10px; height: 14px; border-radius: 50%;
    background: rgba(255,255,255,0.7); filter: blur(0.5px);
    transform: rotate(-15deg);
  }
  .droplet .eyes { position: absolute; bottom: 16px; left: 0; right: 0; display: flex; justify-content: center; gap: 6px; }
  .droplet .eye { width: 5px; height: 7px; border-radius: 50%; background: #1A1F2E; animation: blink 5s infinite; }
  .droplet .smile { position: absolute; bottom: 8px; left: 50%; transform: translateX(-50%); width: 10px; height: 5px; border-bottom: 1.5px solid #1A1F2E; border-radius: 0 0 50% 50%; }
  .droplet.sm { transform: rotate(-8deg) scale(0.55); animation-delay: -1.5s; }
  .droplet.xs { transform: rotate(8deg) scale(0.4); animation-delay: -3s; }
  @keyframes floaty { 0%,100% { translate: 0 0; } 50% { translate: 0 -10px; } }
  @keyframes blink { 0%, 92%, 100% { transform: scaleY(1); } 96% { transform: scaleY(0.1); } }

  .sparkle { position: absolute; width: 10px; height: 10px; opacity: 0.85; animation: twinkle 2.4s ease-in-out infinite; }
  .sparkle::before, .sparkle::after { content: ""; position: absolute; inset: 0; background: var(--accent); border-radius: 50%; }
  .sparkle::before { transform: scaleY(0.18); }
  .sparkle::after  { transform: scaleX(0.18); }
  .sparkle.s2 { background: transparent; animation-delay: -1.2s; }
  .sparkle.s2::before, .sparkle.s2::after { background: var(--pink); }
  .sparkle.s3::before, .sparkle.s3::after { background: var(--lemon); }
  @keyframes twinkle { 0%,100% { transform: scale(0.4); opacity: 0; } 50% { transform: scale(1); opacity: 1; } }

  .eyebrow { display: inline-flex; align-items: center; gap: 8px; font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-3); }
  .eyebrow::before { content: ""; width: 18px; height: 1px; background: var(--ink-4); }
  h1.lede { font-size: 64px; line-height: 1.02; letter-spacing: -0.035em; font-weight: 400; margin: 18px 0 0; font-family: 'Instrument Serif', serif; }
  h1.lede em { font-style: italic; color: var(--accent); }
  .lede-sub { margin: 22px 0 0; font-size: 17px; line-height: 1.55; color: var(--ink-2); max-width: 560px; }
  .search-input-row { margin-top: 36px; position: relative; }
  .search-input { width: 100%; height: 68px; padding: 0 160px 0 56px; border: 1px solid var(--line); background: var(--surface); border-radius: 18px; font-size: 16px; font-family: inherit; color: var(--ink); outline: none; transition: border-color .15s, box-shadow .15s, transform .15s; }
  .search-input:focus { border-color: var(--accent); box-shadow: 0 0 0 5px var(--accent-soft), 0 12px 30px rgba(43,111,212,0.10); transform: translateY(-1px); }
  .search-icon { position: absolute; left: 22px; top: 50%; transform: translateY(-50%); color: var(--ink-3); }
  .search-submit {
    position: absolute; right: 8px; top: 8px; bottom: 8px; padding: 0 20px;
    background: linear-gradient(135deg, var(--accent) 0%, #1A4FA0 100%);
    color: #fff; border: 0; border-radius: 12px;
    font-size: 14px; font-weight: 500; cursor: pointer;
    display: inline-flex; align-items: center; gap: 8px;
    transition: transform .12s, box-shadow .12s;
    box-shadow: 0 4px 14px rgba(43,111,212,0.35), inset 0 1px 0 rgba(255,255,255,0.25);
  }
  .search-submit:hover { transform: translateY(-1px); box-shadow: 0 8px 22px rgba(43,111,212,0.45), inset 0 1px 0 rgba(255,255,255,0.25); }
  .chip-row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 18px; }
  .chip { font-size: 12.5px; padding: 8px 13px; border: 0.5px solid var(--line); background: var(--surface); border-radius: 999px; color: var(--ink-2); cursor: pointer; transition: border-color .15s, color .15s, background .15s, transform .15s; font-family: inherit; }
  .chip:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); transform: translateY(-1px) rotate(-1deg); }
  .chip .mono { color: var(--ink-4); margin-left: 6px; font-size: 11px; }

  /* "How it works" — promoted from a collapsible to a full section with cards + trust bar. */
  .how-it-works { margin-top: 56px; padding-top: 40px; border-top: 0.5px solid var(--line); }
  .hiw-header { text-align: center; max-width: 640px; margin: 0 auto 32px; }
  .hiw-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ink-4); display: block; }
  .hiw-headline { font-size: 22px; font-weight: 500; line-height: 1.3; margin: 10px 0 12px; color: var(--ink); }
  .hiw-intro { font-size: 14.5px; line-height: 1.55; color: var(--ink-2); margin: 0; }
  .hiw-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-bottom: 36px; }
  @media (max-width: 760px) { .hiw-steps { grid-template-columns: 1fr; } }
  .hiw-step { position: relative; padding: 18px; border: 0.5px solid var(--line); border-radius: 12px; background: var(--surface); }
  .hiw-num { font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.16em; color: var(--accent); display: block; margin-bottom: 10px; }
  .hiw-title { font-size: 17px; font-weight: 500; color: var(--ink); margin: 0 0 4px; }
  .hiw-subline { font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--ink-3); margin: 0 0 10px; }
  .hiw-detail { font-size: 13.5px; line-height: 1.55; color: var(--ink-2); margin: 0; }
  /* Subtle dashed connector between cards on desktop — hints progression without dominating. */
  .hiw-step:not(:last-child)::after {
    content: ""; position: absolute; top: 50%; right: -12px; width: 8px;
    border-top: 1px dashed var(--line); transform: translateY(-50%);
  }
  @media (max-width: 760px) { .hiw-step:not(:last-child)::after { display: none; } }
  .hiw-trust { text-align: center; padding-top: 4px; }
  .hiw-trust-label { font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ink-4); display: block; margin-bottom: 10px; }
  .hiw-pills { display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; }
  .hiw-pill { font-family: 'JetBrains Mono', monospace; font-size: 11px; padding: 4px 10px; border: 0.5px solid var(--line); border-radius: 999px; background: var(--bg); color: var(--ink-3); }
  /* Edge note: subtle below-trust-bar callout. Smaller than the Cloud-focused step cards
     on purpose — FlutIQ Cloud is the hero; Edge is the privacy/local-frontier secondary. */
  .hiw-edge-note { margin: 24px auto 0; padding: 14px 18px; border: 0.5px dashed var(--line); border-radius: 12px; max-width: 520px; text-align: center; }
  .hiw-edge-label { font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ink-4); display: block; margin-bottom: 8px; }
  .hiw-edge-detail { font-size: 13px; line-height: 1.55; color: var(--ink-3); margin: 0; }

  .agents-grid {
    flex: 1;
    display: grid;
    grid-template-columns: 380px 1fr;
    min-height: calc(100vh - 52px);
  }
  .agents-side {
    border-right: 0.5px solid var(--line);
    background: var(--surface);
    padding: 28px 28px 24px;
    overflow-y: auto;
    display: flex; flex-direction: column;
  }
  .agents-target { font-size: 12px; color: var(--ink-3); font-family: 'JetBrains Mono', monospace; letter-spacing: 0.04em; }
  .agents-addr { margin-top: 6px; font-size: 22px; line-height: 1.18; letter-spacing: -0.02em; font-weight: 500; }
  .progress-track { margin-top: 18px; height: 3px; background: var(--line-2); border-radius: 4px; overflow: hidden; }
  .progress-fill { height: 100%; background: var(--accent); transition: width 600ms cubic-bezier(.4,0,.2,1); }
  .progress-meta { margin-top: 8px; display: flex; justify-content: space-between; font-size: 11.5px; color: var(--ink-3); font-family: 'JetBrains Mono', monospace; }

  .agent-list { margin-top: 22px; display: flex; flex-direction: column; gap: 0; }
  .agent-item { padding: 14px 0; border-bottom: 0.5px solid var(--line-2); }
  .agent-item:last-child { border-bottom: 0; }
  .agent-head { display: flex; align-items: center; gap: 10px; }
  .agent-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ink-4); flex-shrink: 0; }
  .agent-dot.queued { background: var(--amber); opacity: 0.55; }
  .agent-dot.working { background: var(--accent); animation: pulseSoft 1.1s infinite; box-shadow: 0 0 0 4px var(--accent-soft); }
  .agent-dot.done { background: var(--teal); }
  .agent-dot.error { background: var(--coral); }
  .agent-name { font-size: 13.5px; font-weight: 500; flex: 1; }
  .agent-status { font-size: 11px; font-family: 'JetBrains Mono', monospace; color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.06em; }
  .agent-status.queued { color: var(--amber); }
  .agent-status.working { color: var(--accent); }
  .agent-status.done { color: var(--teal); }
  .agent-status.error { color: var(--coral); }
  .agent-finding { margin-top: 6px; font-size: 12.5px; color: var(--ink-2); line-height: 1.5; padding-left: 18px; }
  .agent-finding .mono { color: var(--ink-3); font-size: 11.5px; }

  .agents-foot { margin-top: auto; padding-top: 24px; font-size: 11px; color: var(--ink-4); font-family: 'JetBrains Mono', monospace; line-height: 1.6; }

  .map-pane { position: relative; background: var(--map-bg); overflow: hidden; }
  .map-svg { position: absolute; inset: 0; width: 100%; height: 100%; }
  .map-overlay-tl { position: absolute; top: 20px; left: 20px; padding: 10px 14px; background: rgba(255,255,255,0.92); backdrop-filter: blur(6px); border: 0.5px solid var(--line); border-radius: 8px; font-family: 'JetBrains Mono', monospace; font-size: 11px; color: var(--ink-2); }
  .map-overlay-tr { position: absolute; top: 20px; right: 20px; display: flex; flex-direction: column; gap: 6px; align-items: flex-end; }
  .map-overlay-tr .legend { padding: 8px 12px; background: rgba(255,255,255,0.92); border: 0.5px solid var(--line); border-radius: 8px; font-size: 11px; }
  .map-overlay-bl { position: absolute; bottom: 20px; left: 20px; padding: 10px 14px; background: rgba(255,255,255,0.92); border: 0.5px solid var(--line); border-radius: 8px; font-size: 11px; color: var(--ink-3); font-family: 'JetBrains Mono', monospace; }
  .map-pin { position: absolute; transform: translate(-50%, -100%); animation: pinDrop 360ms cubic-bezier(.34,1.56,.64,1) both; }
  @keyframes pinDrop { 0% { opacity: 0; transform: translate(-50%, -130%) scale(.7); } 100% { opacity: 1; transform: translate(-50%, -100%) scale(1); } }
  .pin-bubble { padding: 7px 11px; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; font-size: 11.5px; white-space: nowrap; box-shadow: 0 8px 24px rgba(22,22,22,0.10); display: inline-flex; align-items: center; gap: 8px; font-weight: 500; }
  .pin-bubble.ring { border-color: var(--accent); }
  .pin-bubble .pin-dot { width: 8px; height: 8px; border-radius: 50%; box-shadow: 0 0 0 3px rgba(255,255,255,0.6); animation: pulseSoft 1.6s ease-in-out infinite; }
  .pin-stem { width: 1.5px; height: 16px; margin: 0 auto; background: currentColor; opacity: 0.45; }
  .pin-anchor { width: 11px; height: 11px; border-radius: 50%; border: 2.5px solid #fff; margin: -2px auto 0; box-shadow: 0 4px 10px rgba(22,22,22,0.18); }

  .map-center { position: absolute; transform: translate(-50%,-50%); z-index: 5; }
  .center-ring { width: 96px; height: 96px; border-radius: 50%; border: 1.5px solid var(--accent); animation: ringPulse 2.4s ease-out infinite; opacity: 0; }
  .center-ring.b { animation-delay: 0.8s; }
  .center-ring.c { animation-delay: 1.6s; }
  @keyframes ringPulse { 0% { transform: scale(.4); opacity: 0; } 20% { opacity: 0.7; } 100% { transform: scale(2.8); opacity: 0; } }
  .center-pin {
    position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);
    width: 28px; height: 36px;
    background: radial-gradient(circle at 30% 25%, #BCDBFF 0%, var(--accent) 55%, #1A4FA0 100%);
    border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
    border: 3px solid #fff;
    box-shadow: 0 6px 18px rgba(43,111,212,0.55);
    animation: bob 2.2s ease-in-out infinite;
  }
  .center-pin::after { content: ""; position: absolute; top: 4px; left: 5px; width: 6px; height: 8px; border-radius: 50%; background: rgba(255,255,255,0.7); }

  .dossier-wrap { padding: 40px 24px 96px; flex: 1; display: flex; justify-content: center; }
  .dossier { width: 100%; max-width: 720px; }
  .dossier-head {
    display: flex; gap: 24px; align-items: center; padding: 28px;
    background: linear-gradient(135deg, var(--coral-soft) 0%, var(--surface) 60%, var(--lemon-soft) 130%);
    border: 1px solid var(--line); border-radius: 22px;
    position: relative; overflow: hidden;
  }
  .dossier-head::before {
    content: ""; position: absolute; right: -40px; top: -40px; width: 220px; height: 220px;
    background: radial-gradient(circle, rgba(238,106,61,0.18) 0%, transparent 60%);
    pointer-events: none;
  }
  .risk-circle { width: 110px; height: 110px; flex-shrink: 0; position: relative; }
  .risk-circle svg { transform: rotate(-90deg); }
  .risk-circle .num { position: absolute; inset: 0; display: grid; place-items: center; font-size: 38px; font-weight: 500; letter-spacing: -0.02em; font-family: 'Instrument Serif', serif; font-style: italic; }
  .risk-meta { flex: 1; min-width: 0; }
  .risk-tag { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px; border-radius: 6px; font-size: 11px; font-family: 'JetBrains Mono', monospace; letter-spacing: 0.04em; text-transform: uppercase; }
  .risk-tag.coral { background: var(--coral-soft); color: var(--coral); }
  .risk-tag.amber { background: var(--amber-soft); color: var(--amber); }
  .risk-tag.teal { background: var(--teal-soft); color: var(--teal); }
  .risk-tag.blue { background: var(--accent-soft); color: var(--accent); }
  .risk-tag.purple { background: var(--purple-soft); color: var(--purple); }
  .risk-tag.neutral { background: rgba(22,22,22,0.05); color: var(--ink-2); }
  .risk-headline { margin: 12px 0 4px; font-size: 22px; line-height: 1.22; letter-spacing: -0.02em; font-weight: 500; }
  .risk-headline em { font-style: italic; font-family: 'Instrument Serif', serif; font-weight: 400; color: var(--coral); }
  .risk-addr { font-size: 13px; color: var(--ink-3); }
  .risk-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }

  .section { margin-top: 14px; background: var(--surface); border: 1px solid var(--line); border-radius: 18px; overflow: hidden; transition: box-shadow .2s, transform .2s; }
  .section:hover { box-shadow: 0 14px 32px rgba(22,22,22,0.05); }
  .sec-head { display: flex; align-items: center; gap: 14px; padding: 18px 22px; cursor: pointer; user-select: none; }
  .sec-icon { width: 38px; height: 38px; border-radius: 12px; display: grid; place-items: center; flex-shrink: 0; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.6), 0 4px 10px rgba(22,22,22,0.05); transition: transform .2s; }
  .sec-head:hover .sec-icon { transform: rotate(-6deg) scale(1.05); }
  .sec-title { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  .sec-title h3 { margin: 0; font-size: 15px; font-weight: 500; letter-spacing: -0.01em; }
  .sec-num { font-family: 'JetBrains Mono', monospace; font-size: 11px; color: var(--ink-4); }
  .sec-toggle { color: var(--ink-3); transition: transform .2s; display: inline-flex; }
  .sec-toggle.open { transform: rotate(180deg); }
  .sec-body { padding: 0 20px 20px; }
  .sec-body p { margin: 0 0 12px; font-size: 14px; line-height: 1.6; color: var(--ink-2); }
  .sec-body p:last-child { margin-bottom: 0; }

  .stat-row { display: flex; justify-content: space-between; align-items: baseline; padding: 12px 0; border-bottom: 0.5px solid var(--line-2); gap: 12px; }
  .stat-row:last-child { border-bottom: 0; }
  .stat-label { font-size: 13px; color: var(--ink-3); }
  .stat-val { font-size: 13.5px; font-family: 'JetBrains Mono', monospace; color: var(--ink); text-align: right; }
  .stat-val .small { color: var(--ink-3); font-size: 11.5px; }

  .prob-block { margin-top: 14px; padding: 16px; background: var(--coral-soft); border-radius: 10px; }
  .prob-head { display: flex; justify-content: space-between; align-items: baseline; }
  .prob-label { font-size: 12.5px; color: var(--ink-2); }
  .prob-pct { font-size: 28px; font-weight: 500; letter-spacing: -0.02em; color: var(--coral); font-family: 'Instrument Serif', serif; font-style: italic; }
  .prob-bar { margin-top: 10px; height: 8px; background: rgba(216,90,48,0.18); border-radius: 4px; overflow: hidden; }
  .prob-bar .fill { height: 100%; background: var(--coral); border-radius: 4px; animation: barFill 1.1s cubic-bezier(.4,0,.2,1) both; }
  .prob-foot { margin-top: 8px; font-size: 11.5px; font-family: 'JetBrains Mono', monospace; color: var(--ink-3); display: flex; justify-content: space-between; }

  .ins-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 14px; }
  .ins-card { padding: 16px; border: 1px solid var(--line); border-radius: 14px; cursor: pointer; transition: transform .2s cubic-bezier(.34,1.56,.64,1), border-color .15s, box-shadow .2s; background: var(--surface); position: relative; }
  .ins-card:hover { transform: translateY(-3px) rotate(-0.4deg); box-shadow: 0 14px 32px rgba(22,22,22,0.08); border-color: var(--accent); }
  .ins-card.recommended { border: 1.5px solid var(--teal); background: linear-gradient(160deg, var(--teal-soft) 0%, #fff 60%); }
  .ins-card .recbadge { position: absolute; top: -10px; right: 12px; background: linear-gradient(135deg, var(--teal) 0%, #0AB084 100%); color: #fff; font-size: 10.5px; font-family: 'JetBrains Mono', monospace; padding: 4px 10px; border-radius: 999px; letter-spacing: 0.04em; box-shadow: 0 4px 10px rgba(15,138,106,0.4); }
  .ins-name { font-size: 13.5px; font-weight: 500; }
  .ins-cost { margin-top: 4px; font-size: 11.5px; color: var(--ink-3); font-family: 'JetBrains Mono', monospace; }
  .ins-desc { margin-top: 8px; font-size: 12.5px; color: var(--ink-2); line-height: 1.5; }
  .ins-why { margin-top: 8px; padding-top: 8px; border-top: 0.5px solid var(--line-2); font-size: 11.5px; color: var(--ink-3); line-height: 1.45; }

  .action-row { display: flex; gap: 14px; padding: 14px 0; border-bottom: 0.5px solid var(--line-2); }
  .action-row:last-child { border-bottom: 0; }
  .action-num { width: 30px; height: 30px; border-radius: 50%;
    background: linear-gradient(135deg, var(--accent-soft) 0%, var(--pink-soft) 100%);
    border: 1px solid var(--line); display: grid; place-items: center;
    font-family: 'Instrument Serif', serif; font-size: 15px; font-style: italic; color: var(--accent);
    flex-shrink: 0; margin-top: 1px; transition: transform .2s; }
  .action-row:hover .action-num { transform: scale(1.1) rotate(-6deg); }
  .action-body { flex: 1; min-width: 0; }
  .action-title { font-size: 14px; font-weight: 500; }
  .action-title .cost { font-family: 'JetBrains Mono', monospace; color: var(--ink-3); font-weight: 400; font-size: 12px; margin-left: 8px; }
  .action-desc { margin-top: 4px; font-size: 13px; color: var(--ink-2); line-height: 1.5; }
  .action-contact { margin-top: 6px; font-size: 12px; font-family: 'JetBrains Mono', monospace; color: var(--accent); }

  .news-row { display: grid; grid-template-columns: 80px 1fr 90px; gap: 16px; padding: 12px 0; border-bottom: 0.5px solid var(--line-2); align-items: baseline; }
  .news-row:last-child { border-bottom: 0; }
  .news-date { font-size: 11.5px; font-family: 'JetBrains Mono', monospace; color: var(--ink-4); }
  .news-title { font-size: 13.5px; line-height: 1.4; color: var(--ink); }
  .news-source { font-size: 11.5px; color: var(--ink-3); text-align: right; }

  .method-foot { margin-top: 32px; padding: 20px 24px; border: 0.5px dashed var(--line); border-radius: 14px; font-size: 11.5px; color: var(--ink-3); line-height: 1.7; font-family: 'JetBrains Mono', monospace; }
  .method-foot strong { color: var(--ink-2); font-weight: 500; }
  .method-foot .small { font-size: 11px; }

  .dossier-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; }
  .dossier-toolbar .back { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; color: var(--ink-3); cursor: pointer; padding: 6px 10px; border-radius: 6px; }
  .dossier-toolbar .back:hover { color: var(--ink); background: var(--surface); }
  .dossier-toolbar .meta { font-family: 'JetBrains Mono', monospace; font-size: 11px; color: var(--ink-4); letter-spacing: 0.04em; text-transform: uppercase; }

  body.dark {
    --bg: #131416;
    --surface: #1A1B1E;
    --ink: #F2F2F0;
    --ink-2: #C9C9C7;
    --ink-3: #8A8A88;
    --ink-4: #5A5A58;
    --line: rgba(255,255,255,0.10);
    --line-2: rgba(255,255,255,0.05);
    --accent: #6FA8DD;
    --accent-soft: rgba(111,168,221,0.14);
    --teal: #4FB89A;
    --teal-soft: rgba(79,184,154,0.14);
    --amber: #E5A946;
    --amber-soft: rgba(229,169,70,0.14);
    --coral: #F08363;
    --coral-soft: rgba(240,131,99,0.14);
    --purple: #9A8FE0;
    --purple-soft: rgba(154,143,224,0.14);
    --map-bg: #1F2123;
    --map-water: #2A3946;
    --map-park: #233027;
    --map-road: #2A2B2D;
    --map-stroke: rgba(255,255,255,0.14);
  }
  body.dark .wordmark .glyph { background: var(--ink); color: var(--bg); }
  body.dark .search-submit { background: var(--accent); color: var(--bg); }
  body.dark .map-overlay-tl, body.dark .map-overlay-tr .legend, body.dark .map-overlay-bl, body.dark .pin-bubble { background: rgba(26,27,30,0.92); }
</style>
</head>
<body>
<div id="app"></div>

<script src="https://unpkg.com/react@18.3.1/umd/react.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>

<script type="text/babel">
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// Inference variant — populated by FastAPI's index handler before send.
// Values: "openrouter" (cloud) | "ollama" (edge / on-device) |
//         "__INFERENCE_BACKEND__" (raw file served without substitution).
// Anything other than "ollama" falls through to Cloud branding, so the
// blue Cloud look-and-feel is the safe default.
const VARIANT = document.documentElement.dataset.variant || "openrouter";
const IS_EDGE = VARIANT === "ollama";
const BRAND_NAME = IS_EDGE ? "FlutIQ Edge" : "FlutIQ Cloud";
const BRAND_PILL = IS_EDGE ? "gemma-4 · Edge (Ollama, on-device)" : "gemma-4 · Cloud (OpenRouter)";
document.title = `${BRAND_NAME} — flood risk advisor`;

// Backend URL. Default to same-origin so that whichever uvicorn served
// the HTML (port 8000 cloud, port 8001 edge, HF Space, etc.) is also the
// API target. Override with ?api=... or window.FLUTIQ_API only when the
// page and backend are on different origins (e.g. python -m http.server).
const API_URL = (() => {
  const fromQuery = new URLSearchParams(window.location.search).get("api");
  if (fromQuery) return fromQuery;
  if (window.FLUTIQ_API) return window.FLUTIQ_API;
  return "";
})();

// ── SSE hook ───────────────────────────────────────────────────────────────
// Streams /api/assess. Surfaces per-agent status, geocode, dossier, errors.
// Languages we support for the dossier. Mirrored from
// backend/app/data/languages.py — keep in sync.
const LANGUAGES = [
  { code: "en", label: "English",        native: "English" },
  { code: "es", label: "Spanish",        native: "Español" },
  { code: "zh", label: "Mandarin",       native: "中文" },
  { code: "vi", label: "Vietnamese",     native: "Tiếng Việt" },
  { code: "ht", label: "Haitian Creole", native: "Kreyòl ayisyen" },
  { code: "ar", label: "Arabic",         native: "العربية" },
  { code: "tl", label: "Tagalog",        native: "Tagalog" },
];

// UI chrome translations — labels, section titles, headlines.
// The model-generated prose (verdict, NRI interpretations, vision findings,
// mitigation steps) is translated server-side; this dict covers ONLY the
// static frontend strings that never round-trip through Gemma. Non-English
// translations should be reviewed by native speakers before production.
const UI_STRINGS = {
  en: {
    risk_low:                  "Low risk",
    risk_medium:               "Medium risk",
    risk_high:                 "High risk",
    headline_high_femasafe_pre: "High urban flood risk —",
    headline_high_femasafe_em:  "despite FEMA saying \"minimal\"",
    headline_high_pre:          "High flood risk —",
    headline_high_em:           "FEMA confirms a hazard zone",
    headline_med_femasafe_pre:  "Moderate risk that FEMA misses —",
    headline_med_femasafe_em:   "urban flood signals are present",
    headline_med_pre:           "Moderate flood risk",
    headline_low_femasafe_pre:  "Low risk on this block —",
    headline_low_femasafe_em:   "FEMA and local signals agree",
    headline_low_pre:           "Low risk",
    section_before:    "Before you sign — what to verify this week",
    section_actions:   "What to do once you live there",
    section_insurance: "Insurance options, in plain English",
    section_images:    "What we saw at the property",
    section_gap:       "Why FEMA's flood map isn't the whole story",
    section_regional:  "Wider neighborhood — beyond just flooding",
    section_signals:   "The raw signals we looked at",
    section_news:      "Recent local flood news",
    bottom_line_label: "Bottom line",
    bottom_line_sub:   "what a flood-savvy friend would tell you",
    synthesized_from:  "Synthesized from",
    commercial_label:  "Commercial property",
    commercial_sub:    "homeowner advice not shown",
    commercial_body:   "FlutIQ is built for residential decisions — buying, renting, or living in a home. This address resolved to a commercial property, so the homeowner action plan, insurance recommendations, and before-you-sign checklist are hidden. The flood risk findings, multi-hazard profile, and visual analysis below still apply to the building. For coverage decisions, talk to a commercial insurance broker.",
  },
  es: {
    risk_low:                  "Riesgo bajo",
    risk_medium:               "Riesgo moderado",
    risk_high:                 "Riesgo alto",
    headline_high_femasafe_pre: "Alto riesgo de inundación urbana —",
    headline_high_femasafe_em:  "a pesar de que FEMA dice \"mínimo\"",
    headline_high_pre:          "Alto riesgo de inundación —",
    headline_high_em:           "FEMA confirma una zona de peligro",
    headline_med_femasafe_pre:  "Riesgo moderado que FEMA no detecta —",
    headline_med_femasafe_em:   "hay señales de inundación urbana",
    headline_med_pre:           "Riesgo moderado de inundación",
    headline_low_femasafe_pre:  "Riesgo bajo en esta cuadra —",
    headline_low_femasafe_em:   "FEMA y las señales locales coinciden",
    headline_low_pre:           "Riesgo bajo",
    section_before:    "Antes de firmar — qué verificar esta semana",
    section_actions:   "Qué hacer una vez que vivas allí",
    section_insurance: "Opciones de seguro, en lenguaje claro",
    section_images:    "Lo que vimos en la propiedad",
    section_gap:       "Por qué el mapa de FEMA no cuenta toda la historia",
    section_regional:  "Vecindario más amplio — más allá de las inundaciones",
    section_signals:   "Las señales que examinamos",
    section_news:      "Noticias locales recientes sobre inundaciones",
    bottom_line_label: "Lo esencial",
    bottom_line_sub:   "lo que te diría un amigo experto en inundaciones",
    synthesized_from:  "Sintetizado de",
    commercial_label:  "Propiedad comercial",
    commercial_sub:    "no se muestran consejos para propietarios",
    commercial_body:   "FlutIQ está hecho para decisiones residenciales — comprar, alquilar o vivir en una casa. Esta dirección se identificó como una propiedad comercial, por lo que el plan de acción del propietario, las recomendaciones de seguro y la lista de verificación previa a la firma están ocultos. Los hallazgos sobre el riesgo de inundación, el perfil multi-peligro y el análisis visual a continuación siguen siendo aplicables al edificio. Para decisiones de cobertura, hable con un corredor de seguros comerciales.",
  },
  zh: {
    risk_low:                  "低风险",
    risk_medium:               "中等风险",
    risk_high:                 "高风险",
    headline_high_femasafe_pre: "城市洪水风险高 —",
    headline_high_femasafe_em:  "尽管 FEMA 评定为\"极低\"",
    headline_high_pre:          "洪水风险高 —",
    headline_high_em:           "FEMA 确认为危险区域",
    headline_med_femasafe_pre:  "FEMA 未识别的中等风险 —",
    headline_med_femasafe_em:   "存在城市洪水信号",
    headline_med_pre:           "中等洪水风险",
    headline_low_femasafe_pre:  "本街区风险较低 —",
    headline_low_femasafe_em:   "FEMA 与本地信号一致",
    headline_low_pre:           "风险较低",
    section_before:    "签约前 — 本周需要核实的事项",
    section_actions:   "入住后应该做的事",
    section_insurance: "保险选项,简明易懂",
    section_images:    "我们在物业看到的情况",
    section_gap:       "为什么 FEMA 洪水地图并非全貌",
    section_regional:  "更大范围的邻里 — 不止于洪水",
    section_signals:   "我们查看的原始信号",
    section_news:      "近期本地洪水新闻",
    bottom_line_label: "核心结论",
    bottom_line_sub:   "懂洪水的朋友会这样告诉你",
    synthesized_from:  "综合自",
    commercial_label:  "商业地产",
    commercial_sub:    "不显示业主建议",
    commercial_body:   "FlutIQ 专为居住决策(购房、租房或居住)而设计。此地址识别为商业地产,因此业主行动计划、保险建议和签约前核查清单已被隐藏。下方的洪水风险分析、多灾害概况和视觉分析仍适用于该建筑。如需保险方案,请咨询商业保险经纪人。",
  },
  vi: {
    risk_low:                  "Rủi ro thấp",
    risk_medium:               "Rủi ro trung bình",
    risk_high:                 "Rủi ro cao",
    headline_high_femasafe_pre: "Rủi ro lũ đô thị cao —",
    headline_high_femasafe_em:  "mặc dù FEMA xếp loại \"tối thiểu\"",
    headline_high_pre:          "Rủi ro lũ cao —",
    headline_high_em:           "FEMA xác nhận khu vực nguy hiểm",
    headline_med_femasafe_pre:  "Rủi ro trung bình mà FEMA bỏ sót —",
    headline_med_femasafe_em:   "có dấu hiệu lũ đô thị",
    headline_med_pre:           "Rủi ro lũ trung bình",
    headline_low_femasafe_pre:  "Rủi ro thấp ở khu này —",
    headline_low_femasafe_em:   "FEMA và tín hiệu địa phương đồng nhất",
    headline_low_pre:           "Rủi ro thấp",
    section_before:    "Trước khi ký — cần kiểm tra tuần này",
    section_actions:   "Cần làm gì khi đã ở đó",
    section_insurance: "Các lựa chọn bảo hiểm, giải thích dễ hiểu",
    section_images:    "Những gì chúng tôi thấy tại địa điểm",
    section_gap:       "Vì sao bản đồ lũ của FEMA không kể hết câu chuyện",
    section_regional:  "Khu vực rộng hơn — không chỉ là lũ lụt",
    section_signals:   "Các tín hiệu nguyên gốc chúng tôi đã xem",
    section_news:      "Tin tức lũ lụt địa phương gần đây",
    bottom_line_label: "Tóm lại",
    bottom_line_sub:   "điều một người bạn am hiểu về lũ sẽ nói với bạn",
    synthesized_from:  "Tổng hợp từ",
    commercial_label:  "Bất động sản thương mại",
    commercial_sub:    "không hiển thị tư vấn cho chủ nhà",
    commercial_body:   "FlutIQ được xây dựng cho các quyết định nhà ở — mua, thuê, hoặc sinh sống. Địa chỉ này được nhận diện là bất động sản thương mại, vì vậy kế hoạch hành động chủ nhà, đề xuất bảo hiểm, và danh sách kiểm tra trước khi ký đã bị ẩn. Các phát hiện về rủi ro lũ, hồ sơ đa hiểm họa, và phân tích hình ảnh bên dưới vẫn áp dụng cho tòa nhà. Để quyết định về bảo hiểm, hãy liên hệ với một môi giới bảo hiểm thương mại.",
  },
  ht: {
    risk_low:                  "Risk fèb",
    risk_medium:               "Risk modere",
    risk_high:                 "Risk wo",
    headline_high_femasafe_pre: "Gwo risk inondasyon iben —",
    headline_high_femasafe_em:  "menm si FEMA di \"minim\"",
    headline_high_pre:          "Gwo risk inondasyon —",
    headline_high_em:           "FEMA konfime zòn danje",
    headline_med_femasafe_pre:  "Risk modere ke FEMA pa wè —",
    headline_med_femasafe_em:   "gen siyal inondasyon iben",
    headline_med_pre:           "Risk inondasyon modere",
    headline_low_femasafe_pre:  "Risk fèb nan blok sa a —",
    headline_low_femasafe_em:   "FEMA ak siyal lokal yo dakò",
    headline_low_pre:           "Risk fèb",
    section_before:    "Anvan ou siyen — sa pou verifye semèn sa a",
    section_actions:   "Sa pou fè lè ou viv la",
    section_insurance: "Opsyon asirans, an lang senp",
    section_images:    "Sa nou te wè nan pwopriyete a",
    section_gap:       "Poukisa kat inondasyon FEMA pa tout istwa a",
    section_regional:  "Pi laj katye a — pi lwen pase inondasyon",
    section_signals:   "Siyal brit nou te gade",
    section_news:      "Nouvèl inondasyon lokal resan",
    bottom_line_label: "Sa ki esansyèl",
    bottom_line_sub:   "sa yon zanmi ki konnen inondasyon ta di ou",
    synthesized_from:  "Konbine soti nan",
    commercial_label:  "Pwopriyete komèsyal",
    commercial_sub:    "konsèy pou pwopriyetè kay pa parèt",
    commercial_body:   "FlutIQ fèt pou desizyon rezidansyèl — achte, lwe, oswa viv nan yon kay. Adrès sa a se yon pwopriyete komèsyal, kidonk plan aksyon pwopriyetè a, rekòmandasyon asirans yo, ak lis verifikasyon anvan-siyen yo kache. Konstata sou risk inondasyon, pwofil milti-danje, ak analiz vizyèl anba a toujou aplike pou bilding la. Pou desizyon kouvèti, pale ak yon koutye asirans komèsyal.",
  },
  ar: {
    risk_low:                  "مخاطر منخفضة",
    risk_medium:               "مخاطر متوسطة",
    risk_high:                 "مخاطر مرتفعة",
    headline_high_femasafe_pre: "مخاطر فيضان حضري مرتفعة —",
    headline_high_femasafe_em:  "رغم أن FEMA تصنفها \"دنيا\"",
    headline_high_pre:          "مخاطر فيضان مرتفعة —",
    headline_high_em:           "FEMA تؤكد أنها منطقة خطر",
    headline_med_femasafe_pre:  "مخاطر متوسطة لا تكتشفها FEMA —",
    headline_med_femasafe_em:   "هناك مؤشرات فيضان حضري",
    headline_med_pre:           "مخاطر فيضان متوسطة",
    headline_low_femasafe_pre:  "مخاطر منخفضة في هذا الحي —",
    headline_low_femasafe_em:   "FEMA والمؤشرات المحلية متفقة",
    headline_low_pre:           "مخاطر منخفضة",
    section_before:    "قبل التوقيع — ما يجب التحقق منه هذا الأسبوع",
    section_actions:   "ما ينبغي فعله بعد السكن",
    section_insurance: "خيارات التأمين، بلغة مبسطة",
    section_images:    "ما رأيناه في العقار",
    section_gap:       "لماذا لا تروي خريطة FEMA القصة كاملة",
    section_regional:  "المنطقة الأوسع — أبعد من الفيضانات وحدها",
    section_signals:   "المؤشرات الأولية التي فحصناها",
    section_news:      "أخبار الفيضانات المحلية الأخيرة",
    bottom_line_label: "الخلاصة",
    bottom_line_sub:   "ما سيخبرك به صديق خبير بالفيضانات",
    synthesized_from:  "مُجمَّع من",
    commercial_label:  "عقار تجاري",
    commercial_sub:    "لا تظهر نصائح المالكين",
    commercial_body:   "تم تصميم FlutIQ للقرارات السكنية — الشراء أو الاستئجار أو السكن في منزل. تم التعرف على هذا العنوان كعقار تجاري، لذلك يتم إخفاء خطة العمل للمالك وتوصيات التأمين وقائمة التحقق قبل التوقيع. تبقى نتائج مخاطر الفيضانات وملف المخاطر المتعددة والتحليل البصري أدناه قابلة للتطبيق على المبنى. لقرارات التأمين، تحدث مع وسيط تأمين تجاري.",
  },
  tl: {
    risk_low:                  "Mababang panganib",
    risk_medium:               "Katamtamang panganib",
    risk_high:                 "Mataas na panganib",
    headline_high_femasafe_pre: "Mataas na panganib sa baha sa lungsod —",
    headline_high_femasafe_em:  "kahit sinabi ng FEMA na \"minimal\"",
    headline_high_pre:          "Mataas na panganib sa baha —",
    headline_high_em:           "Kinumpirma ng FEMA bilang panganib na sona",
    headline_med_femasafe_pre:  "Katamtamang panganib na hindi nakita ng FEMA —",
    headline_med_femasafe_em:   "may mga senyales ng baha sa lungsod",
    headline_med_pre:           "Katamtamang panganib sa baha",
    headline_low_femasafe_pre:  "Mababang panganib sa block na ito —",
    headline_low_femasafe_em:   "FEMA at lokal na senyales ay magkasundo",
    headline_low_pre:           "Mababang panganib",
    section_before:    "Bago pumirma — ano ang sisiyasatin ngayong linggo",
    section_actions:   "Ano ang gagawin pagdating mo dito",
    section_insurance: "Mga pagpipiliang insurance, sa simpleng salita",
    section_images:    "Ang nakita namin sa ari-arian",
    section_gap:       "Bakit hindi kabuuan ng kuwento ang flood map ng FEMA",
    section_regional:  "Mas malawak na kapitbahayan — hindi lang baha",
    section_signals:   "Ang mga raw signal na sinuri namin",
    section_news:      "Mga kamakailang lokal na balita sa baha",
    bottom_line_label: "Ang pangunahing punto",
    bottom_line_sub:   "ang sasabihin sa iyo ng kaibigang sanay sa baha",
    synthesized_from:  "Pinagsama-sama mula sa",
    commercial_label:  "Komersyal na ari-arian",
    commercial_sub:    "hindi ipinapakita ang payo para sa homeowner",
    commercial_body:   "Ang FlutIQ ay ginawa para sa mga desisyong tirahan — pagbili, pag-arkila, o pagtira sa isang bahay. Ang address na ito ay natukoy bilang komersyal na ari-arian, kaya nakatago ang plano ng aksyon para sa homeowner, mga rekomendasyon sa insurance, at checklist bago pumirma. Ang mga natuklasang panganib sa baha, multi-hazard profile, at visual analysis sa ibaba ay nananatiling angkop sa gusali. Para sa mga desisyon sa coverage, kumonsulta sa isang komersyal na insurance broker.",
  },
};

// Lookup helper: returns the translation, falling back to English, then to
// the key itself if even English is missing (shouldn't happen, but safe).
const tr = (lang, key) => {
  const dict = UI_STRINGS[lang] || UI_STRINGS.en;
  return dict[key] ?? UI_STRINGS.en[key] ?? key;
};

const useFloodAssessment = () => {
  const [agentState, setAgentState] = useState({});  // {fema: {status, summary}, ...}
  const [geocode, setGeocode] = useState(null);
  const [dossier, setDossier] = useState(null);
  const [error, setError] = useState(null);
  const [running, setRunning] = useState(false);
  const abortRef = useRef(null);

  const reset = useCallback(() => {
    if (abortRef.current) abortRef.current.abort();
    abortRef.current = null;
    setAgentState({});
    setGeocode(null);
    setDossier(null);
    setError(null);
    setRunning(false);
  }, []);

  const start = useCallback(async (address, language = "en") => {
    reset();
    setRunning(true);
    const controller = new AbortController();
    abortRef.current = controller;

    try {
      const resp = await fetch(`${API_URL}/api/assess`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ address, language }),
        signal: controller.signal,
      });
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      if (!resp.body) throw new Error("no response body");

      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let buffer = "";

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });

        // SSE blocks are separated by \n\n
        let sep;
        while ((sep = buffer.indexOf("\n\n")) !== -1) {
          const block = buffer.slice(0, sep);
          buffer = buffer.slice(sep + 2);
          if (!block.trim()) continue;

          const lines = block.split("\n");
          let event = "message";
          let data = "";
          for (const line of lines) {
            if (line.startsWith("event:")) event = line.slice(6).trim();
            else if (line.startsWith("data:")) data += line.slice(5).trim();
          }
          let parsed;
          try { parsed = JSON.parse(data); } catch { continue; }

          if (event === "geocoded") {
            setGeocode(parsed);
          } else if (event === "agent_update") {
            setAgentState(prev => ({
              ...prev,
              [parsed.agent]: { status: parsed.status, summary: parsed.summary },
            }));
          } else if (event === "complete") {
            setDossier(parsed.dossier);
          } else if (event === "error") {
            setError(parsed.message || "Backend error");
          }
        }
      }
    } catch (e) {
      if (e.name !== "AbortError") setError(e.message || String(e));
    } finally {
      setRunning(false);
      abortRef.current = null;
    }
  }, [reset]);

  return { start, reset, agentState, geocode, dossier, error, running };
};

// ── ICONS ──────────────────────────────────────────────────────────────────
const Icon = ({ name, size = 16, color = "currentColor" }) => {
  const s = size;
  const stroke = { stroke: color, strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };
  switch (name) {
    case "search":      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>);
    case "arrow-right": return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M5 12h14M13 6l6 6-6 6"/></svg>);
    case "arrow-left":  return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>);
    case "chevron-down":return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="m6 9 6 6 6-6"/></svg>);
    case "warn":        return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 4 2 20h20L12 4z"/><path d="M12 10v5M12 18v.01"/></svg>);
    case "drop":        return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 3s7 7 7 12a7 7 0 1 1-14 0c0-5 7-12 7-12z"/></svg>);
    case "dollar":      return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 3v18M16 7H10a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6H8"/></svg>);
    case "plus":        return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 5v14M5 12h14"/></svg>);
    case "news":        return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M7 9h10M7 13h10M7 17h6"/></svg>);
    case "sun":         return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/></svg>);
    case "moon":        return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M21 13a8 8 0 1 1-9.9-9.9 7 7 0 0 0 9.9 9.9z"/></svg>);
    case "pin":         return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M12 22s7-7 7-13a7 7 0 1 0-14 0c0 6 7 13 7 13z"/><circle cx="12" cy="9" r="2.5"/></svg>);
    case "x":           return (<svg width={s} height={s} viewBox="0 0 24 24" {...stroke}><path d="M6 6l12 12M18 6 6 18"/></svg>);
    default: return null;
  }
};

// ── DATA FIXTURES ──────────────────────────────────────────────────────────
const EXAMPLES = [
  { label: "4521 S Drexel Blvd, Chicago", code: "60653" },
  { label: "Greenwich Village, New York NY", code: "10011" },
  { label: "Echo Park, Los Angeles CA",   code: "90026" },
  { label: "Houston Heights, TX",         code: "77008" },
];

const AGENTS = [
  { id: "fema",    name: "FEMA expert",
    finding: "Zone X (minimal) — but map panel is from 2019. Address sits 600ft outside the AE boundary along Lake Michigan.",
    pin: { x: 28, y: 58, label: "Zone X", tone: "amber" }, delay: 1100 },
  { id: "local",   name: "311 analyst",
    finding: "23 \"water in basement\" reports within 500m since 2021. Combined sewer service area; TARP McCook reservoir nearby but at capacity in 2023 storm.",
    pin: { x: 46, y: 48, label: "23 reports", tone: "coral" }, delay: 1200 },
  { id: "weather", name: "Weather analyst",
    finding: "Nearest USGS gauge (North Branch Chicago River) at 1.4× normal discharge. NOAA HMI 7-day rainfall outlook: above normal.",
    pin: { x: 18, y: 32, label: "Gauge 1.4×", tone: "blue" }, delay: 900 },
  { id: "news",    name: "News scout",
    finding: "5 GDELT articles in last 6 mo. Sept 2025 storm dumped 4.7\" in 90min, MWRD reversed flow into Lake. Focus on South Side basements.",
    pin: { x: 72, y: 38, label: "Sep '25 storm", tone: "purple" }, delay: 1400 },
  { id: "archive", name: "Archivist",
    finding: "Cook County: 11 NOAA flood events in 10yr, 4 FEMA disaster declarations. 2008, 2013, 2020, 2023 caused widespread basement flooding.",
    pin: { x: 62, y: 70, label: "11 events / 10y", tone: "amber" }, delay: 1100 },
  { id: "regional", name: "Regional risk analyst",
    finding: "FEMA NRI county-level multi-hazard profile — wildfire, hurricane, tornado, earthquake, etc. — for the wider neighborhood.",
    pin: null, delay: 1300 },
  { id: "satellite", name: "Satellite surveyor",
    finding: "Multimodal: bird's-eye Mapbox imagery → Gemma 4 vision → impervious-surface and catchment analysis.",
    pin: null, delay: 1700 },
  { id: "streetview", name: "Streetview surveyor",
    finding: "Multimodal: feeding Google Street View imagery to Gemma 4 vision to spot ground-floor flood-risk indicators.",
    pin: null, delay: 1800 },
  { id: "risk",    name: "Risk analyst",
    finding: "Synthesizing… Score 74/100. AEP ≈ 5.1%, 30-yr cumulative probability of basement flood ≈ 79%. FEMA gap material.",
    pin: null, delay: 1600 },
  { id: "advisor", name: "Advisor",
    finding: "Drafting recommendations: prioritize sewer-backup rider + backwater valve before NFIP. Action plan sequenced by impact-to-cost.",
    pin: null, delay: 1100 },
];

const TONE_HEX = {
  blue:   "var(--accent)",
  teal:   "var(--teal)",
  amber:  "var(--amber)",
  coral:  "var(--coral)",
  purple: "var(--purple)",
};

const DOSSIER = {
  score: 74,
  level: "high",
  headline_pre: "High urban flood risk —",
  headline_em: "despite FEMA saying \"minimal\"",
  address: "4521 S Drexel Blvd, Chicago IL 60653",
  tags: [
    { label: "Combined sewer", tone: "blue" },
    { label: "FEMA Zone X",    tone: "amber" },
    { label: "TARP-served",    tone: "neutral" },
    { label: "Cook County",    tone: "neutral" },
  ],
  fema_gap: {
    body: [
      "FEMA's National Flood Hazard Layer puts this address in Zone X — what the agency labels \"minimal\" risk. That assessment measures one specific thing: a riverine or coastal 100-year flood. It does not measure sewer backup, the dominant flood mode for Chicago's combined-sewer service area.",
      "Within 500m of this address, the city has logged 23 water-in-basement 311 reports since 2021. The block also sits below the McCook TARP overflow elevation. When the system is overwhelmed (≈ 1.5 in/hr sustained), MWRD has historically reversed flow into Lake Michigan and basements back up regardless of FEMA zone.",
    ],
    aep_pct: 5.1,
    cum_pct: 79,
    cum_label: "30-year mortgage",
  },
  infra: [
    { label: "Sewer type",                  val: "Combined", small: "MWRD service area" },
    { label: "Overwhelm threshold",         val: "1.5 in/hr", small: "sustained" },
    { label: "Impervious surface (1km²)",   val: "62%" },
    { label: "TARP coverage",               val: "Yes", small: "McCook reservoir" },
    { label: "311 floods, 500m / 5yr",      val: "23" },
    { label: "Nearest USGS gauge",          val: "05536123", small: "N. Branch · 1.4× normal" },
    { label: "Ground elevation",            val: "180 m", small: "USGS 3DEP" },
    { label: "Distance to Lake Michigan",   val: "0.9 km" },
  ],
  insurance: [
    { type:"sewer_rider", name:"Sewer backup rider", cost:"~$55 / yr",
      desc:"Add-on to your homeowners policy. Covers water that backs up through floor drains, toilets, sinks during a sewer overwhelm event.",
      why:"Cheapest, most targeted protection for this exact failure mode in your area.",
      recommended: true },
    { type:"nfip", name:"NFIP Preferred Risk", cost:"$485 / yr",
      desc:"Building $250K · contents $100K. Federal program. Not legally required in Zone X, but eligible at preferred-risk pricing.",
      why:"Covers structural damage from surface flooding; complements the rider.",
      recommended: false },
    { type:"private", name:"Private excess flood", cost:"$320 / yr",
      desc:"Excess coverage above the NFIP $250K building cap. Useful if your structure value exceeds federal limits.",
      why:"Skip unless your home value is well above NFIP caps.",
      recommended: false },
    { type:"parametric", name:"Parametric (FloodFlash-style)", cost:"$240 / yr",
      desc:"Sensor-triggered. If flood depth exceeds 6 in at the property, payout is automatic within 48 hours — no claim adjuster.",
      why:"Speeds recovery, but trigger depths must be tuned carefully.",
      recommended: false },
  ],
  actions: [
    { title:"Disconnect downspouts", cost:"Free · DIY",
      desc:"Redirect roof runoff onto your lawn instead of into the sewer. In a combined-sewer block, a single house can divert ~1,400 gallons per inch of rain.",
      contact:"chicago.gov/downspout" },
    { title:"Install a backwater valve", cost:"$1,200 – $2,500",
      desc:"A one-way valve on your sewer lateral that closes when the main line surges. The single highest-impact upgrade for basement-backup risk.",
      contact:"MWRD Cost-Share — (312) 751-3000" },
    { title:"Add a sewer-backup rider", cost:"~$55 / yr",
      desc:"Call your homeowners insurer and ask for a sewer/water-backup endorsement. Confirm the limit is at least $25K.",
      contact:null },
    { title:"Buy NFIP Preferred Risk policy", cost:"~$485 / yr",
      desc:"Federal flood insurance. 30-day waiting period, so don't wait for a forecast. You're eligible at preferred-risk rates because you're outside the SFHA.",
      contact:"floodsmart.gov" },
    { title:"Sewer-camera inspection", cost:"$150 – $300",
      desc:"Pre-existing breaks or root intrusion in your lateral roughly double your basement-backup exposure. Worth a one-time check.",
      contact:null },
    { title:"Apply to MWRD Rain-Ready cost-share", cost:"Up to $5,000 reimbursed",
      desc:"Cook County reimburses qualifying mitigation work — valves, dry wells, permeable pavers — through MWRD's residential program.",
      contact:"mwrd.org/rainready" },
  ],
  news: [
    { date:"Apr 14, 2026", title:"South Side residents pack town hall over basement-flood payouts", source:"Block Club" },
    { date:"Mar 02, 2026", title:"MWRD opens 2026 cost-share window for backwater valves", source:"Sun-Times" },
    { date:"Sep 18, 2025", title:"Storm dumps 4.7\" in 90 minutes; CTA Red Line tunnels close", source:"Chicago Tribune" },
    { date:"Aug 22, 2025", title:"Why FEMA's flood maps miss most Chicago flooding, explained", source:"WBEZ" },
    { date:"Jul 09, 2025", title:"Hyde Park homeowners sue over repeat sewer backups", source:"Crain's Chicago" },
  ],
};

// ── REAL MAP (Leaflet) ─────────────────────────────────────────────────────
// Renders an actual basemap centered on the geocoded lat/lon. Falls back to
// the synthetic illustrative grid below when no geocode is available yet
// (i.e. while the request is in-flight).
const RealMap = ({ geocode, dark = false }) => {
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const markerRef = useRef(null);
  const circleRef = useRef(null);

  // Initialize the Leaflet map once.
  useEffect(() => {
    if (!containerRef.current || mapRef.current) return;
    if (typeof L === "undefined") return;  // Leaflet not yet loaded
    const map = L.map(containerRef.current, {
      zoomControl: false,
      attributionControl: true,
      scrollWheelZoom: false,
      dragging: true,
    }).setView([39.5, -98.35], 4);  // continental US default
    L.tileLayer(
      dark
        ? "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png"
        : "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png",
      {
        maxZoom: 19,
        attribution: '© <a href="https://openstreetmap.org/copyright">OSM</a> · © <a href="https://carto.com/attributions">CARTO</a>',
      }
    ).addTo(map);
    L.control.zoom({ position: "bottomright" }).addTo(map);
    mapRef.current = map;
    return () => {
      map.remove();
      mapRef.current = null;
      markerRef.current = null;
      circleRef.current = null;
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Recenter whenever geocode arrives or changes.
  useEffect(() => {
    const map = mapRef.current;
    if (!map || !geocode) return;
    const { lat, lon } = geocode;
    map.setView([lat, lon], 15, { animate: true });

    if (markerRef.current) markerRef.current.remove();
    if (circleRef.current) circleRef.current.remove();

    const dropletIcon = L.divIcon({
      className: "",
      html: '<div style="width:18px;height:18px;border-radius:50% 50% 50% 0;transform:rotate(-45deg);background:#2B6FD4;border:3px solid #fff;box-shadow:0 4px 14px rgba(43,111,212,0.45);"></div>',
      iconSize: [18, 18],
      iconAnchor: [9, 18],
    });
    markerRef.current = L.marker([lat, lon], { icon: dropletIcon }).addTo(map);
    circleRef.current = L.circle([lat, lon], {
      radius: 500,  // matches our 311 / weather search radii
      color: "#2B6FD4",
      weight: 1.5,
      opacity: 0.6,
      fillColor: "#2B6FD4",
      fillOpacity: 0.06,
    }).addTo(map);
  }, [geocode]);

  return <div ref={containerRef} style={{ position: "absolute", inset: 0, background: "var(--map-bg)" }} />;
};

// ── MAP (synthetic fallback used pre-geocode and as design reference) ──────
const NeighborhoodMap = ({ dark = false }) => {
  const blocks = [];
  for (let i = 0; i < 8; i++) {
    blocks.push(<line key={"v"+i} x1={120 + i*100} y1={0} x2={120 + i*100} y2={720} stroke="var(--map-road)" strokeWidth={i%3===0 ? 18 : 10} />);
  }
  for (let j = 0; j < 6; j++) {
    blocks.push(<line key={"h"+j} x1={0} y1={90 + j*110} x2={1000} y2={90 + j*110} stroke="var(--map-road)" strokeWidth={j%3===0 ? 18 : 10} />);
  }

  const buildings = [];
  let seed = 7;
  const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
  for (let bx = 0; bx < 9; bx++) {
    for (let by = 0; by < 7; by++) {
      const x0 = bx*100 + 18, y0 = by*110 + 18;
      const cells = 2 + Math.floor(rnd()*3);
      for (let c = 0; c < cells; c++) {
        const w = 14 + rnd()*20;
        const h = 14 + rnd()*22;
        const x = x0 + rnd()*(82-w);
        const y = y0 + rnd()*(92-h);
        buildings.push(<rect key={`b-${bx}-${by}-${c}`} x={x} y={y} width={w} height={h}
          fill={dark ? "rgba(255,255,255,0.04)" : "rgba(22,22,22,0.05)"}
          stroke="var(--map-stroke)" strokeWidth="0.5" />);
      }
    }
  }

  return (
    <svg className="map-svg" viewBox="0 0 1000 720" preserveAspectRatio="xMidYMid slice">
      <rect x="0" y="0" width="1000" height="720" fill="var(--map-bg)" />
      <path d="M 600 470 Q 680 440 760 470 Q 820 530 780 600 Q 700 640 620 610 Q 560 560 600 470 Z"
            fill="var(--map-park)" stroke="var(--map-stroke)" strokeWidth="0.5" />
      <path d="M 920 0 Q 880 200 905 400 Q 940 560 920 720 L 1000 720 L 1000 0 Z"
            fill="var(--map-water)" stroke="var(--map-stroke)" strokeWidth="0.5" />
      <path d="M 0 220 Q 120 240 220 200 Q 320 170 380 240 Q 440 320 380 380"
            fill="none" stroke="var(--map-water)" strokeWidth="22" strokeLinecap="round" />
      {blocks}
      {buildings}
      <text x="700" y="540" fontFamily="JetBrains Mono" fontSize="11" fill="var(--ink-3)" letterSpacing="2">PARK</text>
      <text x="940" y="360" fontFamily="JetBrains Mono" fontSize="11" fill="var(--ink-3)" letterSpacing="2" transform="rotate(-90 940 360)">WATER</text>
      <text x="120" y="200" fontFamily="JetBrains Mono" fontSize="10" fill="var(--ink-3)" letterSpacing="1.5">RIVER</text>
    </svg>
  );
};

const MapPin = ({ pin, idx }) => {
  const tone = TONE_HEX[pin.tone] || "var(--accent)";
  return (
    <div className="map-pin" style={{ left: pin.x + "%", top: pin.y + "%", animationDelay: (idx*60)+"ms" }}>
      <div className="pin-bubble">
        <span className="pin-dot" style={{ background: tone }}></span>
        <span>{pin.label}</span>
      </div>
      <div className="pin-stem" style={{ background: tone }}></div>
      <div className="pin-anchor" style={{ background: tone }}></div>
    </div>
  );
};

// ── SEARCH ─────────────────────────────────────────────────────────────────
const SearchScreen = ({ onSubmit }) => {
  const [val, setVal] = useState("");
  const submit = (v) => { const final = v ?? val; if (final.trim()) onSubmit(final.trim()); };
  return (
    <div className="screen search-wrap">
      <div className="mascot-cluster tl">
        <div className="droplet"><div className="eyes"><div className="eye"/><div className="eye"/></div><div className="smile"/></div>
      </div>
      <div className="mascot-cluster br">
        <div className="droplet sm"><div className="eyes"><div className="eye"/><div className="eye"/></div><div className="smile"/></div>
      </div>

      <div className="search-card">
        <span className="eyebrow">{BRAND_NAME}</span>
        <h1 className="lede">Your <em>real</em> flood risk.</h1>

        <form className="search-input-row" onSubmit={(e) => { e.preventDefault(); submit(); }}>
          <span className="search-icon"><Icon name="search" size={18}/></span>
          <input className="search-input" value={val} onChange={(e)=>setVal(e.target.value)}
            placeholder="Address" />
          <button className="search-submit" type="submit">Investigate <Icon name="arrow-right" size={14}/></button>
        </form>

        <div className="chip-row">
          {EXAMPLES.map((ex) => (
            <button key={ex.label} className="chip" onClick={() => { setVal(ex.label); submit(ex.label); }}>
              {ex.label}
            </button>
          ))}
        </div>

        <section className="how-it-works">
          <div className="hiw-header">
            <span className="hiw-eyebrow">How it works</span>
            <h2 className="hiw-headline">Three steps from address to action plan.</h2>
            <p className="hiw-intro">FEMA flood maps miss the risks that actually hit homeowners. FlutIQ fills the gap with AI that checks what the maps won't.</p>
          </div>

          <div className="hiw-steps">
            <div className="hiw-step">
              <span className="hiw-num">01</span>
              <h3 className="hiw-title">Spot the gap</h3>
              <p className="hiw-subline">FEMA only maps rivers and coasts.</p>
              <p className="hiw-detail">Most urban flood damage comes from sewer backup, storm surge, and poor drainage — none of which appear on official flood maps. If your zone says "minimal risk," it might be wrong.</p>
            </div>
            <div className="hiw-step">
              <span className="hiw-num">02</span>
              <h3 className="hiw-title">Investigate everything</h3>
              <p className="hiw-subline">7 AI agents. 9 public data sources. ~60 seconds.</p>
              <p className="hiw-detail">Flood zones, 311 complaints, building permits, river gauges, weather forecasts, news reports — even satellite and street-level imagery. All checked in parallel, all synthesized by AI reasoning.</p>
            </div>
            <div className="hiw-step">
              <span className="hiw-num">03</span>
              <h3 className="hiw-title">Get your dossier</h3>
              <p className="hiw-subline">A verdict, a checklist, and a plan.</p>
              <p className="hiw-detail">Your personalized risk report includes a bottom-line score, a before-you-sign checklist with evidence, drainage and barrier recommendations, and real insurance products matched to your risk — in your language.</p>
            </div>
          </div>

          <div className="hiw-trust">
            <span className="hiw-trust-label">Powered by 9 public data sources</span>
            <div className="hiw-pills">
              <span className="hiw-pill">FEMA NFHL</span>
              <span className="hiw-pill">FEMA NRI</span>
              <span className="hiw-pill">311 + Permits</span>
              <span className="hiw-pill">USGS</span>
              <span className="hiw-pill">NOAA</span>
              <span className="hiw-pill">Open-Meteo</span>
              <span className="hiw-pill">GDELT</span>
              <span className="hiw-pill">Mapbox Satellite</span>
              <span className="hiw-pill">Street View</span>
            </div>
          </div>

          <div className="hiw-edge-note">
            <span className="hiw-edge-label">FlutIQ Edge · also runs offline</span>
            <p className="hiw-edge-detail">The same agents and dossier can run locally on a laptop via Ollama with Gemma 4 e4b on-device. No API key, no internet for inference — the address never leaves your device.</p>
          </div>
        </section>
      </div>
    </div>
  );
};

// ── AGENTS / MAP ───────────────────────────────────────────────────────────
const AgentsScreen = ({ address, language, onComplete, dark }) => {
  const startedAt = useRef(Date.now());
  const [now, setNow] = useState(Date.now());
  const { start, agentState, geocode, dossier, error, running } = useFloodAssessment();

  useEffect(() => {
    start(address, language || "en");
    const tickClock = setInterval(() => setNow(Date.now()), 100);
    return () => clearInterval(tickClock);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [address, language]);

  // Once the backend emits the full dossier, hand it up.
  useEffect(() => {
    if (dossier && onComplete) onComplete(dossier);
  }, [dossier, onComplete]);

  const total = AGENTS.length;
  const doneCount = AGENTS.filter(a => agentState[a.id]?.status === "done").length;
  const erroredCount = AGENTS.filter(a => agentState[a.id]?.status === "error").length;
  const tick = doneCount + erroredCount;
  const progress = Math.min(tick / total, 1);
  const elapsed = ((now - startedAt.current)/1000).toFixed(1);
  const cute = ["humming…","sleuthing…","peeking…","scribbling…","triangulating…","double-checking…","sniffing the data…"];

  // Pins surface for any agent that has reported done/error and has a pin.
  const visiblePins = AGENTS
    .filter(a => a.pin && (agentState[a.id]?.status === "done" || agentState[a.id]?.status === "working"))
    .map((a, i) => ({ ...a, _idx: i }));

  return (
    <div className="screen agents-grid">
      <aside className="agents-side">
        <div className="agents-target">INVESTIGATING</div>
        <div className="agents-addr">{address}</div>
        <div className="progress-track"><div className="progress-fill" style={{width: (progress*100)+"%"}}/></div>
        <div className="progress-meta">
          <span>{tick} / {total} agents on it</span>
          <span>{elapsed}s</span>
        </div>

        <div className="agent-list">
          {AGENTS.map((a, i) => {
            const live = agentState[a.id];
            // Backend statuses: queued, working, done, error.
            // Unreported = idle (the agent hasn't been registered yet,
            // which happens briefly before the orchestrator's initial
            // round of agent_update events arrives).
            const status = live?.status || "idle";
            const summary = live?.summary;
            return (
              <div key={a.id} className="agent-item">
                <div className="agent-head">
                  <span className={`agent-dot ${status}`}/>
                  <span className="agent-name">{a.name}</span>
                  <span className={`agent-status ${status}`}>{status}</span>
                </div>
                {(status === "done" || status === "working" || status === "error" || status === "queued") && (
                  <div className="agent-finding">
                    {status === "working"
                      ? <span style={{color:"var(--ink-3)"}}>{summary || cute[i % cute.length]}</span>
                      : status === "queued"
                      ? <span style={{color:"var(--ink-3)"}}>{summary || "queued — waiting for upstream agents"}</span>
                      : (summary || a.finding)}
                  </div>
                )}
              </div>
            );
          })}
        </div>
        {error && (
          <div style={{marginTop: 12, padding: "10px 12px", background: "var(--coral-soft)", color: "var(--coral)", borderRadius: 8, fontSize: 12}}>
            {error}
          </div>
        )}

        <div className="agents-foot">
          ORCHESTRATOR · gemma-4-31b-it · thinking=on<br/>
          5 agents in parallel · 2 sequential synthesis<br/>
          all data sources public · 0 PII stored
        </div>
      </aside>

      <div className="map-pane">
        {geocode
          ? <RealMap geocode={geocode} dark={dark}/>
          : <NeighborhoodMap dark={dark}/>}

        {!geocode && (
          <div className="map-center" style={{ left: "50%", top: "50%" }}>
            <div style={{position:"relative", width:0, height:0}}>
              <div className="center-ring" style={{position:"absolute", left:-48, top:-48}}/>
              <div className="center-ring b" style={{position:"absolute", left:-48, top:-48}}/>
              <div className="center-ring c" style={{position:"absolute", left:-48, top:-48}}/>
              <div className="center-pin"/>
            </div>
          </div>
        )}

        <div className="map-overlay-tl" style={{zIndex: 500}}>
          {geocode
            ? `${Math.abs(geocode.lat).toFixed(4)}°${geocode.lat >= 0 ? "N" : "S"} · ${Math.abs(geocode.lon).toFixed(4)}°${geocode.lon >= 0 ? "E" : "W"}`
            : "geocoding…"}<br/>
          ZOOM 15 · 500m search radius
        </div>
        <div className="map-overlay-tr" style={{zIndex: 500}}>
          <div className="legend">
            <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:4}}><span style={{width:8,height:8,borderRadius:"50%",background:"var(--accent)"}}/> property</div>
            <div style={{display:"flex",alignItems:"center",gap:6}}><span style={{width:14,height:8,borderRadius:"3px",background:"rgba(43,111,212,0.2)",border:"1px solid var(--accent)"}}/> 500m radius</div>
          </div>
        </div>
        {!geocode && (
          <div className="map-overlay-bl" style={{zIndex: 500}}>
            basemap · synthetic placeholder
          </div>
        )}
      </div>
    </div>
  );
};

// ── DOSSIER ────────────────────────────────────────────────────────────────
const Section = ({ icon, iconBg, num, title, badge, children, defaultOpen = true }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className="section">
      <div className="sec-head" onClick={()=>setOpen(o=>!o)}>
        <div className="sec-icon" style={{ background: iconBg }}>{icon}</div>
        <div className="sec-title">
          <span className="sec-num">{num}</span>
          <h3>{title}</h3>
          {badge}
        </div>
        <span className={`sec-toggle ${open ? "open" : ""}`}><Icon name="chevron-down" size={18}/></span>
      </div>
      {open && <div className="sec-body">{children}</div>}
    </section>
  );
};

const RiskCircle = ({ score }) => {
  const color = score >= 61 ? "var(--coral)" : score >= 31 ? "var(--amber)" : "var(--teal)";
  const C = 2 * Math.PI * 42;
  return (
    <div className="risk-circle">
      <svg width="96" height="96" viewBox="0 0 96 96">
        <circle cx="48" cy="48" r="42" stroke="var(--line-2)" strokeWidth="6" fill="none"/>
        <circle cx="48" cy="48" r="42" stroke={color} strokeWidth="6" fill="none"
          strokeDasharray={C} strokeDashoffset={C * (1 - score/100)} strokeLinecap="round"
          style={{ transition: "stroke-dashoffset 1.2s cubic-bezier(.4,0,.2,1)" }}/>
      </svg>
      <div className="num" style={{ color }}>{score}</div>
    </div>
  );
};

// Map the live backend dossier shape onto the existing display shape.
// Be defensive about missing fields — any individual agent could have errored.
// `lang` drives translation of the static headline templates; the dossier
// PROSE (verdict, NRI narrative, vision findings) is already translated
// server-side by the language directive.
const mapDossier = (raw, lang = "en") => {
  if (!raw) return DOSSIER;
  const fema    = raw.fema    || {};
  const local   = raw.local   || {};
  const weather = raw.weather || {};
  const news    = raw.news    || {};
  const archive = raw.archive || {};
  const risk    = raw.risk    || {};
  const advisor = raw.advisor || {};

  const score = Number.isFinite(risk.risk_score) ? Math.round(risk.risk_score) : 0;
  const level = (risk.risk_level || (score >= 61 ? "high" : score >= 31 ? "medium" : "low")).toLowerCase();
  const aep_pct = risk.aep_estimate != null ? +(risk.aep_estimate * 100).toFixed(2) : null;
  const cum_pct = risk.mortgage_30yr_probability != null ? Math.round(risk.mortgage_30yr_probability * 100) : null;

  // Headline framing — the FEMA-gap thesis kicks in when FEMA says "safe"
  // but the risk agent disagrees. Both halves come from UI_STRINGS so the
  // headline reads in the user's chosen language, not English.
  const femaSaysSafe = fema.is_sfha === false;
  const headline = (() => {
    if (level === "high" && femaSaysSafe)
      return { pre: tr(lang, "headline_high_femasafe_pre"), em: tr(lang, "headline_high_femasafe_em") };
    if (level === "high")
      return { pre: tr(lang, "headline_high_pre"),          em: tr(lang, "headline_high_em") };
    if (level === "medium" && femaSaysSafe)
      return { pre: tr(lang, "headline_med_femasafe_pre"),  em: tr(lang, "headline_med_femasafe_em") };
    if (level === "medium")
      return { pre: tr(lang, "headline_med_pre"),           em: "" };
    if (level === "low" && femaSaysSafe)
      return { pre: tr(lang, "headline_low_femasafe_pre"),  em: tr(lang, "headline_low_femasafe_em") };
    return { pre: tr(lang, "headline_low_pre"), em: "" };
  })();

  const tags = [];
  if (fema.flood_zone) tags.push({ label: `FEMA Zone ${fema.flood_zone}`, tone: fema.is_sfha ? "coral" : "amber" });
  if (raw.city) tags.push({ label: raw.city, tone: "blue" });
  if (raw.county) tags.push({ label: raw.county, tone: "neutral" });
  if (local?.data_available && raw.city?.toLowerCase().includes("chicago")) tags.push({ label: "Combined sewer", tone: "neutral" });

  const femaGapBody = [
    risk.fema_gap_explanation,
    fema.gap_warning,
  ].filter(Boolean);

  const gauge = weather.nearest_gauge || {};
  const gaugeName = (gauge.site_name || "").split(" AT ")[0] || gauge.site_name || "—";
  const gaugeHeight = gauge.current_gage_height_ft;

  const infra = [
    { label: "FEMA flood zone", val: fema.flood_zone || "—",
      small: fema.is_sfha ? "Special Flood Hazard Area" : (fema.zone_description ? "outside SFHA" : null) },
    // 311 rows only appear when a city-specific 311 dataset is wired
    // (currently Chicago only). For other cities we omit them entirely
    // rather than showing empty dashes.
    ...(local.data_available ? [
      { label: "Basement-flood 311 reports", val: local.basement_flooding_reports ?? "—",
        small: `${local?.raw?.years || 5}y · ${local?.raw?.radius_m || 500}m` },
      { label: "Street-flood 311 reports", val: local.street_flooding_reports ?? "—" },
    ] : []),
    { label: "Nearest stream gauge", val: gaugeName,
      small: gaugeHeight != null ? `${gaugeHeight} ft current` : null },
    { label: "Active flood alerts", val: (weather.active_flood_alerts?.length ?? 0).toString(),
      small: weather.near_term_concern ? `near-term: ${weather.near_term_concern}` : null },
    { label: "River discharge trend", val: weather.river_discharge_trend || "—" },
    { label: "Historical events (24mo)", val: archive.event_count != null ? String(archive.event_count) : "—",
      small: archive.frequency_assessment ? archive.frequency_assessment : null },
    { label: "FEMA panel", val: fema?.raw?.DFIRM_ID || "—" },
  ];

  const _PRIORITY_LABEL = {
    start_here: "start here",
    also_consider: "also consider",
    only_if: "only if",
    essential: "start here",      // legacy
    recommended: "also consider", // legacy
    optional: "only if",          // legacy
  };
  const insurance = (advisor.insurance_recommendations || []).map(i => {
    const prio = (i.priority || "").toLowerCase();
    return {
      type: (i.policy_type || "").toLowerCase().replace(/\s+/g, "_"),
      name: i.policy_type || "Coverage option",
      cost: i.estimated_cost || "—",
      desc: i.covers || "",
      not_covered: i.does_not_cover || "",
      how_to_buy: i.how_to_buy || "",
      why: i.rationale || "",
      priority: prio,
      priority_label: _PRIORITY_LABEL[prio] || prio,
      recommended: prio === "start_here" || prio === "essential",
    };
  });
  // Sort: start_here → also_consider → only_if → unknown
  const _PRIORITY_ORDER = { start_here: 0, essential: 0, also_consider: 1, recommended: 1, only_if: 2, optional: 2 };
  insurance.sort((a, b) =>
    (_PRIORITY_ORDER[a.priority] ?? 9) - (_PRIORITY_ORDER[b.priority] ?? 9)
  );
  const advisor_tldr = advisor.tldr || "";

  const actions = (advisor.mitigation_actions || []).map(a => ({
    bucket: (a.bucket || "other").toLowerCase(),
    title: a.action || "Action",
    cost: a.cost || "",
    desc: a.first_step || "",
    effort: a.effort || "",
    impact: a.impact || "",
    contact: null,
  }));

  const before_you_move_in = (advisor.before_you_move_in || []).map(b => ({
    check: b.check || "",
    why: b.why || "",
    how: b.how || "",
    cite: b.cite || "",
  })).filter(b => b.check);

  // Surface advisor.key_resources as additional bottom rows. Tagged
  // with bucket "resources" so the grouped renderer keeps them in
  // their own section after the three physical-mitigation buckets.
  const resourceRows = (advisor.key_resources || []).map(r => ({
    bucket: "resources",
    title: r.name || "Resource",
    cost: "info",
    desc: r.what || "",
    effort: "",
    impact: "",
    contact: r.contact_or_url || null,
  }));

  const newsItems = (news.articles || []).map(n => ({
    date: n.date || "",
    title: n.title || "",
    source: n.source || "",
    url: n.url || null,
  }));

  return {
    score, level,
    headline_pre: headline.pre,
    headline_em: headline.em,
    address: raw.address || "",
    tags,
    fema_gap: {
      body: femaGapBody.length ? femaGapBody : ["The risk analyst did not produce a FEMA-gap narrative for this address."],
      aep_pct: aep_pct ?? 0,
      cum_pct: cum_pct ?? 0,
      cum_label: "30-year mortgage",
    },
    infra,
    insurance,
    actions: [...actions, ...resourceRows],
    news: newsItems,
    risk_factors: risk.key_risk_factors || [],
    mitigating_factors: risk.mitigating_factors || [],
    reasoning_trace: risk.reasoning_trace || "",
    visual_corroboration: risk.visual_corroboration || "",
    used_streetview_image: !!risk.used_streetview_image,
    images_used: risk.images_used || [],
    advisor_tldr,
    plain_verdict: risk.plain_verdict || "",
    before_you_move_in,
    streetview: raw.streetview || {},
    satellite: raw.satellite || {},
    local: raw.local || {},
    regional: raw.regional || {},
    property_type: raw.property_type || "residential",
  };
};

const DossierScreen = ({ onBack, dossier, language = "en" }) => {
  const D = useMemo(() => mapDossier(dossier, language), [dossier, language]);
  const t = useCallback((key) => tr(language, key), [language]);
  const [showReasoning, setShowReasoning] = useState(false);

  // Section numbers depend on which conditional sections render. We
  // precompute them so the rendering JSX stays readable. The order
  // here mirrors the visual order in the dossier below.
  // Commercial properties suppress the homeowner-specific sections
  // (before-you-sign, actions, insurance) — see commercial banner below.
  const isCommercial = D.property_type === "commercial";
  const _sectionNums = useMemo(() => {
    const hasBefore   = !isCommercial && (D.before_you_move_in || []).length > 0;
    const hasActions  = !isCommercial;
    const hasInsurance = !isCommercial;
    const hasImages   = D.streetview?.available || D.satellite?.available;
    const hasRegional = D.regional?.available;
    let n = 0;
    const fmt = () => "§" + String(++n).padStart(2, "0");
    return {
      before:    hasBefore    ? fmt() : null,
      actions:   hasActions   ? fmt() : null,
      insurance: hasInsurance ? fmt() : null,
      images:    hasImages    ? fmt() : null,
      gap:       fmt(),
      regional:  hasRegional  ? fmt() : null,
      signals:   fmt(),
      news:      fmt(),
    };
  }, [D, isCommercial]);
  const [showBoxes, setShowBoxes] = useState(true);
  const [imageTab, setImageTab] = useState("streetview");  // "streetview" | "satellite" | "topo"
  return (
    <div className="screen dossier-wrap">
      <div className="dossier">
        <div className="dossier-toolbar">
          <span className="back" onClick={onBack}><Icon name="arrow-left" size={14}/> new search</span>
          <span className="meta">DOSSIER · {new Date().toLocaleDateString("en-US",{year:"numeric",month:"short",day:"2-digit"}).toUpperCase()} · v1</span>
        </div>

        <div className="dossier-head">
          <RiskCircle score={D.score}/>
          <div className="risk-meta">
            <span className={`risk-tag ${D.level === "high" ? "coral" : D.level === "medium" ? "amber" : "teal"}`}>
              {t("risk_" + D.level)} · {D.score}/100
            </span>
            <h2 className="risk-headline">{D.headline_pre} {D.headline_em && <em>{D.headline_em}</em>}</h2>
            <div className="risk-addr">{D.address}</div>
            <div className="risk-tags">
              {D.tags.map((t,i) => <span key={i} className={`risk-tag ${t.tone}`}>{t.label}</span>)}
            </div>
          </div>
        </div>

        {isCommercial && (
          <div style={{margin: "20px 0 14px", padding: "14px 16px 16px", background: "var(--surface)", border: "1px solid var(--line)", borderLeft: "4px solid var(--amber)", borderRadius: 12, boxShadow: "0 6px 16px rgba(22,22,22,0.04)"}}>
            <div style={{display: "flex", alignItems: "center", gap: 8, fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--amber)", marginBottom: 8}}>
              <span>◆ {t("commercial_label")}</span>
              <span style={{color: "var(--ink-4)", fontWeight: 400, textTransform: "none", letterSpacing: "0.02em"}}>· {t("commercial_sub")}</span>
            </div>
            <p style={{margin: 0, fontSize: 14, lineHeight: 1.6, color: "var(--ink)"}}>
              {t("commercial_body")}
            </p>
          </div>
        )}

        {!isCommercial && D.plain_verdict && (
          <div style={{margin: "20px 0 14px", padding: "16px 18px 18px", background: "var(--surface)", border: "1px solid var(--line)", borderLeft: "4px solid var(--accent)", borderRadius: 12, boxShadow: "0 6px 16px rgba(22,22,22,0.04)"}}>
            <div style={{display: "flex", alignItems: "center", gap: 8, fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--accent)", marginBottom: 8}}>
              <span>◆ {t("bottom_line_label")}</span>
              <span style={{color: "var(--ink-4)", fontWeight: 400, textTransform: "none", letterSpacing: "0.02em"}}>· {t("bottom_line_sub")}</span>
            </div>
            <p style={{margin: 0, fontSize: 15, lineHeight: 1.6, color: "var(--ink)"}}>{D.plain_verdict}</p>
          </div>
        )}

        {(() => {
          // Synthesis receipt — shows what data sources fed the briefing.
          // Quietly tells the time-compression story without bragging.
          const items = [];
          if (D.fema_gap?.aep_pct != null) items.push(`FEMA · ${D.fema_gap.aep_pct.toFixed?.(2) ?? D.fema_gap.aep_pct}% AEP`);
          const r311 = (D.local?.basement_flooding_reports ?? null);
          const s311 = (D.local?.street_flooding_reports ?? null);
          if (r311 != null || s311 != null) items.push(`311 · ${(r311 ?? 0)} basement / ${(s311 ?? 0)} street`);
          const con = D.local?.construction;
          if (con && (con.permits_count || con.total_reported_cost)) {
            const dollars = con.total_reported_cost ? ` / $${(con.total_reported_cost/1e6).toFixed(0)}M` : "";
            items.push(`Permits · ${con.permits_count || 0}${dollars} / 3y`);
          }
          if (D.regional?.available) items.push("NRI multi-hazard");
          items.push("USGS · NOAA");
          if (D.images_used?.length) items.push(`${D.images_used.length} image${D.images_used.length === 1 ? "" : "s"} (${D.images_used.join(" + ")})`);
          return (
            <div style={{margin: "0 0 22px", padding: "10px 14px", background: "var(--bg)", border: "1px dashed var(--line)", borderRadius: 8, fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: "var(--ink-3)", lineHeight: 1.7}}>
              <span style={{color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.08em", marginRight: 8}}>{t("synthesized_from")}</span>
              {items.join("  ·  ")}
            </div>
          );
        })()}

        {!isCommercial && D.before_you_move_in.length > 0 && (
          <Section
            num={_sectionNums.before}
            icon={<Icon name="search" color="var(--purple)" size={16}/>}
            iconBg="var(--purple-soft)"
            title={t("section_before")}
            badge={<span className="risk-tag purple">due diligence</span>}>
            <p style={{color:"var(--ink-2)"}}>If you're considering a lease or a purchase, these are the things a flood-savvy buyer would check first. Each item points to the data layer that flagged it.</p>
            {D.before_you_move_in.map((b,i) => (
              <div key={i} className="action-row">
                <div className="action-num">{i+1}</div>
                <div className="action-body">
                  <div className="action-title">{b.check}{b.cite && <span className="cost" style={{color:"var(--purple)", background:"var(--purple-soft)", padding:"2px 8px", borderRadius:6, marginLeft:8, fontSize:11}}>from {b.cite}</span>}</div>
                  {b.why && <div className="action-desc"><strong>Why · </strong>{b.why}</div>}
                  {b.how && <div className="action-desc" style={{marginTop:4}}><strong>How · </strong>{b.how}</div>}
                </div>
              </div>
            ))}
          </Section>
        )}

        {!isCommercial && (
        <Section
          num={_sectionNums.actions}
          icon={<Icon name="plus" color="var(--teal)" size={16}/>}
          iconBg="var(--teal-soft)"
          title={t("section_actions")}
          badge={<span className="risk-tag teal">personalized</span>}>
          <p style={{color:"var(--ink-2)"}}>Three ways to harden a property against urban flooding: get water <strong>away</strong> from the building, let it <strong>soak in</strong>, and <strong>block</strong> the rest from getting inside. Items below are sequenced cheapest-and-easiest first within each group.</p>
          {D.actions.length === 0 ? (
            <p style={{color:"var(--ink-3)"}}>The advisor agent did not return an action plan for this address.</p>
          ) : (() => {
            const BUCKETS = [
              {key: "drainage",     label: "Get water away from the building",  hint: "downspouts, sump pumps, regrading"},
              {key: "infiltration", label: "Let water soak in",                 hint: "rain gardens, rainwater harvesting, permeable surfaces"},
              {key: "barrier",      label: "Block water from getting in",       hint: "backwater valve, waterproofing, flood vents"},
              {key: "resources",    label: "Local resources & rebates",         hint: "city programs, contacts, grants"},
              {key: "other",        label: "Other actions",                     hint: ""},
            ];
            let counter = 0;
            return BUCKETS.map(bk => {
              const items = D.actions.filter(a => (a.bucket || "other").toLowerCase() === bk.key);
              if (items.length === 0) return null;
              return (
                <div key={bk.key} style={{marginTop: 16}}>
                  <div style={{display:"flex", alignItems:"baseline", gap:10, marginBottom:6, paddingBottom:6, borderBottom:"1px solid var(--line)"}}>
                    <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:11, color:"var(--teal)", textTransform:"uppercase", letterSpacing:"0.08em"}}>{bk.label}</span>
                    {bk.hint && <span style={{color:"var(--ink-4)", fontSize:11}}>· {bk.hint}</span>}
                  </div>
                  {items.map((a,i) => {
                    counter += 1;
                    return (
                      <div key={i} className="action-row">
                        <div className="action-num">{counter}</div>
                        <div className="action-body">
                          <div className="action-title">{a.title}<span className="cost">· {a.cost}</span>{a.effort && <span className="cost" style={{color:"var(--ink-4)", marginLeft:6}}>· {a.effort}</span>}{a.impact && <span className="cost" style={{color:a.impact === "high" ? "var(--teal)" : "var(--ink-4)", marginLeft:6}}>· {a.impact} impact</span>}</div>
                          <div className="action-desc">{a.desc}</div>
                          {a.contact && <div className="action-contact">{a.contact}</div>}
                        </div>
                      </div>
                    );
                  })}
                </div>
              );
            });
          })()}
        </Section>
        )}

        {!isCommercial && (
        <Section
          num={_sectionNums.insurance}
          icon={<Icon name="dollar" color="var(--purple)" size={16}/>}
          iconBg="var(--purple-soft)"
          title={t("section_insurance")}
          badge={<span className="risk-tag teal">verified products</span>}>
          {D.advisor_tldr && (
            <div style={{marginBottom: 14, padding: "12px 14px", background: "var(--teal-soft)", borderRadius: 10, fontSize: 14, color: "var(--ink)", lineHeight: 1.5}}>
              <strong style={{color:"var(--teal)"}}>For this property: </strong>{D.advisor_tldr}
            </div>
          )}
          <p style={{color:"var(--ink-2)"}}>Flood insurance feels intimidating, but the menu is short. The products listed here are real, verified, and currently available — never invented by the model. Prices are typical ranges; get an exact quote from the link or phone in each card.</p>
          {D.insurance.length === 0 ? (
            <p style={{color:"var(--ink-3)"}}>The advisor agent did not return insurance recommendations for this address.</p>
          ) : (
            <div className="ins-grid">
              {D.insurance.map((c,i) => {
                const tone = c.priority === "start_here" || c.priority === "essential" ? "teal"
                          : c.priority === "also_consider" || c.priority === "recommended" ? "blue"
                          : "neutral";
                return (
                  <div key={i} className={"ins-card" + (c.recommended ? " recommended" : "")}>
                    {c.priority_label && <span className={`recbadge`} style={{background: `var(--${tone}-soft, rgba(22,22,22,0.05))`, color: `var(--${tone}, var(--ink-2))`}}>{c.priority_label}</span>}
                    <div className="ins-name">{c.name}</div>
                    <div className="ins-cost">{c.cost}</div>
                    <div className="ins-desc">{c.desc}</div>
                    {c.not_covered && (
                      <div style={{marginTop:8, fontSize:12, color:"var(--ink-3)", lineHeight:1.5}}>
                        <strong style={{color:"var(--coral)"}}>Doesn't cover · </strong>{c.not_covered}
                      </div>
                    )}
                    <div className="ins-why" style={{marginTop:8}}>Why · {c.why}</div>
                    {c.how_to_buy && (
                      <div style={{marginTop:10, padding:"8px 10px", background:"var(--bg)", borderRadius:6, fontSize:12, color:"var(--ink-2)", lineHeight:1.5}}>
                        <strong style={{color:"var(--accent)"}}>How to get it · </strong>{c.how_to_buy}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </Section>
        )}

        {(D.streetview?.available || D.satellite?.available) && (() => {
          const tabs = [
            D.streetview?.available && {key:"streetview", label:"Street level", source:"Google"},
            D.satellite?.available  && {key:"satellite",  label:"Satellite",    source:"Mapbox"},
          ].filter(Boolean);
          const activeKey = tabs.find(t => t.key === imageTab) ? imageTab : tabs[0]?.key;
          const active = activeKey === "streetview" ? D.streetview
                       : activeKey === "satellite"  ? D.satellite
                       : null;
          const activeAlt = activeKey === "streetview" ? "Google Street View of the property"
                         : activeKey === "satellite"  ? "Mapbox satellite view of the property + surrounding catchment"
                         : "";
          const indicatorsWithBoxes = (active?.indicators || []).filter(i => i.box_2d);
          const showOverlay = showBoxes && indicatorsWithBoxes.length > 0;
        return (
          <Section
            num={_sectionNums.images || "§03"}
            icon={<Icon name="pin" color="var(--accent)" size={16}/>}
            iconBg="var(--accent-soft)"
            title={t("section_images")}
            badge={<span className="risk-tag purple">Gemma 4 vision</span>}>
            <div style={{display:"grid", gridTemplateColumns:"320px 1fr", gap:18, alignItems:"start"}}>
              <div>
                {tabs.length > 1 && (
                  <div style={{display:"flex", gap:6, marginBottom:8}}>
                    {tabs.map(t => (
                      <button
                        key={t.key}
                        onClick={() => setImageTab(t.key)}
                        style={{
                          flex:1, padding:"6px 8px", fontSize:11,
                          fontFamily:"'JetBrains Mono', monospace",
                          letterSpacing:"0.04em", textTransform:"uppercase",
                          background: activeKey === t.key ? "var(--accent-soft)" : "transparent",
                          color: activeKey === t.key ? "var(--accent)" : "var(--ink-3)",
                          border: `1px solid ${activeKey === t.key ? "var(--accent)" : "var(--line)"}`,
                          borderRadius:6, cursor:"pointer",
                        }}
                      >
                        {t.label}
                      </button>
                    ))}
                  </div>
                )}
                <div style={{position:"relative", borderRadius:10, overflow:"hidden", border:"1px solid var(--line)", lineHeight:0}}>
                  <img
                    src={active.image_data_url}
                    alt={activeAlt}
                    style={{width:"100%", display:"block"}}
                  />
                  {showOverlay && (
                    <svg
                      viewBox="0 0 1000 1000"
                      preserveAspectRatio="none"
                      style={{position:"absolute", inset:0, width:"100%", height:"100%", pointerEvents:"none"}}
                    >
                      {indicatorsWithBoxes.map((ind, i) => {
                        const [y1, x1, y2, x2] = ind.box_2d;
                        const w = x2 - x1, h = y2 - y1;
                        const sev = (ind.severity || "").toLowerCase();
                        const color = sev === "high" ? "#EE6A3D"
                                    : sev === "moderate" ? "#D4881E"
                                    : sev === "low" ? "#0F8A6A"
                                    : "#2B6FD4";
                        const labelText = `${i+1}. ${ind.feature || "indicator"}`;
                        const labelWidthEstimate = labelText.length * 11 + 12;
                        const labelY = y1 > 50 ? y1 - 8 : y2 + 32;
                        return (
                          <g key={i}>
                            <rect
                              x={x1} y={y1} width={w} height={h}
                              fill="none"
                              stroke={color}
                              strokeWidth={4}
                              vectorEffect="non-scaling-stroke"
                              rx={6}
                            />
                            <rect
                              x={x1} y={labelY - 22}
                              width={Math.min(labelWidthEstimate, 1000 - x1)}
                              height={26}
                              fill={color}
                              rx={3}
                            />
                            <text
                              x={x1 + 6} y={labelY - 4}
                              fontSize={18}
                              fontFamily="DM Sans, sans-serif"
                              fontWeight={600}
                              fill="white"
                            >
                              {labelText}
                            </text>
                          </g>
                        );
                      })}
                    </svg>
                  )}
                </div>
                {indicatorsWithBoxes.length > 0 && (
                  <button
                    onClick={() => setShowBoxes(s => !s)}
                    style={{
                      marginTop:8, fontSize:11, fontFamily:"'JetBrains Mono', monospace",
                      letterSpacing:"0.04em", textTransform:"uppercase",
                      background:"transparent", border:"1px solid var(--line)",
                      borderRadius:6, padding:"4px 10px", color:"var(--ink-2)", cursor:"pointer",
                    }}
                  >
                    {showBoxes ? "hide" : "show"} {indicatorsWithBoxes.length} box{indicatorsWithBoxes.length === 1 ? "" : "es"}
                  </button>
                )}
                <div style={{fontSize:11, color:"var(--ink-4)", marginTop:6, fontFamily:"'JetBrains Mono', monospace"}}>
                  {activeKey === "streetview" && (
                    <>{active.copyright || "© Google"}
                      {active.capture_date && ` · captured ${active.capture_date}`}
                      {active.pano_distance_m != null && ` · ${active.pano_distance_m}m from address`}
                    </>
                  )}
                  {activeKey === "satellite" && (
                    <>© Mapbox · © OpenStreetMap · {active.style} · zoom {active.zoom}</>
                  )}
                </div>
              </div>
              <div>
                <p style={{margin:"0 0 10px"}}>
                  {activeKey === "streetview" ? (
                    <>The <strong>street-view agent</strong> ran Gemma 4 vision on this eye-level photo, looking for ground-floor flood-risk indicators (basement windows, downspouts, lot grade, evidence of prior damage). The model was instructed not to fabricate features it couldn't see.</>
                  ) : (
                    <>The <strong>satellite agent</strong> ran Gemma 4 vision on this bird's-eye image of the property and its surrounding block, looking for catchment-scale signals: impervious surface, building footprint, drainage features, and adjacent land use that drains TO this property.</>
                  )}
                </p>
                <div style={{display:"flex", gap:8, flexWrap:"wrap", marginBottom:12, fontSize:12}}>
                  <span className={`risk-tag ${active.overall_visual_risk === "high" ? "coral" : active.overall_visual_risk === "moderate" ? "amber" : "teal"}`}>
                    visual risk: {active.overall_visual_risk || "unclear"}
                  </span>
                  {activeKey === "streetview" && active.elevation_vs_street && active.elevation_vs_street !== "unclear" && (
                    <span className="risk-tag neutral">{active.elevation_vs_street.replace(/_/g, " ")}</span>
                  )}
                  {activeKey === "satellite" && active.impervious_estimate_pct != null && (
                    <span className="risk-tag neutral">impervious ≈ {active.impervious_estimate_pct}%</span>
                  )}
                  {activeKey === "satellite" && active.building_footprint_pct != null && (
                    <span className="risk-tag neutral">building ≈ {active.building_footprint_pct}% of lot</span>
                  )}
                  {activeKey === "satellite" && active.vegetation_buffer && (
                    <span className="risk-tag neutral">vegetation: {active.vegetation_buffer}</span>
                  )}
                  <span className="risk-tag neutral">confidence: {active.confidence || "unknown"}</span>
                </div>
                {activeKey === "satellite" && active.catchment_assessment && (
                  <p style={{margin:"0 0 10px", fontSize:13, color:"var(--ink-2)", lineHeight:1.55, padding:"8px 10px", background:"var(--bg)", borderLeft:"3px solid var(--accent)", borderRadius:4}}>
                    <strong style={{color:"var(--accent)"}}>Catchment · </strong>{active.catchment_assessment}
                  </p>
                )}
                {(active.indicators || []).length > 0 ? (
                  <ol style={{margin:0, paddingLeft:0, listStyle:"none", fontSize:13, color:"var(--ink-2)", lineHeight:1.55}}>
                    {active.indicators.map((ind, i) => {
                      const sev = (ind.severity || "").toLowerCase();
                      const color = sev === "high" ? "var(--coral)"
                                  : sev === "moderate" ? "var(--amber)"
                                  : sev === "low" ? "var(--teal)"
                                  : "var(--accent)";
                      return (
                        <li key={i} style={{marginBottom:10, display:"flex", gap:10}}>
                          <span style={{
                            flexShrink:0, width:22, height:22, borderRadius:4,
                            background:color, color:"white",
                            fontSize:12, fontWeight:600, fontFamily:"'JetBrains Mono', monospace",
                            display:"flex", alignItems:"center", justifyContent:"center",
                          }}>{i+1}</span>
                          <div>
                            <strong>{ind.feature}</strong>
                            {ind.category && <span className="small" style={{marginLeft:6, color:"var(--ink-4)"}}> · {ind.category}</span>}
                            {ind.severity && <span className="small" style={{marginLeft:6}}> · {ind.severity}</span>}
                            {!ind.box_2d && <span className="small" style={{marginLeft:6, color:"var(--ink-4)"}}> · no box</span>}
                            <div style={{color:"var(--ink-3)", fontSize:12, marginTop:2}}>{ind.risk_implication}</div>
                          </div>
                        </li>
                      );
                    })}
                  </ol>
                ) : (
                  <p style={{color:"var(--ink-3)", fontSize:13, margin:0}}>
                    {active.summary || "No specific indicators visible."}
                  </p>
                )}
              </div>
            </div>
          </Section>
        );
        })()}

        <Section
          num={_sectionNums.gap}
          icon={<Icon name="warn" color="var(--coral)" size={16}/>}
          iconBg="var(--coral-soft)"
          title={t("section_gap")}
          badge={D.level === "low" ? null : <span className="risk-tag coral">FEMA may understate risk</span>}
          defaultOpen={false}>
          {D.fema_gap.body.map((p,i) => <p key={i}>{p}</p>)}
          <div className="prob-block">
            <div className="prob-head">
              <span className="prob-label">Probability of at least one flood over a {D.fema_gap.cum_label}</span>
              <span className="prob-pct">{D.fema_gap.cum_pct}%</span>
            </div>
            <div className="prob-bar"><div className="fill" style={{width: D.fema_gap.cum_pct + "%"}}/></div>
            <div className="prob-foot">
              <span>AEP {D.fema_gap.aep_pct}% · per year</span>
              <span>P = 1 − (1 − AEP)<sup>30</sup></span>
            </div>
          </div>
          {(D.risk_factors.length > 0 || D.mitigating_factors.length > 0) && (
            <div style={{marginTop: 16, display:"grid", gridTemplateColumns: "1fr 1fr", gap: 14}}>
              {D.risk_factors.length > 0 && (
                <div>
                  <div className="stat-label" style={{marginBottom: 6}}>Key risk factors</div>
                  <ul style={{margin: 0, paddingLeft: 16, fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5}}>
                    {D.risk_factors.map((f,i) => <li key={i}>{f}</li>)}
                  </ul>
                </div>
              )}
              {D.mitigating_factors.length > 0 && (
                <div>
                  <div className="stat-label" style={{marginBottom: 6}}>Mitigating factors</div>
                  <ul style={{margin: 0, paddingLeft: 16, fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5}}>
                    {D.mitigating_factors.map((f,i) => <li key={i}>{f}</li>)}
                  </ul>
                </div>
              )}
            </div>
          )}
          {(D.visual_corroboration || D.used_streetview_image || (D.images_used && D.images_used.length > 0)) && (() => {
            const _imgLabel = {streetview: "street view", satellite: "satellite"};
            const usedImages = (D.images_used || []).map(k => _imgLabel[k] || k);
            const imgPart = usedImages.length === 0
              ? "no images"
              : usedImages.length === 1
                ? `${usedImages[0]} image`
                : `${usedImages.length} images (${usedImages.join(" + ")})`;
            return (
            <div style={{marginTop: 18, padding: "14px 16px", background: "linear-gradient(135deg, rgba(110,95,216,0.08), rgba(43,111,212,0.06))", border: "1px solid rgba(110,95,216,0.25)", borderRadius: 10}}>
              <div style={{display:"flex", alignItems:"center", gap: 8, fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--purple)", marginBottom: 8, flexWrap:"wrap"}}>
                <span>◆ Gemma 4 multimodal reasoning</span>
                <span style={{color: "var(--ink-4)", fontWeight: 400, textTransform: "none", letterSpacing: "0.02em"}}>· {imgPart} + 6 data sources + chain-of-thought · one inference call</span>
              </div>
              {D.visual_corroboration ? (
                <p style={{margin: 0, fontSize: 14, lineHeight: 1.55, color: "var(--ink)"}}>
                  <em>{D.visual_corroboration}</em>
                </p>
              ) : (
                <p style={{margin: 0, fontSize: 13, color: "var(--ink-3)"}}>
                  The risk analyst received {imgPart} and reasoned about them directly alongside the data — see the trace below.
                </p>
              )}
            </div>
            );
          })()}
          {(D.local?.construction || D.local?.compound_signal) && (() => {
            const con = D.local.construction || {};
            const compound = D.local.compound_signal;
            const major = (D.local.raw_construction || {}).major_projects || [];
            const total = D.local.raw_construction?.total_reported_cost || con.total_cost;
            const trend = con.trend_direction || D.local.raw_construction?.trend?.direction;
            const concern = (con.concern_level || "").toLowerCase();
            const concernColor = concern === "high" ? "var(--coral)"
                              : concern === "moderate" ? "var(--amber)"
                              : "var(--teal)";
            const trendIcon = trend === "increasing" ? "↑" : trend === "decreasing" ? "↓" : "→";
            return (
            <div style={{marginTop: 12, padding: "14px 16px", background: "rgba(238,106,61,0.05)", border: "1px solid rgba(238,106,61,0.22)", borderRadius: 10}}>
              <div style={{display:"flex", alignItems:"center", gap: 8, fontSize: 11, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--coral)", marginBottom: 8, flexWrap:"wrap"}}>
                <span>⊕ Development pressure</span>
                <span style={{color: "var(--ink-4)", fontWeight: 400, textTransform: "none", letterSpacing: "0.02em"}}>· what's being built around you, in real time</span>
              </div>
              {compound && (
                <p style={{margin: "0 0 10px", fontSize: 14, lineHeight: 1.55, color: "var(--ink)"}}>
                  <em>{compound}</em>
                </p>
              )}
              <div style={{display:"flex", gap:8, flexWrap:"wrap", fontSize: 12, marginBottom: 10}}>
                {con.permits_count != null && (
                  <span className="risk-tag neutral">{con.permits_count} permits · 1km · 3y</span>
                )}
                {con.new_construction_count != null && (
                  <span className="risk-tag neutral">{con.new_construction_count} new builds</span>
                )}
                {total != null && (
                  <span className="risk-tag neutral">${(total/1_000_000).toFixed(1)}M total</span>
                )}
                {trend && (
                  <span className="risk-tag neutral">{trendIcon} {trend}</span>
                )}
                {concern && (
                  <span className="risk-tag" style={{background: `${concernColor}1A`, color: concernColor, border: `1px solid ${concernColor}55`}}>concern: {concern}</span>
                )}
              </div>
              {con.interpretation && (
                <p style={{margin:"0 0 10px", fontSize:13, color:"var(--ink-2)", lineHeight:1.55}}>{con.interpretation}</p>
              )}
              {major.length > 0 && (
                <div>
                  <div className="stat-label" style={{marginBottom: 6}}>Largest projects within 1km</div>
                  <ol style={{margin:0, paddingLeft:0, listStyle:"none", fontSize:12, color:"var(--ink-2)", lineHeight:1.5}}>
                    {major.slice(0, 5).map((p, i) => (
                      <li key={i} style={{marginBottom:6, display:"grid", gridTemplateColumns:"110px 70px 1fr", gap:10, alignItems:"baseline"}}>
                        <span style={{fontFamily:"'JetBrains Mono', monospace", color:"var(--coral)", fontWeight:600}}>${(p.cost/1_000_000).toFixed(1)}M</span>
                        <span style={{fontFamily:"'JetBrains Mono', monospace", fontSize:11, color:"var(--ink-3)"}}>{(p.date || "").slice(0,7)}</span>
                        <span><strong style={{textTransform:"capitalize"}}>{p.type}</strong> · {p.address || ""}<span style={{color:"var(--ink-3)"}}> — {(p.description || "").slice(0,90)}</span></span>
                      </li>
                    ))}
                  </ol>
                </div>
              )}
            </div>
            );
          })()}
          {D.reasoning_trace && (
            <div style={{marginTop: 12, padding: "12px 14px", background: "rgba(110,95,216,0.06)", border: "1px solid rgba(110,95,216,0.2)", borderRadius: 10}}>
              <div style={{display:"flex", alignItems:"center", justifyContent:"space-between", cursor:"pointer"}} onClick={() => setShowReasoning(s => !s)}>
                <div style={{display:"flex", alignItems:"center", gap: 8, fontSize: 12, fontFamily: "'JetBrains Mono', monospace", letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--purple)"}}>
                  <span>◆ Gemma 4 reasoning trace</span>
                </div>
                <span style={{fontSize: 11, color: "var(--ink-3)"}}>{showReasoning ? "hide" : "show"}</span>
              </div>
              {showReasoning && (
                <pre style={{marginTop: 12, marginBottom: 0, fontSize: 12, fontFamily: "'JetBrains Mono', monospace", lineHeight: 1.55, color: "var(--ink-2)", whiteSpace: "pre-wrap", wordBreak: "break-word"}}>{D.reasoning_trace}</pre>
              )}
            </div>
          )}
        </Section>

        {D.regional?.available && (
          <Section
            num={_sectionNums.regional}
            icon={<Icon name="warn" color="var(--purple)" size={16}/>}
            iconBg="var(--purple-soft)"
            title={t("section_regional")}
            badge={<span className="risk-tag purple">FEMA NRI · county-level</span>}>
            <p style={{color:"var(--ink-2)", marginTop:0}}>
              FlutIQ is flood-focused, but your county faces other hazards too. This is FEMA's
              National Risk Index for {D.regional.nri?.county} {D.regional.nri?.state}
              {D.regional.nri?.population ? ` (pop. ${D.regional.nri.population.toLocaleString()})` : ""},
              calibrated against every other US county.
            </p>
            <div style={{display:"flex", gap:8, flexWrap:"wrap", margin:"12px 0", fontSize:12}}>
              {D.regional.nri?.composite_risk_rating && (
                <span className={`risk-tag ${
                  D.regional.nri.composite_risk_rating.includes("Very High") ? "coral"
                  : D.regional.nri.composite_risk_rating.includes("High") ? "amber"
                  : D.regional.nri.composite_risk_rating.includes("Moderate") ? "amber"
                  : "teal"
                }`}>
                  Composite: {D.regional.nri.composite_risk_rating} ({D.regional.nri.composite_risk_score}/100)
                </span>
              )}
              {D.regional.nri?.expected_annual_loss_usd != null && (
                <span className="risk-tag neutral">
                  Expected annual loss: ${(D.regional.nri.expected_annual_loss_usd / 1_000_000).toFixed(0)}M
                </span>
              )}
              {D.regional.nri?.social_vulnerability_rating && (
                <span className="risk-tag neutral">SoVI: {D.regional.nri.social_vulnerability_rating}</span>
              )}
              {D.regional.nri?.community_resilience_rating && (
                <span className="risk-tag neutral">Resilience: {D.regional.nri.community_resilience_rating}</span>
              )}
            </div>
            {Array.isArray(D.regional.headline_hazards) && D.regional.headline_hazards.length > 0 && (
              <div style={{marginBottom:12}}>
                <div className="stat-label" style={{marginBottom:8}}>Headline hazards for this county</div>
                <ol style={{margin:0, paddingLeft:0, listStyle:"none", fontSize:13, color:"var(--ink-2)", lineHeight:1.55}}>
                  {D.regional.headline_hazards.map((h, i) => {
                    const r = (h.rating || "").toLowerCase();
                    const color = r.includes("very high") ? "var(--coral)"
                                : r.includes("high") ? "var(--amber)"
                                : r.includes("moderate") ? "var(--amber)"
                                : "var(--teal)";
                    return (
                      <li key={i} style={{marginBottom:10, display:"flex", gap:10}}>
                        <span style={{
                          flexShrink:0, width:22, height:22, borderRadius:4,
                          background:color, color:"white", fontSize:12, fontWeight:600,
                          fontFamily:"'JetBrains Mono', monospace",
                          display:"flex", alignItems:"center", justifyContent:"center",
                        }}>{i+1}</span>
                        <div>
                          <strong>{h.name}</strong>
                          {h.rating && <span className="small" style={{marginLeft:6}}> · {h.rating}</span>}
                          {h.score != null && <span className="small" style={{marginLeft:6, color:"var(--ink-4)"}}> · score {h.score}</span>}
                          <div style={{color:"var(--ink-3)", fontSize:12, marginTop:2}}>{h.matters_because}</div>
                        </div>
                      </li>
                    );
                  })}
                </ol>
              </div>
            )}
            {D.regional.what_property_level_flood_misses && (
              <p style={{margin:"10px 0", padding:"10px 12px", background:"var(--bg)", borderLeft:"3px solid var(--accent)", borderRadius:4, fontSize:13, color:"var(--ink-2)", lineHeight:1.55}}>
                <strong style={{color:"var(--accent)"}}>vs property-level FEMA · </strong>{D.regional.what_property_level_flood_misses}
              </p>
            )}
            {D.regional.resilience_context && (
              <p style={{margin:"10px 0", padding:"10px 12px", background:"var(--bg)", borderLeft:"3px solid var(--teal)", borderRadius:4, fontSize:13, color:"var(--ink-2)", lineHeight:1.55}}>
                <strong style={{color:"var(--teal)"}}>Community resilience · </strong>{D.regional.resilience_context}
              </p>
            )}
            <div style={{fontSize:11, color:"var(--ink-4)", marginTop:10, fontFamily:"'JetBrains Mono', monospace"}}>
              source · FEMA National Risk Index via the Resilience Analysis and Planning Tool (RAPT)
            </div>
          </Section>
        )}

        <Section
          num={_sectionNums.signals}
          icon={<Icon name="drop" color="var(--accent)" size={16}/>}
          iconBg="var(--accent-soft)"
          title={t("section_signals")}
          defaultOpen={false}>
          {D.infra.map((s,i) => (
            <div key={i} className="stat-row">
              <span className="stat-label">{s.label}</span>
              <span className="stat-val">{s.val}{s.small && <span className="small"> · {s.small}</span>}</span>
            </div>
          ))}
        </Section>

        <Section
          num={_sectionNums.news}
          icon={<Icon name="news" color="var(--amber)" size={16}/>}
          iconBg="var(--amber-soft)"
          title={t("section_news")}>
          {D.news.length === 0 ? (
            <p style={{color:"var(--ink-3)"}}>No recent flood-related coverage surfaced for this area.</p>
          ) : D.news.map((n,i) => {
            const Inner = (
              <>
                <span className="news-date">{(n.date || "").toUpperCase()}</span>
                <span className="news-title">{n.title}</span>
                <span className="news-source">{n.source}</span>
              </>
            );
            return n.url
              ? <a key={i} className="news-row" href={n.url} target="_blank" rel="noopener noreferrer" style={{textDecoration:"none", color:"inherit"}}>{Inner}</a>
              : <div key={i} className="news-row">{Inner}</div>;
          })}
        </Section>

        <div className="method-foot">
          <strong>Methodology.</strong> Nine specialist Gemma 4 agents run in parallel. The seven data agents pull from free public APIs — FEMA NFHL for the property-level flood zone, FEMA's National Risk Index (via the RAPT ArcGIS REST endpoint) for the county-level 18-hazard profile (wildfire, hurricane, tornado, earthquake, etc.), USGS Water Services for the nearest stream gauge, NOAA NWS for the local forecast and active flood alerts, Open-Meteo for the 7-day flood + precipitation outlook, and GDELT for 6-month and 24-month flood news. In five Tier-1 cities (Chicago, NYC, SF, LA, Austin) we also pull city-specific 311 reports and recent building permits as a leading indicator of impervious-surface change; other US addresses show <code></code> for those rows but still get full NRI + FEMA + vision coverage. Two dedicated Gemma 4 vision agents independently analyze a Mapbox satellite image (bird's-eye) and a Google Street View photograph (eye-level), each producing bounding-box detections of flood indicators. A risk-analyst agent then synthesizes everything in a single Gemma 4 reasoning-mode inference call — both raw images alongside the structured findings — computing AEP and cumulative 30-year probability with P = 1 − (1 − AEP)<sup>n</sup>. An advisor agent translates the risk into verified-catalog insurance options, a before-you-sign checklist, and a bucketed drainage / infiltration / barrier action plan, in the homeowner's chosen language. All Gemma 4 calls go through the OpenRouter free tier (or a local Ollama in Edge mode); nothing about your address is stored.<br/>
          <span className="small">This is not financial or insurance advice. Confirm specifics with a licensed broker before purchasing coverage.</span>
        </div>
      </div>
    </div>
  );
};

// ── CHROME ─────────────────────────────────────────────────────────────────
const Chrome = ({ screen, onJump, dark, onToggleDark, language, onLanguageChange }) => (
  <div className="app-chrome">
    <div className="wordmark" onClick={()=>onJump("search")} style={{cursor:"pointer"}}>
      <span className="glyph">F</span>
      <span>{BRAND_NAME}</span>
      <span style={{color:"var(--ink-4)",fontSize:12,marginLeft:8,fontFamily:"JetBrains Mono"}}>v0.15.4 · beta</span>
    </div>
    <div className="chrome-meta">
      <span className="pill static"><span className="dot"/>{BRAND_PILL}</span>
      <select
        value={language}
        onChange={(e) => onLanguageChange(e.target.value)}
        title="Dossier language"
        aria-label="Dossier language"
        style={{
          height: 28, padding: "0 8px", border: "1px solid var(--line)",
          borderRadius: 6, background: "var(--surface)", color: "var(--ink-2)",
          fontSize: 12, fontFamily: "'JetBrains Mono', monospace", cursor: "pointer",
        }}
      >
        {LANGUAGES.map(l => (
          <option key={l.code} value={l.code}>
            {l.code === "en" ? l.label : `${l.native} · ${l.label}`}
          </option>
        ))}
      </select>
      <span className={"pill" + (screen === "search" ? " active" : "")} onClick={()=>onJump("search")}>search</span>
      <span className={"pill" + (screen === "agents" ? " active" : "")} onClick={()=>onJump("agents")}>agents</span>
      <span className={"pill" + (screen === "dossier" ? " active" : "")} onClick={()=>onJump("dossier")}>dossier</span>
      <button className="icon-btn" onClick={onToggleDark} aria-label="Toggle dark mode" title="Toggle dark mode">
        <Icon name={dark ? "sun" : "moon"} size={14}/>
      </button>
    </div>
  </div>
);

// ── APP ────────────────────────────────────────────────────────────────────
const App = () => {
  const [screen, setScreen] = useState("search");
  const [address, setAddress] = useState("");
  const [liveDossier, setLiveDossier] = useState(null);
  const [dark, setDark] = useState(() => {
    // Dark by default for first-time visitors; respect saved preference for returners.
    try {
      const stored = localStorage.getItem("flutiq.dark");
      if (stored === null) return true;
      return stored === "true";
    } catch { return true; }
  });
  const [language, setLanguage] = useState(() => {
    try { return localStorage.getItem("flutiq.language") || "en"; }
    catch { return "en"; }
  });

  useEffect(() => {
    document.body.classList.toggle("dark", dark);
    try { localStorage.setItem("flutiq.dark", String(dark)); } catch {}
  }, [dark]);

  useEffect(() => {
    try { localStorage.setItem("flutiq.language", language); } catch {}
  }, [language]);

  const handleSubmit = (addr) => {
    setAddress(addr);
    setLiveDossier(null);
    setScreen("agents");
  };

  const handleAgentsComplete = (dossier) => {
    setLiveDossier(dossier);
    setScreen("dossier");
  };

  return (
    <>
      <Chrome
        screen={screen}
        onJump={setScreen}
        dark={dark}
        onToggleDark={() => setDark(d => !d)}
        language={language}
        onLanguageChange={setLanguage}
      />
      {screen === "search"  && <SearchScreen onSubmit={handleSubmit}/>}
      {screen === "agents"  && <AgentsScreen address={address} language={language} dark={dark} onComplete={handleAgentsComplete} />}
      {screen === "dossier" && <DossierScreen onBack={()=>setScreen("search")} dossier={liveDossier} language={language} />}
    </>
  );
};

ReactDOM.createRoot(document.getElementById("app")).render(<App/>);
</script>
</body>
</html>