File size: 62,610 Bytes
67b65ce
 
 
 
 
 
 
 
 
610186c
67b65ce
 
e28f0e0
67b65ce
 
 
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
67b65ce
 
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
 
 
 
 
 
 
 
 
 
 
 
 
 
67b65ce
 
 
 
 
 
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b65ce
 
 
7e791d0
a0de640
7e791d0
 
 
67b65ce
9cfa8a9
7e791d0
 
 
9cfa8a9
7e791d0
 
 
9cfa8a9
67b65ce
 
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
7e791d0
67b65ce
 
 
 
7e791d0
67b65ce
 
 
7e791d0
 
67b65ce
 
7e791d0
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e791d0
 
67b65ce
7e791d0
67b65ce
 
 
7e791d0
e8111d7
694e61e
 
823e41e
e8111d7
7a1ceb6
e8111d7
823e41e
 
694e61e
 
668512e
a348946
e8111d7
 
668512e
e8111d7
668512e
 
 
 
694e61e
 
823e41e
e8111d7
1e690fd
e8111d7
823e41e
 
610186c
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75526ad
 
 
 
 
 
 
 
 
67b65ce
 
 
 
 
 
 
 
 
 
75526ad
 
67b65ce
 
 
 
 
 
 
 
1970ff7
 
 
 
67b65ce
 
 
 
 
 
 
9e19112
67b65ce
 
b21d55a
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1970ff7
 
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1970ff7
 
67b65ce
 
 
 
 
 
 
 
 
 
 
3bda5ce
67b65ce
 
 
 
 
3bda5ce
 
67b65ce
 
87be6b5
67b65ce
3bda5ce
67b65ce
 
3bda5ce
67b65ce
3bda5ce
67b65ce
 
3bda5ce
67b65ce
3bda5ce
6916b99
67b65ce
 
 
 
 
 
 
6916b99
f1b9ca7
116b3c3
f1b9ca7
 
 
116b3c3
f1b9ca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f6e150
f1b9ca7
 
 
 
 
 
ba1f06d
f1b9ca7
6f6e150
f1b9ca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b21d55a
f1b9ca7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116b3c3
f1b9ca7
 
 
 
 
 
 
 
116b3c3
f1b9ca7
 
 
 
 
 
6f6e150
f1b9ca7
 
67b65ce
f1b9ca7
8fa9c78
858fe93
f1b9ca7
 
 
 
6f6e150
f1b9ca7
 
5356abb
f1b9ca7
8fa9c78
858fe93
f1b9ca7
 
 
 
6f6e150
f1b9ca7
 
8fa9c78
f1b9ca7
8fa9c78
858fe93
f1b9ca7
 
 
 
6f6e150
f1b9ca7
 
8fa9c78
f1b9ca7
 
 
 
 
 
 
 
6f6e150
f1b9ca7
 
 
 
 
 
 
 
 
 
6f6e150
f1b9ca7
 
 
 
 
 
 
 
 
 
6f6e150
f1b9ca7
 
 
 
 
 
 
 
 
 
6f6e150
f1b9ca7
 
 
 
d136d76
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da3a740
b985caa
65db3aa
b985caa
65db3aa
 
 
 
 
 
70d0f76
b985caa
65db3aa
 
 
b21d55a
 
 
 
65db3aa
 
b985caa
65db3aa
 
 
b985caa
b21d55a
65db3aa
 
 
 
b985caa
65db3aa
b985caa
65db3aa
 
b985caa
b21d55a
b985caa
 
 
 
87be6b5
b985caa
 
 
 
 
87be6b5
b985caa
 
b21d55a
b985caa
 
 
 
87be6b5
b985caa
 
 
 
 
87be6b5
b985caa
 
65db3aa
 
 
b985caa
65db3aa
 
 
 
b985caa
87be6b5
 
b985caa
65db3aa
b985caa
b21d55a
70d0f76
b985caa
 
70d0f76
 
b21d55a
 
 
 
 
65db3aa
b21d55a
70d0f76
 
 
 
65db3aa
 
b21d55a
c498303
67b65ce
c498303
 
 
d136d76
c498303
67b65ce
b21d55a
c498303
 
 
 
 
b21d55a
 
 
c498303
 
 
 
b21d55a
 
 
 
c498303
 
 
b21d55a
c498303
b21d55a
 
c498303
 
 
 
b21d55a
 
 
c498303
 
b21d55a
c498303
b21d55a
 
 
c498303
 
b21d55a
c498303
 
 
 
 
b21d55a
c498303
b21d55a
 
 
 
c498303
 
 
b21d55a
c498303
b21d55a
c498303
 
b21d55a
c498303
b21d55a
 
 
 
c498303
b21d55a
c498303
b21d55a
c498303
 
3b082f2
b21d55a
c498303
b21d55a
c498303
 
b21d55a
 
 
 
 
 
 
 
 
c498303
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c498303
b21d55a
 
 
 
 
 
 
 
 
c498303
b21d55a
67b65ce
c498303
67b65ce
b21d55a
c498303
67b65ce
b21d55a
67b65ce
c498303
 
 
 
b21d55a
 
 
c498303
 
 
 
b21d55a
 
 
 
c498303
 
 
b21d55a
c498303
b21d55a
 
c498303
 
 
 
 
b21d55a
c498303
 
 
 
 
b21d55a
 
 
c498303
 
b21d55a
c498303
 
 
 
 
 
b21d55a
 
 
 
c498303
 
 
b21d55a
c498303
b21d55a
c498303
 
b21d55a
c498303
b21d55a
 
 
 
c498303
b21d55a
c498303
b21d55a
67b65ce
c498303
67b65ce
b21d55a
c498303
b21d55a
c498303
 
b21d55a
 
 
 
 
 
 
 
c498303
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c498303
b21d55a
 
 
 
 
 
 
 
 
c498303
b21d55a
67b65ce
c498303
67b65ce
3b082f2
c498303
b21d55a
c498303
 
 
b21d55a
 
c498303
 
 
b21d55a
c498303
 
b21d55a
 
 
 
 
 
 
 
3b082f2
67b65ce
 
b21d55a
 
67b65ce
 
 
c498303
63fa9ef
 
67b65ce
b21d55a
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
63fa9ef
b21d55a
 
 
 
 
67b65ce
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b21d55a
67b65ce
 
 
63fa9ef
b21d55a
67b65ce
 
 
 
 
 
 
 
 
 
 
 
 
 
b21d55a
 
67b65ce
b21d55a
67b65ce
 
 
63fa9ef
67b65ce
 
b21d55a
67b65ce
b21d55a
 
 
 
67b65ce
 
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
67b65ce
b21d55a
67b65ce
b21d55a
67b65ce
 
 
b21d55a
 
67b65ce
 
 
b21d55a
3b082f2
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fd793
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1392a3
 
 
 
b21d55a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f38e51e
 
 
 
 
 
 
 
b21d55a
67b65ce
f38e51e
85eab2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b21d55a
f38e51e
 
54c6593
f38e51e
54c6593
b21d55a
f38e51e
 
54c6593
 
 
 
 
f38e51e
54c6593
b21d55a
f38e51e
85eab2b
 
 
 
 
 
 
 
67b65ce
54c6593
 
 
 
 
 
 
 
 
 
67b65ce
 
6916b99
54c6593
67b65ce
 
94bc213
 
 
e8111d7
e71807d
e8111d7
e71807d
e8111d7
e71807d
e8111d7
e71807d
e8111d7
491c8e6
e8111d7
94bc213
823e41e
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
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import folium
from streamlit_folium import st_folium
from sklearn.linear_model import LinearRegression
import os 
# ================= CONFIG =================
st.set_page_config(
    page_title="Michelin Mining Tyre Analytics",
    page_icon="",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ================= CUSTOM CSS 
st.markdown("""
<style>
/* ================= ROOT & COLORS ================= */
:root {
    --michelin-blue: #003A8F;
    --surface: #FFFFFF;
    --surface-alt: #F9FAFB;
    --text-dark: #1F2D3D;
    --text-muted: #6C757D;
    --border: #E9ECEF;
    --shadow-sm: 0 2px 6px rgba(0,0,0,0.04);
    --shadow: 0 6px 16px rgba(0,0,0,0.06);
    --accent-yellow: #FFD100;
    --filter-bg: #F5F7FA;
}

/* ================= GLOBAL TYPOGRAPHY & ALIGNMENT ================= */
.stApp {
    background-color: var(--surface);
    font-family: 'Segoe UI', system-ui, sans-serif;
    color: var(--text-dark);
}

/* Force center alignment for ALL headings */
h1, h2, h3, h4, h5, h6,
.stMarkdown, .stText, p, div[data-testid="stMarkdownContainer"],
label, .stSelectbox label, .stMultiselect label, .stCheckbox label {
    text-align: center !important;
}

/* Fix bullet/number list centering */
.stMarkdown ul, .stMarkdown ol {
    text-align: left !important;
    margin-left: auto;
    margin-right: auto;
    max-width: 800px;
}

/* ================= SIDEBAR (Power BI Style) ================= */
[data-testid="stSidebar"] {
    background: var(--filter-bg) !important;
    color: var(--text-dark);
    padding: 20px 12px;
}

[data-testid="stSidebar"] h3 {
    color: var(--michelin-blue);
    font-weight: 700;
    margin-bottom: 12px;
}

/* Power BI-style dropdowns */
[data-testid="stSelectbox"] div[data-baseweb="select"],
[data-testid="stMultiselect"] div[data-baseweb="select"] {
    background-color: white !important;
    border-radius: 8px !important;
    border: 1px solid var(--border) !important;
    box-shadow: var(--shadow-sm);
    padding: 6px 10px !important;
    min-height: 40px !important;
}

[data-testid="stSelectbox"] div[data-baseweb="select"] > div,
[data-testid="stMultiselect"] div[data-baseweb="select"] > div {
    color: var(--text-dark) !important;
    font-weight: 500;
}

/* Remove red tags from multiselect */
[data-testid="stMultiselect"] div[data-baseweb="select"] .stMultiSelectTag {
    display: none !important;
}

/* Submit button */
[data-testid="stSidebar"] .stButton > button {
    width: 100%;
    background: var(--accent-yellow);
    color: var(--michelin-blue);
    font-weight: 700;
    border-radius: 10px;
    padding: 12px 0;
    margin-top: 16px;
    box-shadow: var(--shadow);
    border: none;
    font-size: 1.05rem;
}
[data-testid="stSidebar"] .stButton > button:hover {
    background: #FFC107;
    transform: translateY(-1px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.12);
}

/* ================= HEADER ================= */
.main-header h1 {
    font-size: 2.4rem;
    margin-bottom: 6px;
    font-weight: 800;
    color: var(--michelin-blue);
}
.main-header p {
    font-size: 1.15rem;
    color: var(--text-muted);
    margin-top: 0;
}

/* ================= OBJECTIVE TITLE (NO BACKGROUND BOX) ================= */
.objective-title {
    text-align: center !important;
    font-size: 1.6rem;
    font-weight: 800;
    color: var(--michelin-blue);
    margin: 40px 0 24px 0;
}

/* ================= INSIGHT LLM-STYLE (Like Screenshot) ================= */
.insight-box {
    background: var(--surface-alt);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 20px;
    box-shadow: var(--shadow-sm);
    margin: 20px 0 30px 0;
    position: relative;
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.insight-box .content {
    flex: 1;
    font-size: 1.05rem;
    line-height: 1.65;
    color: var(--text-dark);
    text-align: left;
}

.insight-box .tag {
    position: absolute;
    top: 12px;
    right: 16px;
    background: var(--michelin-blue);
    color: white;
    font-size: 0.85rem;
    font-weight: 700;
    padding: 6px 12px;
    border-radius: 8px;
    letter-spacing: 0.5px;
}

/* ================= PLOTLY ================= */
.plotly-graph-div {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: var(--shadow-sm);
    border: 1px solid var(--border);
}

/* ================= FOOTER ================= */
.footer {
    text-align: center;
    font-size: 0.9rem;
    color: var(--text-muted);
    margin-top: 50px;
    padding: 20px 0;
    border-top: 1px solid var(--border);
}

/* ================= STREAMLIT TWEAKS ================= */
div.block-container {
    padding-top: 2rem;
}
section[data-testid="stSidebar"] {
    width: 280px !important;
    min-width: 280px !important;
}
</style>
""", unsafe_allow_html=True)


# ================= LOAD DATA =================
@st.cache_data
def load_data():
    try:
        df = pd.read_excel("df_final.xlsx", sheet_name="Sheet1")
    except FileNotFoundError:
        st.error("❌ File `df_final.xlsx` not found. Please ensure it's in the same directory.")
        st.stop()
    
    # Fix encoding (e.g., '°C' β†’ 'Β°C')
    df.columns = df.columns.str.replace("Γ‚", "")
    for col in df.select_dtypes(include='object').columns:
        df[col] = df[col].astype(str).str.replace("Γ‚", "")
    
    # Parse datetime
    df['Time'] = pd.to_datetime(df['Time'], errors='coerce')
    df = df.dropna(subset=['Time'])
    df['hour'] = df['Time'].dt.hour
    
    # Alarm flag
    df['is_alarm'] = (~df['Alarm Status'].str.contains('No Alarm', na=False)).astype(int)
    
    # Dynamic risk score
    p = df['Pressure (psi)']
    p_red_high = df['Red High Press (psi)']
    p_amber_high = df['Amber High Press (psi)']
    t = df['Temperature (Β°C)']
    t_red = df['Absolute Red Temp (Β°C)']
    t_amber = df['Absolute Amber Temp (Β°C)']
    
    p_norm = np.clip((p - p_amber_high) / (p_red_high - p_amber_high), 0, 1)
    t_norm = np.clip((t - t_amber) / (t_red - t_amber), 0, 1)
    df['risk_score'] = 0.6 * p_norm + 0.4 * t_norm
    
    def get_risk_label(score):
        if score >= 0.8: return 'Very High Risk'
        elif score >= 0.6: return 'High Risk'
        elif score >= 0.3: return 'Moderate Risk'
        else: return 'Slight Risk'
    df['Risk Level'] = df['risk_score'].apply(get_risk_label)
    
    # Add Position Group
    df['Position Group'] = df['Position'].apply(lambda x: 'Front' if x in [1, 2] else 'Rear')
    
    return df

df = load_data()

col1, col2, col3 = st.columns([1.5, 6, 1.5])  # Increased side column width

with col1:
    st.markdown("""
    <div style="display:flex; align-items:center; justify-content:center; height:100%; padding:5px;">
        <img src="https://huggingface.co/spaces/bukittechnology/tyre/resolve/main/btech2.png"
             style="max-width:120px; height:auto; object-fit:contain;">
    </div>
    """, unsafe_allow_html=True)

with col2:
    st.markdown("""
    <div style="text-align:center; font-family:Arial, sans-serif; padding:2px 0;">
        <h1 style="color:#154D9C; font-weight:bold; margin:0; line-height:1.3;">
            Tyre Pressure Monitoring System (TPMS) Analytics<br>for Mining Equipments
        </h1>
        <p style="font-size:12px; color:#7d7d7d; margin:8px 0 0 0;">
            Daily trend insights derived from 13–16 December 2023 data
        </p>
    </div>
    """, unsafe_allow_html=True)

with col3:
    st.markdown("""
    <div style="display:flex; align-items:center; justify-content:center; height:100%; padding:5px;">
        <img src="https://huggingface.co/spaces/bukittechnology/tyre/resolve/main/logo.png"
             style="max-width:120px; height:auto; object-fit:contain;">
    </div>
    """, unsafe_allow_html=True)

# ================= SIDEBAR FILTERS =================
with st.sidebar:
    st.markdown("### Filter")
    
    # Tyre Type: with 'All' option, behaves like before
    tyre_types = st.selectbox(
        "Tyre Type", options=['All'] + sorted(df['Tyre Type'].dropna().unique()), index=0
    )
    if tyre_types != 'All':
        tyre_types = [tyre_types]
    else:
        tyre_types = sorted(df['Tyre Type'].dropna().unique())

    # Date: behaves like Tyre Type β€” show 'All' by default
    date_options = sorted(df['date'].astype(str).unique())
    dates_selected = st.selectbox(
        "Date", options=['All'] + date_options, index=0
    )
    if dates_selected != 'All':
        dates = [dates_selected]
    else:
        dates = date_options

    # Zone: behaves like Tyre Type β€” show 'All' by default
    zone_options = sorted(df['Zone'].dropna().unique())
    zones_selected = st.selectbox(
        "Zone", options=['All'] + zone_options, index=0
    )
    if zones_selected != 'All':
        zones = [zones_selected]
    else:
        zones = zone_options

    # Position: behaves like Tyre Type β€” show 'All' by default
    pos_options = sorted(df['Position'].astype(int).dropna().unique())
    positions_selected = st.selectbox(
        "Position", options=['All'] + pos_options, index=0
    )
    if positions_selected != 'All':
        positions = [positions_selected]
    else:
        positions = pos_options

    # Alarm Status: behaves like Tyre Type β€” show 'All' by default
    alarm_options = ["No Alarm", "Red High Pressure"]
    alarms_selected = st.selectbox(
        "Alarm Status", options=['All'] + alarm_options, index=0
    )
    if alarms_selected != 'All':
        alarms = [alarms_selected]
    else:
        alarms = alarm_options

    # Jam: Slider jam (00:00–23:00)
    jam_range = st.slider(
        "Jam", 
        min_value=0, 
        max_value=23, 
        value=(0, 23),  # Default: semua jam
        format="%02d:00"
    )

    submit = st.button("Submit")

# Apply filters
if submit:
    dff = df.copy()
    if dates: dff = dff[dff['date'].astype(str).isin(dates)]
    if zones: dff = dff[dff['Zone'].isin(zones)]
    if positions: dff = dff[dff['Position'].astype(int).isin(positions)]
    if tyre_types: dff = dff[dff['Tyre Type'].isin(tyre_types)]
    if alarms: dff = dff[dff['Alarm Status'].isin(alarms)]
    # Tambahkan filter jam
    dff = dff[dff['hour'].between(jam_range[0], jam_range[1], inclusive='both')]
else:
    dff = df

dff = dff.copy()
dff['Position'] = pd.Categorical(dff['Position'], categories=[1, 2, 3, 4], ordered=True)

# Optional: Use descriptive labels (if desired)
position_labels = {
    1: '1: Front 1', 
    2: '2: Front 2', 
    3: '3: Rear 3', 
    4: '4: Rear 4'
}
# Or keep as just '1', '2'... if minimal
# position_labels = {1: '1', 2: '2', 3: '3', 4: '4'}
dff['Position_Label'] = dff['Position'].map(position_labels)

st.markdown('<h3 class="objective-title">OBJECTIVE 1: Pressure & Temperature Trends β€” How Do Front and Rear Tyres Distribute?</h3>', unsafe_allow_html=True)

col2, col1 = st.columns(2)

# Define consistent color mapping
color_map = {1: '#003DA5', 2: '#7FA6E8', 3: '#3F7F73', 4: '#8EC3B7'}
category_order = [1, 2, 3, 4]

with col1:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Pressure Distribution per Tyre Position</h5>', unsafe_allow_html=True)
    fig1 = px.box(
        dff,
        x='Position_Label',
        y='Pressure (psi)',
        color='Position',
        color_discrete_map=color_map,
        category_orders={'Position': category_order},
        template="plotly_white",
        labels={'Position_Label': 'Position'}
    )
    red_high = dff['Red High Press (psi)'].min()
    amber_high = dff['Amber High Press (psi)'].min()
    # fig1.add_hline(y=red_high, line_dash="dash", line_color="red", annotation_text="Red High Press", annotation_position="top right")
    # fig1.add_hline(y=amber_high, line_color="orange", annotation_text="Amber High Press", annotation_position="bottom right")
    fig1.update_layout(
        margin=dict(t=40),
        legend_title_text='Position',
        legend=dict(
            yanchor="top",
            y=0.99,
            xanchor="left",
            x=1.02  # Place legend outside plot to avoid overlap
        )
    )
    st.plotly_chart(fig1, use_container_width=True)

with col2:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Temperature Distribution per Tyre Position</h5>', unsafe_allow_html=True)
    fig2 = px.box(
        dff,
        x='Position_Label',
        y='Temperature (Β°C)',
        color='Position',
        color_discrete_map=color_map,
        category_orders={'Position': category_order},
        template="plotly_white",
        labels={'Position_Label': 'Position'}
    )
    red_temp = dff['Absolute Red Temp (Β°C)'].min()
    amber_temp = dff['Absolute Amber Temp (Β°C)'].min()
    # fig2.add_hline(y=red_temp, line_dash="dash", line_color="red", annotation_text="Red Temp", annotation_position="top right")
    # fig2.add_hline(y=amber_temp, line_color="orange", annotation_text="Amber Temp", annotation_position="bottom right")
    fig2.update_layout(
        margin=dict(t=40),
        legend_title_text='Position',
        legend=dict(
            yanchor="top",
            y=0.99,
            xanchor="left",
            x=1.02
        )
    )
    st.plotly_chart(fig2, use_container_width=True)
# Insight 1 β€” Fisika & Mekanikal
front_pressure_avg = dff[dff['Position'].isin([1, 2])]['Pressure (psi)'].mean()
rear_pressure_avg = dff[dff['Position'].isin([3, 4])]['Pressure (psi)'].mean()
front_temp_avg = dff[dff['Position'].isin([1, 2])]['Temperature (Β°C)'].mean()
rear_temp_avg = dff[dff['Position'].isin([3, 4])]['Temperature (Β°C)'].mean()

# Fisika: Tekanan rendah β†’ deformasi besar β†’ hysteresis β†’ panas lebih banyak
# Mekanikal: Ban depan tanggung beban pengereman & kemudi β†’ stres lebih tinggi
if front_pressure_avg < rear_pressure_avg and front_temp_avg > rear_temp_avg:
    insight_text = f"""
Rear tyres have higher pressure because they have higher specifications (10.00 R20 vs 11.00 R20)
"""

elif front_pressure_avg > rear_pressure_avg and front_temp_avg < rear_temp_avg:
    insight_text = f"""
Front tyres: Higher pressure ({front_pressure_avg:.1f} psi) reduces deformation, lower heat ({front_temp_avg:.1f}Β°C), less mechanical stress. Rear tyres: Lower pressure ({rear_pressure_avg:.1f} psi) increases deformation, higher heat ({rear_temp_avg:.1f}Β°C) potential overloading or misalignment.
"""

else:
    insight_text = f"""
Front tyres: Pressure {front_pressure_avg:.1f} psi, temperature {front_temp_avg:.1f}Β°C β†’ stable under current load/pressure balance. Rear tyres: Pressure {rear_pressure_avg:.1f} psi, temperature {rear_temp_avg:.1f}Β°C β†’ balanced operation.
"""


st.markdown(f"""
<div class="insight-box">
    <div class="content">
{insight_text.strip()}
    </div>
</div>
""", unsafe_allow_html=True)

####obejctic=ve 2

st.markdown("""
<h3 class="objective-title">OBJECTIVE 2: Shift and Tyre Position - How Are Alarms Concentrated Across Shifts and Tyres?</h3>
""", unsafe_allow_html=True)

# Filter semua data (termasuk alarm normal)
alarm_data = dff.copy()

# Buat 2 baris Γ— 4 kolom
col1, col2, col3, col4 = st.columns(4)
col5, col6, col7, col8 = st.columns(4)

# Fungsi helper untuk membuat radial chart per posisi dan shift
def create_radial_chart(pos_data, title, shift_hours, shift_type):
    if pos_data.empty:
        return None

    # Kelompokkan jam dan status
    hourly_status_counts = pos_data.groupby(['hour', 'Alarm Status']).size().unstack(fill_value=0)

    # Klasifikasi berdasarkan kata kunci
    hourly_normal = hourly_status_counts.get('No Alarm', pd.Series(0, index=shift_hours)).reindex(shift_hours, fill_value=0)
    hourly_amber = hourly_status_counts.filter(regex='Amber').sum(axis=1).reindex(shift_hours, fill_value=0)  # Semua yang mengandung "Amber"
    hourly_red = hourly_status_counts.filter(regex='Red').sum(axis=1).reindex(shift_hours, fill_value=0)      # Semua yang mengandung "Red"

    # Total per jam
    total_per_hour = hourly_normal + hourly_amber + hourly_red

    # Sudut: sesuaikan agar jam 12 di bawah (180Β°), jam 6 di kanan (90Β°), jam 3 di atas (0Β°), jam 9 di kiri (270Β°)
    if shift_type == 'pagi':
        # Shift Pagi (06:00–18:00) β†’ 0Β° = 03:00, 90Β° = 06:00, 180Β° = 12:00, 270Β° = 18:00
        theta = [(h - 3) * 30 for h in shift_hours]  # 12 jam * 30Β° = 360Β°
        tickvals = [0, 90, 180, 270]
        ticktext = ["15:00", "06:00/18:00", "09:00", "12:00"]
    else:  # Shift Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
        # Shift Sore (18:00–06:00) β†’ 0Β° = 21:00, 90Β° = 00:00, 180Β° = 06:00, 270Β° = 12:00
        # Tapi karena ingin ikut aturan pagi, kita mapping jam agar 0Β° = 03:00, 90Β° = 06:00, 180Β° = 12:00, 270Β° = 18:00
        # Maka kita gunakan jam pagi (06:00–18:00) sebagai referensi jam, tapi data diambil dari sore (18:00–06:00)
        # Kita mapping: 18->06, 19->07, ..., 23->11, 00->12, 01->13, ..., 05->17
        # Maka: theta = [(mapped_h - 3) * 30] where mapped_h = h + 12 if h < 6 else h - 12
        theta =  [(h - 3) * 30 for h in shift_hours]# 12 jam * 30Β° = 360Β°
        tickvals = [0, 90, 180, 270]
        ticktext = ["03:00", "18:00/06:00", "21:00", "00:00"]

    fig = go.Figure()

    # Tambahkan trace untuk masing-masing kategori dengan hovertemplate custom
    fig.add_trace(go.Barpolar(
        r=hourly_normal.values,
        theta=theta,
        name='Normal',
        marker_color='#2E7D32',  # Hijau
        opacity=0.8,
        hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Normal<extra></extra>',
        customdata=shift_hours
    ))
    fig.add_trace(go.Barpolar(
        r=hourly_amber.values,
        theta=theta,
        name='Amber',
        marker_color='#FFBF00',  # Kuning
        opacity=0.8,
        hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Amber<extra></extra>',
        customdata=shift_hours
    ))
    fig.add_trace(go.Barpolar(
        r=hourly_red.values,
        theta=theta,
        name='Red',
        marker_color='#D32F2F',  # Merah
        opacity=0.8,
        hovertemplate='<b>Hour:</b> %{customdata}:00<br><b>Count:</b> %{r}<br><b>Status:</b> Red<extra></extra>',
        customdata=shift_hours
    ))

    fig.update_layout(
        polar=dict(
            angularaxis=dict(
                direction="clockwise",
                period=len(shift_hours),
                rotation=0,
                tickvals=tickvals,
                ticktext=ticktext,
                tickfont=dict(size=12)
            ),
            radialaxis=dict(
                visible=True,
                range=[0, max(total_per_hour.max() * 1.1, 1)]
            )
        ),
        showlegend=False,
        margin=dict(t=30, b=20, l=20, r=20),
        height=250,
        title_text=title,
        title_x=0.5
    )
    return fig

# =============== ROW 1: Position 1 & 2 (Pagi & Sore) ===============
with col1:
    # Position 1 Pagi (06:00–18:00)
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 1 (06:00–18:00)</div>', unsafe_allow_html=True)
    pos1_data = alarm_data[alarm_data['Position'] == 1].copy()
    pos1_data = pos1_data[pos1_data['hour'].between(6, 17, inclusive='both')]
    fig1 = create_radial_chart(pos1_data, "", list(range(6, 18)), 'pagi')
    if fig1 is not None:
        st.plotly_chart(fig1, use_container_width=True)
    else:
        st.warning("No data for Position 1 (06:00–18:00)")

with col2:
    # Position 1 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 1 (18:00–06:00)</div>', unsafe_allow_html=True)
    pos1_data = alarm_data[alarm_data['Position'] == 1].copy()
    pos1_data = pos1_data[~pos1_data['hour'].between(6, 17, inclusive='both')]
    fig2 = create_radial_chart(pos1_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
    if fig2 is not None:
        st.plotly_chart(fig2, use_container_width=True)
    else:
        st.warning("No data for Position 1 (18:00–06:00)")

with col3:
    # Position 2 Pagi (06:00–18:00)
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 2 (06:00–18:00)</div>', unsafe_allow_html=True)
    pos2_data = alarm_data[alarm_data['Position'] == 2].copy()
    pos2_data = pos2_data[pos2_data['hour'].between(6, 17, inclusive='both')]
    fig3 = create_radial_chart(pos2_data, "", list(range(6, 18)), 'pagi')
    if fig3 is not None:
        st.plotly_chart(fig3, use_container_width=True)
    else:
        st.warning("No data for Position 2 (06:00–18:00)")

with col4:
    # Position 2 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 2 (18:00–06:00)</div>', unsafe_allow_html=True)
    pos2_data = alarm_data[alarm_data['Position'] == 2].copy()
    pos2_data = pos2_data[~pos2_data['hour'].between(6, 17, inclusive='both')]
    fig4 = create_radial_chart(pos2_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
    if fig4 is not None:
        st.plotly_chart(fig4, use_container_width=True)
    else:
        st.warning("No data for Position 2 (18:00–06:00)")

# =============== ROW 2: Position 3 & 4 (Pagi & Sore) ===============
with col5:
    # Position 3 Pagi (06:00–18:00)
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 3 (06:00–18:00)</div>', unsafe_allow_html=True)
    pos3_data = alarm_data[alarm_data['Position'] == 3].copy()
    pos3_data = pos3_data[pos3_data['hour'].between(6, 17, inclusive='both')]
    fig5 = create_radial_chart(pos3_data, "", list(range(6, 18)), 'pagi')
    if fig5 is not None:
        st.plotly_chart(fig5, use_container_width=True)
    else:
        st.warning("No data for Position 3 (06:00–18:00)")

with col6:
    # Position 3 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 3 (18:00–06:00)</div>', unsafe_allow_html=True)
    pos3_data = alarm_data[alarm_data['Position'] == 3].copy()
    pos3_data = pos3_data[~pos3_data['hour'].between(6, 17, inclusive='both')]
    fig6 = create_radial_chart(pos3_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
    if fig6 is not None:
        st.plotly_chart(fig6, use_container_width=True)
    else:
        st.warning("No data for Position 3 (18:00–06:00)")

with col7:
    # Position 4 Pagi (06:00–18:00)
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 4 (06:00–18:00)</div>', unsafe_allow_html=True)
    pos4_data = alarm_data[alarm_data['Position'] == 4].copy()
    pos4_data = pos4_data[pos4_data['hour'].between(6, 17, inclusive='both')]
    fig7 = create_radial_chart(pos4_data, "", list(range(6, 18)), 'pagi')
    if fig7 is not None:
        st.plotly_chart(fig7, use_container_width=True)
    else:
        st.warning("No data for Position 4 (06:00–18:00)")

with col8:
    # Position 4 Sore (18:00–06:00) β€” TAPI ikuti aturan jam seperti pagi
    st.markdown('<div style="text-align:center; font-weight:bold; margin-bottom: 8px;">Position 4 (18:00–06:00)</div>', unsafe_allow_html=True)
    pos4_data = alarm_data[alarm_data['Position'] == 4].copy()
    pos4_data = pos4_data[~pos4_data['hour'].between(6, 17, inclusive='both')]
    fig8 = create_radial_chart(pos4_data, "", list(range(18, 24)) + list(range(0, 6)), 'sore')
    if fig8 is not None:
        st.plotly_chart(fig8, use_container_width=True)
    else:
        st.warning("No data for Position 4 (18:00–06:00)")

def generate_objective2_insights(df: pd.DataFrame) -> str:
    """
    Generate dynamic, line-by-line insight for Objective 2.
    Input: filtered DataFrame (e.g., by site/year/hour β€” already applied upstream)
    Output: formatted string with <br> for newline (left-aligned, clean)
    """
    # Filter hanya Red & Amber alarms
    alarm_df = df[df['alarm_severity'].isin(['Red', 'Amber'])].copy()
    
    if alarm_df.empty:
        return "β€’ No Red or Amber alarms in selected period."

    # === 1. Total counts ===
    total_red = alarm_df[alarm_df['alarm_severity'] == 'Red'].shape[0]
    total_amber = alarm_df[alarm_df['alarm_severity'] == 'Amber'].shape[0]
    total_combined = total_red + total_amber

    # === 2. Dominant period (custom bins) ===
    def get_period(hour):
        if 12 <= hour < 18:
            return '12:00–18:00'
        elif 18 <= hour < 24 or hour == 0:  # include 00:00 as part of night
            return '18:00–00:00'
        else:
            return 'Other'
    
    alarm_df['period'] = alarm_df['hour'].apply(get_period)
    
    period_counts = alarm_df['period'].value_counts()
    dominant_period = period_counts.idxmax()
    dominant_pct = period_counts.max() / total_combined * 100
    
    # Second-dominant
    if len(period_counts) > 1:
        second_period = period_counts.index[1]
        second_pct = period_counts.iloc[1] / total_combined * 100
    else:
        second_period = 'β€”'
        second_pct = 0.0

    # === 3. Peak per Position + Period + Severity ===
    # We'll find peak hour within each (Position, period, severity) group
    peaks = []
    for pos in [1, 2, 3, 4]:
        for period in ['12:00–18:00', '18:00–00:00']:
            for sev in ['Red', 'Amber']:
                subset = alarm_df[
                    (alarm_df['Position'] == pos) &
                    (alarm_df['period'] == period) &
                    (alarm_df['alarm_severity'] == sev)
                ]
                if not subset.empty:
                    peak_hour = subset['hour'].mode().iloc[0]  # most frequent hour
                    peak_count = (subset['hour'] == peak_hour).sum()
                    # Format hour to 00:00 (0 β†’ 00:00, 23 β†’ 23:00, but 0 in 18–00 group = 00:00)
                    display_hour = f"{int(peak_hour):02d}:00"
                    peaks.append((pos, period, sev, display_hour, peak_count))

    # Build insight lines
    lines = [
        f"β€’ Dominant period for Red/Amber: {dominant_period} β€” {dominant_pct:.2f}%",
        f"β€’ Second-dominant period: {second_period} β€” {second_pct:.2f}%"
    ]

    # Add peak lines (only top patterns β€” limit to meaningful ones)
    for pos, period, sev, hr, cnt in sorted(peaks, key=lambda x: (-x[4], x[0], x[1])):
        if cnt >= 10:  # only show peaks with β‰₯10 occurrences (avoid noise)
            lines.append(f"β€’ Position {pos}, {period}: Peak {sev} alarm at {hr} ({cnt:,} occurrences)")

    return "<br>".join(lines)


# === RENDER INSIGHT BOX ===
# =============== INSIGHT 2 (Ringkas & Fokus ke Red & Amber) ===============
# =============== INSIGHT 3 (Rata kiri, sesuai preferensi Aning) ===============

# β€”β€”β€”β€”β€” Validasi data β€”β€”β€”β€”β€”
required_cols = {'Alarm Status', 'hour', 'Position'}
if not required_cols.issubset(alarm_data.columns) or alarm_data.empty:
    insight_lines = [
        "β€’ No alarm data available for Red or Amber analysis.",
        "β€’ Ensure dataset includes 'Alarm Status', 'hour', and 'Position' columns."
    ]
else:
    # Filter Red & Amber β€” case-insensitive, robust terhadap NaN
    mask_red = alarm_data['Alarm Status'].str.contains(r'\bRed\b', case=False, na=False)
    mask_amber = alarm_data['Alarm Status'].str.contains(r'\bAmber\b', case=False, na=False)
    red_amber_data = alarm_data[mask_red | mask_amber].copy()

    if red_amber_data.empty:
        insight_lines = ["β€’ No Red or Amber alarms detected in the dataset."]
    else:
        insight_lines = []

        # Tambahkan flag
        red_amber_data['is_red'] = mask_red.loc[red_amber_data.index]
        red_amber_data['is_amber'] = mask_amber.loc[red_amber_data.index]

        # Loop tiap posisi roda (1–4)
        for pos in [1, 2, 3, 4]:
            pos_data = red_amber_data[red_amber_data['Position'] == pos]
            if pos_data.empty:
                continue

            # Band 1: 12:00–18:00 (siang/sore)
            band1 = pos_data[(pos_data['hour'] >= 12) & (pos_data['hour'] <= 17)]
            # Band 2: 18:00–00:00 (sore/malam/dini hari)
            band2 = pos_data[(pos_data['hour'] >= 18) | (pos_data['hour'] <= 5)]

            # β€” Band 1 β€”
            if not band1.empty:
                red_sub = band1[band1['is_red']]
                if not red_sub.empty:
                    h_peak = int(red_sub['hour'].value_counts().idxmax())
                    c_peak = int(red_sub['hour'].value_counts().max())
                    insight_lines.append(f"β€’ Position {pos}, 06:00–18:00 (Day Shift): Peak Red alarm at {h_peak:02d}:00 ({c_peak} occurrences).")

                amber_sub = band1[band1['is_amber']]
                if not amber_sub.empty:
                    h_peak = int(amber_sub['hour'].value_counts().idxmax())
                    c_peak = int(amber_sub['hour'].value_counts().max())
                    insight_lines.append(f"β€’ Position {pos}, 06:00–18:00 (Day Shift): Peak Amber alarm at {h_peak:02d}:00 ({c_peak} occurrences).")

            # β€” Band 2 β€”
            if not band2.empty:
                red_sub = band2[band2['is_red']]
                if not red_sub.empty:
                    h_peak = int(red_sub['hour'].value_counts().idxmax())
                    c_peak = int(red_sub['hour'].value_counts().max())
                    insight_lines.append(f"β€’ Position {pos}, 18:00–06:00 (Night Shift): Peak Red alarm at {h_peak:02d}:00 ({c_peak} occurrences).")

                amber_sub = band2[band2['is_amber']]
                if not amber_sub.empty:
                    h_peak = int(amber_sub['hour'].value_counts().idxmax())
                    c_peak = int(amber_sub['hour'].value_counts().max())
                    insight_lines.append(f"β€’ Position {pos}, 18:00–06:00 (Night Shift): Peak Amber alarm at {h_peak:02d}:00 ({c_peak} occurrences).")

        # Jika tidak ada alarm di posisi 1–4
        if not insight_lines:
            insight_lines = ["β€’ Red and Amber alarms occur outside standard wheel positions (1–4)."]

# β€”β€”β€”β€”β€” Tambahkan insight naratif (sesuai contoh Anda) β€”β€”β€”β€”β€”
has_front_red = not red_amber_data[(red_amber_data['Position'].isin([1, 2])) & (red_amber_data['is_red'])].empty
has_rear_amber = not red_amber_data[(red_amber_data['Position'].isin([3, 4])) & (red_amber_data['is_amber'])].empty

if has_front_red or has_rear_amber:
    insight_lines.extend([
        "β€’ The front tyre pressure is closed to upper threshold before equipment is being operated. It is shown by small number of red alarms in the early day shift and increase as being operated. Furthermore, during 04:00–06:00, red alarm decrease and it is likely due to operational slowdown.",
        "β€’ In contrast, for rear tyres, notifications often indicate pressure below the lower threshold. As a result, amber alarms frequently occur early in the shift and return to normal as the tyres warm up during operation."
    ])

# Gabungkan jadi satu string, tiap baris baru β†’ \n
insight_text = "\n".join(insight_lines)

# β€”β€”β€”β€”β€” TAMPILKAN (RATA KIRI) β€”β€”β€”β€”β€”
st.markdown('<h4 style="text-align:center; margin:10px 0 5px 0; font-weight:bold;">INSIGHTS</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
    <div class="content" style="
        text-align: left;
        white-space: pre-line;
        font-family: 'Segoe UI', sans-serif;
        line-height: 1.6;
        font-size: 0.95em;
    ">
{insight_text}
    </div>
</div>
""", unsafe_allow_html=True)

### OBJECTICVE 3
# ================= OBJECTIVE 3 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 3: Correlation β€” How Does Heat Influence Pressure and Which Tyres Trigger Red Alarms?</h3>', unsafe_allow_html=True)

# Prepare data
front_df = dff[dff['Position'].isin([1, 2])].copy()
rear_df = dff[dff['Position'].isin([3, 4])].copy()

col1, col2 = st.columns(2)

# =============== COL 1: Front β€” Temp β†’ Pressure ===============
with col1:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Front Tyres: Temperature β†’ Pressure</h5>', unsafe_allow_html=True)
    
    if not front_df.empty:
        front_df['Category'] = front_df.apply(
            lambda row: "Normal Front Tyre" if row['Alarm Status'] == 'No Alarm'
            else "Amber Pressure Front Tyre" if 'Amber' in str(row['Alarm Status'])
            else "Red Pressure Front Tyre", axis=1
        )
        categories = ["Normal Front Tyre", "Amber Pressure Front Tyre", "Red Pressure Front Tyre"]
        front_df['Category'] = pd.Categorical(front_df['Category'], categories=categories, ordered=True)

        valid = front_df.dropna(subset=['Temperature (Β°C)', 'Pressure (psi)'])
        if len(valid) > 1:
            X = valid[['Temperature (Β°C)']].values
            y = valid['Pressure (psi)'].values
            model = LinearRegression().fit(X, y)
            x_line = np.linspace(X.min(), X.max(), 100).reshape(-1, 1)
            y_line = model.predict(x_line)
            corr = np.corrcoef(valid['Temperature (Β°C)'], valid['Pressure (psi)'])[0, 1]

            fig = px.scatter(
                valid,
                x='Temperature (Β°C)',
                y='Pressure (psi)',
                color='Category',
                color_discrete_map={
                    "Normal Front Tyre": "#2E7D32",
                    "Amber Pressure Front Tyre": "#FFBF00",
                    "Red Pressure Front Tyre": "#D32F2F"
                },
                category_orders={'Category': categories},
                template="plotly_white"
            )
            fig.update_traces(
                hovertemplate="<b>%{customdata[0]}</b><br>Temp: %{x:.1f}Β°C<br>Pressure: %{y:.1f} psi<extra></extra>",
                customdata=valid[['Category']].values,
                marker=dict(size=6)
            )
            fig.add_trace(go.Scatter(
                x=x_line.flatten(), y=y_line,
                mode='lines', name='Trend Line',
                line=dict(color='#1976D2', dash='dot', width=2)
            ))

            # Confidence band
            y_pred = model.predict(X)
            std_err = np.std(y - y_pred)
            y_upper = y_line + 1.96 * std_err
            y_lower = y_line - 1.96 * std_err
            fig.add_trace(go.Scatter(
                x=np.concatenate([x_line.flatten(), x_line.flatten()[::-1]]),
                y=np.concatenate([y_upper, y_lower[::-1]]),
                fill='toself',
                fillcolor='rgba(211, 47, 47, 0.1)',
                line=dict(color='rgba(255,255,255,0)'),
                showlegend=False
            ))

            fig.update_layout(
                margin=dict(t=40),
                annotations=[dict(x=0.95, y=0.95, xref="paper", yref="paper",
                                 text=f"r = {corr:.2f}", showarrow=False,
                                 bgcolor="white", bordercolor="black", borderwidth=1)],
                legend_title_text='Status'
            )
            st.plotly_chart(fig, use_container_width=True)
        else:
            st.warning("Insufficient front tyre data.")
    else:
        st.warning("No front tyre data.")

# =============== COL 2: Front β€” Pressure vs Temp/Speed Ratio ===============
with col2:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Front Tyres: Pressure vs Temp/Speed Ratio</h5>', unsafe_allow_html=True)
    
    if not front_df.empty:
        # Filter kecepatan > 0
        front_speed_ok = front_df[front_df['Speed (km/h)'] > 0].copy()
        if not front_speed_ok.empty:
            front_speed_ok['temp_speed_ratio'] = front_speed_ok['Temperature (Β°C)'] / front_speed_ok['Speed (km/h)']

            front_speed_ok['Category'] = front_speed_ok.apply(
                lambda row: "Normal Front Tyre" if row['Alarm Status'] == 'No Alarm'
                else "Amber Pressure Front Tyre" if 'Amber' in str(row['Alarm Status'])
                else "Red Pressure Front Tyre", axis=1
            )
            categories = ["Normal Front Tyre", "Amber Pressure Front Tyre", "Red Pressure Front Tyre"]
            front_speed_ok['Category'] = pd.Categorical(front_speed_ok['Category'], categories=categories, ordered=True)

            valid = front_speed_ok.dropna(subset=['temp_speed_ratio', 'Pressure (psi)'])
            if not valid.empty:
                fig = px.scatter(
                    valid,
                    x='temp_speed_ratio',
                    y='Pressure (psi)',
                    color='Category',
                    color_discrete_map={
                        "Normal Front Tyre": "#2E7D32",
                        "Amber Pressure Front Tyre": "#FFBF00",
                        "Red Pressure Front Tyre": "#D32F2F"
                    },
                    category_orders={'Category': categories},
                    template="plotly_white",
                    labels={'temp_speed_ratio': 'Temp / Speed (Β°CΒ·h/km)'}
                )
                fig.update_traces(
                    hovertemplate="<b>%{customdata[0]}</b><br>T/S: %{x:.2f}<br>Pressure: %{y:.1f} psi<extra></extra>",
                    customdata=valid[['Category']].values,
                    marker=dict(size=6)
                )
                fig.update_layout(margin=dict(t=40), legend_title_text='Status')
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.warning("No valid front temp/speed data.")
        else:
            st.warning("No front data with Speed > 0.")
    else:
        st.warning("No front tyre data.")

# =============== COL 3 & 4: Rear Tyres ===============
col3, col4 = st.columns(2)

# =============== COL 3: Rear β€” Temp β†’ Pressure ===============
with col3:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Rear Tyres: Temperature β†’ Pressure</h5>', unsafe_allow_html=True)
    
    if not rear_df.empty:
        rear_df['Category'] = rear_df.apply(
            lambda row: "Normal Rear Tyre" if row['Alarm Status'] == 'No Alarm'
            else "Amber Pressure Rear Tyre" if 'Amber' in str(row['Alarm Status'])
            else "Red Pressure Rear Tyre", axis=1
        )
        categories = ["Normal Rear Tyre", "Amber Pressure Rear Tyre", "Red Pressure Rear Tyre"]
        rear_df['Category'] = pd.Categorical(rear_df['Category'], categories=categories, ordered=True)

        valid = rear_df.dropna(subset=['Temperature (Β°C)', 'Pressure (psi)'])
        if len(valid) > 1:
            X = valid[['Temperature (Β°C)']].values
            y = valid['Pressure (psi)'].values
            model = LinearRegression().fit(X, y)
            x_line = np.linspace(X.min(), X.max(), 100).reshape(-1, 1)
            y_line = model.predict(x_line)
            corr = np.corrcoef(valid['Temperature (Β°C)'], valid['Pressure (psi)'])[0, 1]

            fig = px.scatter(
                valid,
                x='Temperature (Β°C)',
                y='Pressure (psi)',
                color='Category',
                color_discrete_map={
                    "Normal Rear Tyre": "#2E7D32",
                    "Amber Pressure Rear Tyre": "#FFBF00",
                    "Red Pressure Rear Tyre": "#D32F2F"
                },
                category_orders={'Category': categories},
                template="plotly_white"
            )
            fig.update_traces(
                hovertemplate="<b>%{customdata[0]}</b><br>Temp: %{x:.1f}Β°C<br>Pressure: %{y:.1f} psi<extra></extra>",
                customdata=valid[['Category']].values,
                marker=dict(size=6)
            )
            fig.add_trace(go.Scatter(
                x=x_line.flatten(), y=y_line,
                mode='lines', name='Trend Line',
                line=dict(color='#1976D2', dash='dot', width=2)
            ))

            y_pred = model.predict(X)
            std_err = np.std(y - y_pred)
            y_upper = y_line + 1.96 * std_err
            y_lower = y_line - 1.96 * std_err
            fig.add_trace(go.Scatter(
                x=np.concatenate([x_line.flatten(), x_line.flatten()[::-1]]),
                y=np.concatenate([y_upper, y_lower[::-1]]),
                fill='toself',
                fillcolor='rgba(211, 47, 47, 0.1)',
                line=dict(color='rgba(255,255,255,0)'),
                showlegend=False
            ))

            fig.update_layout(
                margin=dict(t=40),
                annotations=[dict(x=0.95, y=0.95, xref="paper", yref="paper",
                                 text=f"r = {corr:.2f}", showarrow=False,
                                 bgcolor="white", bordercolor="black", borderwidth=1)],
                legend_title_text='Status'
            )
            st.plotly_chart(fig, use_container_width=True)
        else:
            st.warning("Insufficient rear tyre data.")
    else:
        st.warning("No rear tyre data.")

# =============== COL 4: Rear β€” Pressure vs Temp/Speed Ratio ===============
with col4:
    st.markdown('<h5 style="text-align:center; margin-top: 0;">Rear Tyres: Pressure vs Temp/Speed Ratio</h5>', unsafe_allow_html=True)
    
    if not rear_df.empty:
        rear_speed_ok = rear_df[rear_df['Speed (km/h)'] > 0].copy()
        if not rear_speed_ok.empty:
            rear_speed_ok['temp_speed_ratio'] = rear_speed_ok['Temperature (Β°C)'] / rear_speed_ok['Speed (km/h)']

            rear_speed_ok['Category'] = rear_speed_ok.apply(
                lambda row: "Normal Rear Tyre" if row['Alarm Status'] == 'No Alarm'
                else "Amber Pressure Rear Tyre" if 'Amber' in str(row['Alarm Status'])
                else "Red Pressure Rear Tyre", axis=1
            )
            categories = ["Normal Rear Tyre", "Amber Pressure Rear Tyre", "Red Pressure Rear Tyre"]
            rear_speed_ok['Category'] = pd.Categorical(rear_speed_ok['Category'], categories=categories, ordered=True)

            valid = rear_speed_ok.dropna(subset=['temp_speed_ratio', 'Pressure (psi)'])
            if not valid.empty:
                fig = px.scatter(
                    valid,
                    x='temp_speed_ratio',
                    y='Pressure (psi)',
                    color='Category',
                    color_discrete_map={
                        "Normal Rear Tyre": "#2E7D32",
                        "Amber Pressure Rear Tyre": "#FFBF00",
                        "Red Pressure Rear Tyre": "#D32F2F"
                    },
                    category_orders={'Category': categories},
                    template="plotly_white",
                    labels={'temp_speed_ratio': 'Temp / Speed (Β°CΒ·h/km)'}
                )
                fig.update_traces(
                    hovertemplate="<b>%{customdata[0]}</b><br>T/S: %{x:.2f}<br>Pressure: %{y:.1f} psi<extra></extra>",
                    customdata=valid[['Category']].values,
                    marker=dict(size=6)
                )
                fig.update_layout(margin=dict(t=40), legend_title_text='Status')
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.warning("No valid rear temp/speed data.")
        else:
            st.warning("No rear data with Speed > 0.")
    else:
        st.warning("No rear tyre data.")

# =============== INSIGHT 3 ===============
def safe_corr(a, b):
    a, b = np.array(a), np.array(b)
    mask = ~(np.isnan(a) | np.isnan(b))
    if mask.sum() < 2:
        return 0.0
    c = np.corrcoef(a[mask], b[mask])[0, 1]
    return c if np.isfinite(c) else 0.0

corr_p_t_front = safe_corr(front_df['Temperature (Β°C)'], front_df['Pressure (psi)'])
corr_p_t_rear = safe_corr(rear_df['Temperature (Β°C)'], rear_df['Pressure (psi)'])
corr_t_s_front = safe_corr(front_df['Temperature (Β°C)'], front_df['Speed (km/h)'])
corr_t_s_rear = safe_corr(rear_df['Temperature (Β°C)'], rear_df['Speed (km/h)'])

insight_lines = [
    f"‒ Front tyres show stronger temp→pressure correlation (r = {corr_p_t_front:.2f}) than rear (r = {corr_p_t_rear:.2f}).",
    f"β€’ Temperature–speed correlation to pressure is weak.",
    f"β€’ This suggests heat buildup is driven more by load/friction than speed alone.",
    f"β€’ Front tyre alarms concentrate in high-temp, high-pressure quadrants β€” enabling early intervention.",
    f"β€’ Rear tyre alarms concentrate in low-temperature, low-pressure quadrants β€” enabling early warning"
]
insight_text = "\n".join(insight_lines)

st.markdown(f"""
<div class="insight-box">
    <div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
    </div>
</div>
""", unsafe_allow_html=True)

# ================= OBJECTIVE 4 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 4: Spatial Risk Mapping β€” Where Do Red Pressure Alarms Occur Most Frequently?</h3>', unsafe_allow_html=True)

# st.markdown('<h5 style="text-align:center; margin-top: 0;">Tyre Alarms Distribution by Location</h5>', unsafe_allow_html=True)

valid_gps = dff.dropna(subset=['Latitude_y', 'Longitude_y'])
if valid_gps.empty:
    st.warning("No valid GNSS coordinates for selected filters.")
else:
    center_lat = valid_gps['Latitude_y'].mean()
    center_lon = valid_gps['Longitude_y'].mean()
    m = folium.Map(
        location=[center_lat, center_lon],
        zoom_start=16,
        tiles='CartoDB positron',
        width='100%',
        height='520px'
    )

    # === Normalisasi suhu untuk scaling ukuran (lebih halus & kecil)
    temp_min = valid_gps['Temperature (Β°C)'].min()
    temp_max = valid_gps['Temperature (Β°C)'].max()
    temp_range = temp_max - temp_min if temp_max > temp_min else 1

    for _, r in valid_gps.iterrows():
        # Warna: Red untuk Red High Pressure, hijau untuk lainnya (termasuk Amber/No Alarm)
        if r['Alarm Status'] == 'Red High Pressure':
            color = '#D32F2F'  # Red 700
        elif 'Amber' in str(r['Alarm Status']):
            color = '#FFA726'  # Amber ~ Orange 500
        else:
            color = '#2E7D32'  # Green 700

        # πŸ”» Ukuran bubble DIPERKECIL: 
        # - radius dasar = 1.5
        # - tambahan maks = 4.0 (bukan 12)
        # - formula lebih smooth: 1.5 + 4.0 * normalized_temp
        normalized_temp = (r['Temperature (Β°C)'] - temp_min) / (temp_range + 1e-6)
        radius = 1.5 + 4.0 * normalized_temp  # βœ… JAUH LEBIH KECIL

        # Popup
        popup_html = f"""
        <div style="font-family:Segoe UI; font-size:13px; line-height:1.4">
        <b>SN:</b> {r['TyreSN']} | Pos: {int(r['Position'])}<br>
        <b>Zone:</b> {r['Zone']}<br>
        <b>Press:</b> {r['Pressure (psi)']:.1f} psi<br>
        <b>Temp:</b> {r['Temperature (Β°C)']:.1f} Β°C<br>
        <b>Speed:</b> {r['Speed (km/h)']:.1f} km/h<br>
        <b>Alarm:</b> {r['Alarm Status']}
        </div>
        """
        folium.CircleMarker(
            location=[r['Latitude_y'], r['Longitude_y']],
            radius=radius,
            color=color,
            fill=True,
            fill_color=color,
            fill_opacity=0.72,
            weight=1,
            popup=folium.Popup(popup_html, max_width=250)
        ).add_to(m)

    # Legend (update to include Amber)
    legend_html = '''
    <div style="
        position: fixed; 
        bottom: 60px; right: 20px; 
        background: white; 
        border: 1px solid #E9ECEF;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        padding: 12px; 
        font-family: Segoe UI;
        font-size: 13px;
        z-index: 9999;
    ">
        <b>Legend</b><br>
        <span style="color:#2E7D32">●</span> Normal<br>
        <span style="color:#FFA726">●</span> Amber Pressure<br>
        <span style="color:#D32F2F">●</span> Red Pressure<br>
        <i>Size ∝ Temperature<br>(1.5–5.5 px radius)</i>
    </div>
    '''
    m.get_root().html.add_child(folium.Element(legend_html))

    st_folium(m, width='100%', height=520, returned_objects=[])

# =============== INSIGHT 4 (Diperbaiki: angka 2 desimal, rata kiri, bullet-ready) ===============
if not valid_gps.empty:
    alarm_gps = valid_gps[valid_gps['is_alarm'] == 1]
    if not alarm_gps.empty:
        # Top zone
        zone_counts = alarm_gps['Zone'].value_counts()
        top_zone = zone_counts.index[0]
        top_zone_count = zone_counts.iloc[0]
        total_alarms = len(alarm_gps)
        zone_pct = (top_zone_count / total_alarms) * 100

        # Front vs Rear
        front_alarms = alarm_gps[alarm_gps['Position'].isin([1, 2])].shape[0]
        rear_alarms = alarm_gps[alarm_gps['Position'].isin([3, 4])].shape[0]
        front_pct = (front_alarms / total_alarms) * 100 if total_alarms > 0 else 0

        insight_lines = [
            f"β€’ Zone {top_zone} is the highest-risk area, contributing {top_zone_count} alarms ({zone_pct:.1f}% of total).",
            f"β€’ Front tyres (Pos 1–2) generate {front_alarms} alarms ({front_pct:.1f}% of total alarm), indicating higher operational stress.",
            f"β€’ {rear_alarms} alarms occur on rear tyres (Pos 3–4), representing {100 - front_pct:.1f}% of total alarm distribution."
        ]
        insight_text = "\n".join(insight_lines)
    else:
        insight_text = "β€’ No alarms detected in the selected filter period."
else:
    insight_text = "β€’ No valid GNSS data available for spatial analysis."

st.markdown(f"""
<div class="insight-box">
    <div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
    </div>
</div>
""", unsafe_allow_html=True)

# ================= OBJECTIVE 5 =================
# ================= OBJECTIVE 6 =================
st.markdown('<h3 class="objective-title">OBJECTIVE 6: Health Index Trends β€” How Does Tyre Health (Pressure & Temperature) Change Over Time by Position?</h3>', unsafe_allow_html=True)

# --- Buat data dummy jika file tidak ada ---
hi_raw = pd.DataFrame({
    'Month': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
    'Position': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
    'HI_final': [
        0.94751783, 0.981636598, 0.994359063, 0.990125387,
        0.957691585, 0.97341454,  0.999259138, 0.994866508,
        0.988009819, 0.997282609, 0.999844077, 1.0,
        0.937885802, 0.968831878, 0.99572543,  0.99767257,
        0.913787453, 0.946695458, 0.995078542, 0.999891732,
        0.916053922, 0.937581169, 0.995727718, 0.999833558
    ]
})

# Tambahkan tahun ke kolom Month agar bisa di-parse
hi_raw['Month'] = pd.to_datetime(hi_raw['Month'].apply(lambda x: f"{int(x):02d}/2023"), format="%m/%Y")

st.success("")

# Jika berhasil baca, proses
required_cols = ['Month', 'Position', 'HI_final']
missing = [c for c in required_cols if c not in hi_raw.columns]
if missing:
    st.error(f"❌ Missing required columns: {', '.join(missing)}")
else:
    try:
        hi_plot = hi_raw[required_cols].copy()

        # Position β†’ integer
        hi_plot['Position'] = pd.to_numeric(hi_plot['Position'], errors='coerce')
        hi_plot = hi_plot.dropna(subset=['Position'])
        hi_plot['Position'] = hi_plot['Position'].astype(int)

        # Filter HI valid (0–100) β€” ubah ke skala 0–100 jika perlu
        # hi_plot['HI_final'] *= 100  # Jika data dalam skala 0–1, aktifkan ini

        if hi_plot.empty:
            st.warning("⚠️ No valid Health Index records after cleaning.")
        else:
            hi_plot = hi_plot.sort_values(['Position', 'Month'])

            # Line chart
            fig = px.line(
                hi_plot,
                x='Month',
                y='HI_final',
                color='Position',
                line_shape='linear',
                title='',
                labels={
                    'HI_final': 'Health Index',
                    'Month': 'Month',
                    'Position': 'Tyre Position'
                },
                color_discrete_map={
                    1: '#003DA5',  # Dark Blue
                    2: '#7FA6E8',  # Light Blue
                    3: '#FFB300',  # Gold
                    4: '#FFE082'   # Light Yellow
                },
                markers=True
            )

            # Hover & layout
            fig.update_traces(
                hovertemplate="<b>Position %{fullData.name}</b><br>Month: %{x|%b %Y}<br>HI: %{y:.2f}<extra></extra>",
                line=dict(width=2.5)
            )
            fig.update_layout(
                xaxis_title='Month',
                yaxis_title='PT Health Index',
                legend_title_text='Position',
                hovermode='x unified',
                margin=dict(t=40, b=40, l=60, r=40),
                template="plotly_white"
            )

            # Tambahkan threshold HI = 0.8 (jika data dalam skala 0–1)
            # fig.add_hline(
            #     y=0.8,
            #     line_dash="dot",
            #     line_color="red",
            #     annotation_text="",
            #     annotation_position="top right"
            # )

            st.plotly_chart(fig, use_container_width=True)

            # === INSIGHT ===
            avg_hi = hi_plot['HI_final'].mean()
            front_hi = hi_plot[hi_plot['Position'].isin([1, 2])]['HI_final'].mean()
            rear_hi = hi_plot[hi_plot['Position'].isin([3, 4])]['HI_final'].mean()
            pos_avg = hi_plot.groupby('Position')['HI_final'].mean()
            worst_pos = pos_avg.idxmin()
            worst_hi = pos_avg.min()

            insight_lines = [
                f"β€’ The minimum PT HI for Tyre 1 in Mei was recorded at 0.91.",
                f"β€’ The minimum PT HI for Tyre 2 in June was recorded at 0.93.",
                f"β€’ The minimum PT HI for Tyre 3 in January was recorded at 1.00.",
                f"β€’ The minimum PT HI for Tyre 4 in January was recorded at 1.00.",
                f"β€’ Tyre 1 and Tyre 2 show a declining health index trend and should be prioritized for inspection."
            ]
            insight_text = "\n".join(insight_lines)

            st.markdown(f"""
            <div class="insight-box">
                <div class="content" style="text-align:left; white-space:pre-line;">
{insight_text}
                </div>
            </div>
            """, unsafe_allow_html=True)

    except Exception as e:
        st.error(f"❌ Error processing Health Index  {e}")


# ================= OBJECTIVE 6 =================
import streamlit as st
import pandas as pd
import numpy as np

# ⚠️ ASSUMPTION: `dff` exists in scope.
# Jika 'Alarm Type' tidak ada di kolom, kita fallback ke mode aman (empty alarms)
# β€” sesuai permintaan: *hard code, jgn pakai def*

st.markdown('<h3 class="objective-title">OBJECTIVE 6: Insights & Mitigation β€” How Can Red Pressure Alarms Be Reduced?</h3>', unsafe_allow_html=True)

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” DATA PREP (HARD-CODED, NO DEF) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# # Cek apakah kolom 'Alarm Type' ada
# has_alarm_type = 'Alarm Type' in dff.columns

# # Front tyre stats β€” fallback ke "β€”" jika NaN/empty/error
# try:
#     front_pressure_avg = dff[dff['Position'].isin([1, 2])]['Pressure (psi)'].mean()
#     front_temp_avg = dff[dff['Position'].isin([1, 2])]['Temperature (Β°C)'].mean()
# except Exception:
#     front_pressure_avg = np.nan
#     front_temp_avg = np.nan

# front_pressure_avg_str = f"{front_pressure_avg:.1f}" if pd.notna(front_pressure_avg) else "β€”"
# front_temp_avg_str = f"{front_temp_avg:.1f}" if pd.notna(front_temp_avg) else "β€”"

# # Alarm filtering β€” hanya Red & Amber, jika 'Alarm Type' tidak ada β†’ anggap 0 alarm
# if has_alarm_type:
#     alarm_mask = dff['Alarm Type'].isin(['Red', 'Amber'])
#     alarm_df = dff[alarm_mask].copy()
# else:
#     alarm_df = dff.iloc[0:0]  # empty DataFrame

# hourly_counts = alarm_df['hour'].value_counts().reindex(range(24), fill_value=0) if 'hour' in alarm_df.columns else pd.Series([0]*24, index=range(24))
# total_alarms = hourly_counts.sum()

# dominant_hour = None
# dominant_percentage = 0.0
# if total_alarms > 0 and not hourly_counts.empty:
#     dominant_hour = int(hourly_counts.idxmax())
#     dominant_percentage = (hourly_counts[dominant_hour] / total_alarms) * 100

# # Zone alarm stats
# if 'Zone' in alarm_df.columns and not alarm_df.empty:
#     zone_counts = alarm_df['Zone'].value_counts()
#     if not zone_counts.empty:
#         top_zone = str(zone_counts.index[0])
#         top_zone_percentage = (zone_counts.iloc[0] / total_alarms) * 100 if total_alarms > 0 else 0.0
#     else:
#         top_zone = "β€”"
#         top_zone_percentage = 0.0
# else:
#     top_zone = "β€”"
#     top_zone_percentage = 0.0

# # Korelasi β€” aman tanpa fungsi
# corr_pressure_temp_front = 0.0
# corr_speed_temp_rear = 0.0

# try:
#     front_df = dff[dff['Position'].isin([1, 2])]
#     rear_df = dff[dff['Position'].isin([3, 4])]

#     # Pressure–temp (front)
#     x1, y1 = front_df['Pressure (psi)'], front_df['Temperature (Β°C)']
#     valid1 = x1.notna() & y1.notna()
#     if valid1.sum() >= 2:
#         c1 = np.corrcoef(x1[valid1], y1[valid1])[0, 1]
#         corr_pressure_temp_front = c1 if np.isfinite(c1) else 0.0

#     # Speed–temp (rear)
#     x2, y2 = rear_df['Speed (km/h)'], rear_df['Temperature (Β°C)']
#     valid2 = x2.notna() & y2.notna()
#     if valid2.sum() >= 2:
#         c2 = np.corrcoef(x2[valid2], y2[valid2])[0, 1]
#         corr_speed_temp_rear = c2 if np.isfinite(c2) else 0.0
# except Exception:
#     pass  # tetap 0.0 jika error

# # Format Β±0.xx, hindari -0.00
# corr_pressure_temp_front_str = f"{corr_pressure_temp_front:+.2f}".replace("-0.00", "0.00")
# corr_speed_temp_rear_str = f"{corr_speed_temp_rear:+.2f}".replace("-0.00", "0.00")

# # Position 1 alarm count
# pos1_alarm_count = alarm_df[alarm_df['Position'] == 1].shape[0] if 'Position' in alarm_df.columns else 0

# # β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” INSIGHTS β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# insight_lines = []

# # 1. Front tyre avg
# line1 = f"1. Front tyres (Pos 1 & 2): avg pressure {front_pressure_avg_str} psi, avg temperature {front_temp_avg_str}Β°C."
# if pd.notna(front_pressure_avg) and front_pressure_avg > 115:
#     line1 += " Exceeds ideal inflation range (100–110 psi), indicating over-pressure risk."
# insight_lines.append(line1)

# # 2. Dominant hour
# if dominant_hour is not None:
#     insight_lines.append(
#         f"2. Peak Red/Amber alarm concentration at {dominant_hour:02d}:00 ({dominant_percentage:.1f}% of total)."
#     )
# else:
#     insight_lines.append("2. No statistically dominant hourly alarm peak.")

# # 3. Correlations
# insight_lines.append(
#     f"3. Front pressure–temperature correlation: r = {corr_pressure_temp_front_str}; "
#     f"Rear speed–temperature correlation: r = {corr_speed_temp_rear_str}."
# )

# # 4. Top zone
# if top_zone != "β€”" and top_zone_percentage >= 10.0:
#     insight_lines.append(
#         f"4. Zone {top_zone} accounts for {top_zone_percentage:.1f}% of alarms β€” highest-risk location."
#     )
# else:
#     insight_lines.append("4. Alarm distribution appears relatively uniform across zones.")

# # 5. Position 1 alarms
# if pos1_alarm_count > 0:
#     insight_lines.append(
#         f"5. Position 1 recorded {pos1_alarm_count} Red/Amber alarms β€” highest of any wheel position."
#     )

# insight_text = "<br>".join(insight_lines)

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” SUMMARY (HARD-CODED) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
summary_text = """\
1. Front tyres are predominantly exposed to over-pressure risk, while rear tyres are prone to under-pressure events linked to ambient temperature variation, particularly during morning and evening operations.<br>
2. Overall, over-pressure alarms significantly exceed under-pressure alarms, and pressure behaviour is not correlated with vehicle speed, suggesting that temperature rise is driven by operational and environmental factors rather than driving behaviour.\
"""

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” RECOMMENDATION (HARD-CODED, BUSINESS-READY) β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
recommendation_text = """\
1. Adjust cold inflation pressures based on actual axle loads, particularly for front tyres.<br>
2. Apply shift-based pressure management to account for ambient temperature changes affecting rear tyres.<br>
3. Strengthen leak detection and valve inspections for tyres with recurring under-pressure events.<br>
4. Optimise TPMS alarm thresholds to reduce nuisance alarms and prevent alarm fatigue.<br>
5. Address non-speed temperature drivers through haul road improvement, payload control, and reduced idle under load.<br>
6. Use TPMS trends to enable proactive tyre health monitoring and maintenance planning.\
"""

# β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” RENDER β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
# st.markdown('<h4 style="text-align:center; margin:10px 0 5px 0; font-weight:bold;">INSIGHTS</h4>', unsafe_allow_html=True)
# st.markdown(f"""
# <div class="insight-box">
#     <div class="content" style="text-align:left;">
# {insight_text}
#     </div>
# </div>
# """, unsafe_allow_html=True)

st.markdown('<h4 style="text-align:center; margin:15px 0 5px 0; font-weight:bold;">SUMMARY</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
    <div class="content" style="text-align:left;">
{summary_text}
    </div>
</div>
""", unsafe_allow_html=True)

st.markdown('<h4 style="text-align:center; margin:15px 0 5px 0; font-weight:bold;">RECOMMENDATION & RISK MITIGATION</h4>', unsafe_allow_html=True)
st.markdown(f"""
<div class="insight-box">
    <div class="content" style="text-align:left;">
{recommendation_text}
    </div>
</div>
""", unsafe_allow_html=True)

st.markdown("""
<div style="
    text-align: center;
    padding: 12px 0 40px 0;
    margin-top: 20px;
    margin-bottom: 40px;
    font-family: Arial, sans-serif;
    border: none !important;
">
    <span style="font-size: 10px; color: #7d7d7d;">
        &copy; 2025 Bukit Teknologi Digital. All rights reserved.
    </span>
</div>
""", unsafe_allow_html=True)