File size: 47,454 Bytes
e05d5b4
1d748d8
 
 
 
 
 
 
 
e05d5b4
 
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
 
1d748d8
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
1d748d8
 
 
e05d5b4
1d748d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05d5b4
 
1d748d8
cc38c12
 
 
 
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
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
library(readxl)
library(lme4)
library(emmeans)
library(plotly)
library(shinyWidgets)
library(ggplot2)

# UI with updated styling
ui <- fluidPage(
  useShinyjs(),
  tags$head(
    tags$meta(charset = "UTF-8"),
    tags$title("Combined Analysis Dashboard"),
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
    tags$style(HTML("
      :root {
        --primary: #1E3A8A; /* Dark blue for tabs */
        --secondary: #6B8E23; /* Olive green */
        --success: #32CD32; /* Lime Green */
        --info: #4169E1; /* Royal Blue */
        --warning: #FF8C00; /* Dark Orange */
        --danger: #DC143C; /* Crimson */
        --light: #D1D5DB; /* Grey for tab text */
        --dark: #2F4F4F; /* Dark Slate Gray */
        --background: #FFFFFF; /* White background */
        --card-bg: #FFFFFF; /* White for cards */
      }
      
      body { 
        font-family: 'Poppins', sans-serif; 
        background: var(--background);
        color: var(--dark);
        overflow-x: hidden;
      }
      
      .container-fluid {
        max-width: 1600px;
        padding: 2.5rem;
        margin: 0 auto;
      }
      
      .section { 
        margin-bottom: 30px; 
        background: var(--card-bg);
        padding: 2.5rem; 
        border-radius: 15px; 
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(30, 58, 138, 0.2);
      }
      
      h1, h2, h3 { 
        color: var(--primary); 
        border-bottom: 2px solid var(--secondary);
        padding-bottom: 10px;
        margin-bottom: 20px;
        font-weight: 700;
      }
      
      .chart-container {
        position: relative;
        margin-bottom: 20px;
        border-radius: 12px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        background: var(--card-bg);
        padding: 1.5rem;
        border: 1px solid rgba(30, 58, 138, 0.2);
      }
      
      .insights {
        margin-top: 20px;
        padding: 20px;
        background: #F5F5F5;
        border-radius: 8px;
        border-left: 4px solid var(--secondary);
      }
      
      .upload-container {
        padding: 20px;
        text-align: center;
        border: 2px dashed var(--primary);
        border-radius: 8px;
        margin-bottom: 25px;
        background: #F9F9F9;
      }
      
      .upload-icon {
        font-size: 48px;
        color: var(--primary);
        margin-bottom: 15px;
      }
      
      .btn-primary {
        background: linear-gradient(135deg, var(--primary), var(--info));
        border: none;
        padding: 1rem 2.5rem;
        border-radius: 8px;
        font-weight: 600;
        color: white;
        transition: all 0.3s;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
      }
      
      .btn-primary:hover {
        background: linear-gradient(135deg, var(--info), var(--primary));
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
        color: white;
      }
      
      .nav-tabs {
        border-bottom: 2px solid var(--primary);
        margin-bottom: 20px;
      }
      
      .nav-tabs .nav-item {
        margin-bottom: -2px;
      }
      
      .nav-tabs .nav-link {
        color: var(--light); /* Grey text for tabs */
        background: #F5F5F5;
        border: 1px solid transparent;
        border-radius: 8px 8px 0 0;
        margin-right: 5px;
        padding: 12px 20px;
        transition: all 0.3s;
      }
      
      .nav-tabs .nav-link:hover {
        color: var(--light);
        background: var(--primary); /* Dark blue on hover */
        border: 1px solid var(--primary);
      }
      
      .nav-tabs .nav-link.active {
        color: var(--light); /* Grey text for active tab */
        background: var(--primary); /* Dark blue for active tab */
        border: 1px solid var(--primary);
        font-weight: bold;
      }
      
      .nav-tabs .nav-link i {
        margin-right: 8px;
      }
      
      .sidebar { 
        background: var(--card-bg);
        color: var(--dark);
        padding: 2rem;
        height: 100vh;
        position: fixed;
        width: 280px;
        box-shadow: 5px 0 15px rgba(0,0,0,0.1);
        border-right: 1px solid var(--primary);
      }
      
      .sidebar-header {
        padding: 20px;
        background: linear-gradient(135deg, var(--primary), var(--info));
        text-align: center;
        border-bottom: 1px solid rgba(0,0,0,0.1);
        border-radius: 10px;
        margin-bottom: 20px;
        color: white;
      }
      
      .sidebar-content {
        padding: 15px;
      }
      
      .nav-link {
        color: var(--dark);
        padding: 12px 15px;
        border-radius: 8px;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
        transition: all 0.3s;
        background: #F5F5F5;
      }
      
      .nav-link:hover, .nav-link.active {
        color: white;
        background: linear-gradient(90deg, var(--primary), var(--info));
        transform: translateX(5px);
        box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
      }
      
      .nav-link i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
      }
      
      .main-content {
        margin-left: 280px;
        padding: 20px;
        width: calc(100% - 280px);
        min-height: 100vh;
        background: var(--background);
      }
      
      .loader {
        border: 5px solid #F5F5F5;
        border-top: 5px solid var(--primary);
        border-radius: 50%;
        width: 50px;
        height: 50px;
        animation: spin 1s linear infinite;
        margin: 20px auto;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      
      .hidden {
        display: none;
      }
      
      table.dataTable {
        border-collapse: collapse;
        width: 100%;
        font-size: 16px;
        background: var(--card-bg);
        border-radius: 8px;
        overflow: hidden;
      }
      
      th {
        background: linear-gradient(45deg, var(--primary), var(--info));
        color: white;
        padding: 1.2rem;
        font-weight: 700;
        text-transform: uppercase;
      }
      
      td {
        padding: 1.2rem;
        border-bottom: 1px solid #F0F0F0;
        transition: background 0.3s;
        color: var(--dark);
      }
      
      tr:hover {
        background: #F5F5F5;
      }
      
      .dataTables_wrapper {
        color: var(--dark);
      }
      
      .status-card {
        background: var(--card-bg);
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        border: 1px solid rgba(30, 58, 138, 0.2);
        margin-bottom: 15px;
      }
      
      .status-card i {
        font-size: 2rem;
        color: var(--primary);
        margin-bottom: 10px;
      }
      
      .status-card h4 {
        color: var(--primary);
        font-size: 1.5rem;
        margin: 5px 0;
      }
      
      .status-card p {
        color: var(--dark);
        margin: 0;
      }
    "))
  ),
  tabsetPanel(
    id = "main_tabs",
    type = "tabs",
    tabPanel(
      icon("seedling"), "Preprocessing data",
      div(
        class = "section",
        h1("🌱 Preprocessing", class = "text-4xl font-extrabold tracking-tight"),
        div(
          class = "upload-container",
          div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
          h3("📤 Upload Dataset (Excel)", style = "color: var(--primary);"),
          p("or", style = "margin: 10px 0;"),
          fileInput("pheno_file", NULL, accept = ".xlsx",
                    buttonLabel = "Browse Files", placeholder = "No file selected"),
          p("📝 Supported format: .xlsx", style = "color: var(--light); font-size: 14px;"),
          div(id = "pheno_loader", class = "loader hidden")
        ),
        radioButtons("pheno_plotType", "📊 Select Plot Type",
                     choices = c("2D Bar" = "2d", "3D Bar" = "3d"),
                     selected = "2d", width = "100%"),
        actionButton("pheno_process", "🔍 Analyze Data", class = "btn-primary w-full"),
        tabsetPanel(
          tabPanel(
            icon("search"), "Missing Data Analysis",
            div(
              class = "section",
              h3("🔍 Missing Data Patterns by Environment & Trait", class = "text-2xl font-bold mb-6"),
              div(class = "chart-container", plotlyOutput("pheno_missingPlot"))
            )
          ),
          tabPanel(
            icon("filter"), "Filtered Data Insights",
            div(
              class = "section",
              h3("✅ Post-Filtering Missing Data Patterns", class = "text-2xl font-bold mb-6"),
              div(class = "chart-container", plotlyOutput("pheno_filteredMissingPlot"))
            )
          ),
          tabPanel(
            icon("table"), "Statistical Summary",
            div(
              class = "section",
              h3("📈 Environment-Wise Descriptive Statistics", class = "text-2xl font-bold mb-6"),
              DTOutput("pheno_statsTable"),
              downloadButton("pheno_downloadStats", "📥 Export Stats as CSV", class = "btn-primary mt-6")
            )
          )
        )
      )
    ),
    tabPanel(
      icon("calculator"), "Phenotypic data analysis",
      div(
        class = "app-wrapper",
        div(
          class = "sidebar",
          div(
            class = "sidebar-header",
            h3("📊 Phenotypic data analysis", style = "margin: 0; font-weight: 600; color: white;")
          ),
          selectInput("lme4_selected_trait", "Select Trait", choices = c()),
          checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
          div(
            class = "sidebar-content",
            div(
              class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
              tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
                     icon("file-upload", class = "fas"), "📤 Upload Data"),
              tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
                     icon("chart-bar", class = "fas"), "📈 Predicted Means"),
              tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-heritability", role = "tab",
                     icon("dna", class = "fas"), "🧬 Heritability"),
              tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
                     icon("link", class = "fas"), "🔗 Trait Correlations"),
              tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-stability", role = "tab",
                     icon("balance-scale", class = "fas"), "⚖️ Stability Analysis")
            ),
            hr(style = "border-color: rgba(255,255,255,0.1);"),
            div(
              style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
              p("LME4 Analysis Dashboard v1.0"),
              p("© 2023 Statistical Genetics Lab")
            )
          )
        ),
        div(
          class = "main-content",
          div(
            class = "tab-content",
            div(
              class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
              div(
                class = "section",
                h2("📤 Upload Your Data"),
                div(
                  class = "upload-container",
                  div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
                  h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
                  p("or", style = "margin: 10px 0;"),
                  fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
                            buttonLabel = "Browse Files", placeholder = "No file selected"),
                  p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
                  div(id = "lme4_loader", class = "loader hidden")
                ),
                verbatimTextOutput("lme4_data_preview"),
                verbatimTextOutput("lme4_debug_log"),
                div(
                  id = "lme4_data_stats", class = "hidden",
                  h3("📊 Data Overview"),
                  fluidRow(
                    column(3, div(class = "status-card card-1",
                                  icon("columns", class = "fas"),
                                  h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
                                  p("Variables")
                    )),
                    column(3, div(class = "status-card card-2",
                                  icon("list", class = "fas"),
                                  h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
                                  p("Observations")
                    )),
                    column(3, div(class = "status-card card-3",
                                  icon("dna", class = "fas"),
                                  h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
                                  p("Genotypes")
                    )),
                    column(3, div(class = "status-card card-4",
                                  icon("globe", class = "fas"),
                                  h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
                                  p("Environments")
                    ))
                  )
                )
              )
            ),
            div(
              class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
              div(
                class = "section",
                h2("📈 Predicted Means (BLUEs)"),
                div(
                  id = "lme4_blues_content",
                  div(class = "chart-container", plotlyOutput("lme4_blues_plot")),
                  div(class = "table-container", DTOutput("lme4_blues_table")),
                  div(
                    class = "insights",
                    h4("💡 Interpretation"),
                    p("The G×E interaction heatmap shows genotype performance across environments. Stable genotypes have consistent values, while environment-specific genotypes vary. Use for selecting broadly adapted or specific genotypes.")
                  )
                ),
                div(
                  id = "lme4_blues_placeholder", class = "text-center",
                  icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
                  h4("📤 Upload data to see predicted means", style = "color: var(--light);")
                )
              )
            ),
            div(
              class = "tab-pane fade", id = "lme4-heritability", role = "tabpanel",
              div(
                class = "section",
                h2("🧬 Heritability"),
                div(
                  id = "lme4_heritability_content",
                  div(class = "chart-container", plotlyOutput("lme4_heritability_plot")),
                  div(class = "table-container", DTOutput("lme4_heritability_table")),
                  div(
                    class = "insights",
                    h4("💡 Interpretation"),
                    p("Heritability (H²) measures genetic variance proportion. High H² (>0.7) traits are easier to improve via breeding, while low H² traits are environment-driven, requiring careful management.")
                  )
                ),
                div(
                  id = "lme4_heritability_placeholder", class = "text-center",
                  icon("dna", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
                  h4("📤 Upload data to see heritability analysis", style = "color: var(--light);")
                )
              )
            ),
            div(
              class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
              div(
                class = "section",
                h2("🔗 Trait Correlations"),
                div(
                  id = "lme4_correlations_content",
                  div(class = "chart-container", plotlyOutput("lme4_correlation_plot")),
                  div(class = "table-container", DTOutput("lme4_cor_table")),
                  div(
                    class = "insights",
                    h4("💡 Interpretation"),
                    p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs. Prioritize traits accordingly.")
                  )
                ),
                div(
                  id = "lme4_correlations_placeholder", class = "text-center",
                  icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
                  h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
                )
              )
            ),
            div(
              class = "tab-pane fade", id = "lme4-stability", role = "tabpanel",
              div(
                class = "section",
                h2("⚖️ Stability Analysis"),
                div(
                  id = "lme4_stability_content",
                  div(class = "chart-container", plotlyOutput("lme4_stability_plot")),
                  div(class = "table-container", DTOutput("lme4_stability_table")),
                  div(
                    class = "insights",
                    h4("💡 Interpretation"),
                    p("Finlay-Wilkinson stability identifies genotypes with slopes near 1 (stable) and high R² (consistent). Stable genotypes suit broad adaptation; extreme slopes suit specific environments.")
                  )
                ),
                div(
                  id = "lme4_stability_placeholder", class = "text-center",
                  icon("balance-scale", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
                  h4("📤 Upload data to see stability analysis", style = "color: var(--light);")
                )
              )
            )
          )
        )
      )
    )
  )
)

# Server function (unchanged from previous)
server <- function(input, output, session) {
  # Phenotypic Analysis Reactive Values
  rv_pheno <- reactiveValues(
    data = NULL,
    processed_data = NULL,
    missing_data = NULL,
    missing_20 = NULL,
    filtered_missing_data = NULL,
    summary_traits = NULL
  )
  
  # LME4 Analysis Reactive Values
  rv_lme4 <- reactiveValues(
    data = NULL,
    traits = NULL,
    trait = NULL,
    lme4_models = NULL,
    blues_all = NULL,
    heritability_table = NULL,
    cor_matrix = NULL,
    cor_table = NULL,
    stability_table = NULL,
    debug_log = NULL
  )
  
  # Phenotypic: Process data
  pheno_process_data <- function(path) {
    message("Pheno: Reading Excel file: ", path)
    input_data <- read_excel(path)
    input_data$Genotype <- as.factor(input_data$Genotype)
    input_data$Block <- as.factor(input_data$Block)
    input_data$Row <- as.factor(input_data$Row)
    input_data$Rep <- as.factor(input_data$Rep)
    input_data$Column <- as.factor(input_data$Column)
    input_data$Environment <- as.factor(input_data$Environment)
    input_data$Environment <- factor(input_data$Environment, levels = unique(input_data$Environment))
    
    trait_cols <- colnames(input_data)[10:ncol(input_data)]
    
    data_missing <- input_data %>%
      group_by(Environment) %>%
      summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
    
    data_missing_long <- data_missing %>%
      pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value")
    
    missing_20_df <- data_missing_long %>% filter(value > 0.20)
    bad_env <- unique(missing_20_df$Environment)
    
    filtered_data <- input_data %>% filter(!(Environment %in% bad_env)) %>% droplevels()
    
    filtered_missing <- filtered_data %>%
      group_by(Environment) %>%
      summarise(across(all_of(trait_cols), ~ sum(is.na(.)) / length(.)))
    
    filtered_missing_long <- filtered_missing %>%
      pivot_longer(cols = all_of(trait_cols), names_to = "Trait", values_to = "value")
    
    summary_traits_df <- filtered_data %>%
      group_by(Environment) %>%
      summarise(across(
        all_of(trait_cols),
        list(
          mean = ~ mean(.x, na.rm = TRUE),
          median = ~ median(.x, na.rm = TRUE),
          sd = ~ sd(.x, na.rm = TRUE),
          min = ~ min(.x, na.rm = TRUE),
          max = ~ max(.x, na.rm = TRUE),
          cv = ~ (sd(.x, na.rm = TRUE) / mean(.x, na.rm = TRUE)) * 100
        ),
        .names = "{.col}_{.fn}"
      )) %>%
      mutate(across(where(is.numeric), ~ round(.x, 2)))
    
    summary_long <- summary_traits_df %>%
      pivot_longer(cols = -Environment, names_to = c("Trait", "Stat"), names_sep = "_", values_to = "value") %>%
      pivot_wider(names_from = "Stat", values_from = "value")
    
    return(list(
      data = input_data,
      processed_data = filtered_data,
      missing_data = data_missing_long,
      missing_20 = missing_20_df,
      filtered_missing_data = filtered_missing_long,
      summary_traits = summary_long
    ))
  }
  
  # Phenotypic: File upload and process observer
  observeEvent(input$pheno_process, {
    req(input$pheno_file)
    message("Pheno: File upload triggered: ", input$pheno_file$name)
    shinyjs::show("pheno_loader")
    on.exit(shinyjs::hide("pheno_loader"))
    
    tryCatch({
      result <- pheno_process_data(input$pheno_file$datapath)
      rv_pheno$data <- result$data
      rv_pheno$processed_data <- result$processed_data
      rv_pheno$missing_data <- result$missing_data
      rv_pheno$missing_20 <- result$missing_20
      rv_pheno$filtered_missing_data <- result$filtered_missing_data
      rv_pheno$summary_traits <- result$summary_traits
      
      showNotification("Pheno: File uploaded and analyzed successfully", type = "message", duration = 5)
    }, error = function(e) {
      message("Pheno: Error in file processing: ", e$message)
      showNotification(paste("Pheno Error:", e$message), type = "error", duration = 10)
    })
  })
  
  # Phenotypic: Plot outputs
  output$pheno_missingPlot <- renderPlotly({
    req(rv_pheno$missing_data)
    if (input$pheno_plotType == "2d") {
      p <- ggplot(rv_pheno$missing_data, aes(x = Environment, y = value, fill = Trait)) +
        geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
        labs(y = "Proportion of Missing Data", x = "Environment") +
        theme_minimal() +
        scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) +
        theme(
          axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"),
          axis.text.y = element_text(size = 12, color = "#2D3748"),
          axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
          axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
          legend.position = "top",
          legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
          legend.text = element_text(size = 10, color = "#2D3748"),
          panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
          panel.grid.minor = element_blank(),
          panel.background = element_rect(fill = "#F9FAFB"),
          plot.background = element_rect(fill = "transparent")
        ) +
        facet_wrap(~Trait, ncol = 2, scales = "free_y")
      
      ggplotly(p) %>%
        layout(
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          margin = list(l = 70, r = 70, t = 70, b = 140),
          font = list(family = "Poppins", size = 12, color = "#2D3748"),
          showlegend = TRUE
        )
    } else {
      plot_ly(
        data = rv_pheno$missing_data,
        x = ~Environment,
        y = ~Trait,
        z = ~value,
        type = "histogram2dcontour",
        histfunc = "sum",
        colorscale = list(
          c(0, 0.5, 1),
          c("#FFB6C1", "#FFDAB9", "#B5EAD7")
        ),
        showscale = TRUE,
        colorbar = list(title = "Missing Proportion")
      ) %>%
        layout(
          scene = list(
            xaxis = list(title = "Environment", tickangle = 45),
            yaxis = list(title = "Trait"),
            zaxis = list(title = "Proportion"),
            camera = list(
              eye = list(x = 2, y = 2, z = 0.5),
              up = list(x = 0, y = 0, z = 1)
            )
          ),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          margin = list(l = 70, r = 70, t = 70, b = 140),
          font = list(family = "Poppins", size = 12, color = "#2D3748"),
          showlegend = FALSE
        )
    }
  })
  
  output$pheno_filteredMissingPlot <- renderPlotly({
    req(rv_pheno$filtered_missing_data)
    if (input$pheno_plotType == "2d") {
      p <- ggplot(rv_pheno$filtered_missing_data, aes(x = Environment, y = value, fill = Trait)) +
        geom_bar(stat = "identity", position = "dodge", alpha = 0.85) +
        labs(y = "Proportion of Missing Data (Filtered)", x = "Environment") +
        theme_minimal() +
        scale_fill_manual(values = c("#FFB6C1", "#FFDAB9", "#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999")) +
        theme(
          axis.text.x = element_text(angle = 30, hjust = 1, size = 12, color = "#2D3748"),
          axis.text.y = element_text(size = 12, color = "#2D3748"),
          axis.title.x = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(t = 12)),
          axis.title.y = element_text(size = 14, color = "#2D3748", face = "bold", margin = margin(r = 12)),
          legend.position = "top",
          legend.title = element_text(size = 12, face = "bold", color = "#2D3748"),
          legend.text = element_text(size = 10, color = "#2D3748"),
          panel.grid.major = element_line(color = "#e5e7eb", size = 0.4),
          panel.grid.minor = element_blank(),
          panel.background = element_rect(fill = "#F9FAFB"),
          plot.background = element_rect(fill = "transparent")
        ) +
        facet_wrap(~Trait, ncol = 2, scales = "free_y")
      
      ggplotly(p) %>%
        layout(
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          margin = list(l = 70, r = 70, t = 70, b = 140),
          font = list(family = "Poppins", size = 12, color = "#2D3748"),
          showlegend = TRUE
        )
    } else {
      plot_ly(
        data = rv_pheno$filtered_missing_data,
        x = ~Environment,
        y = ~Trait,
        z = ~value,
        type = "histogram2dcontour",
        histfunc = "sum",
        colorscale = list(
          c(0, 0.5, 1),
          c("#FFB6C1", "#FFDAB9", "#B5EAD7")
        ),
        showscale = TRUE,
        colorbar = list(title = "Missing Proportion")
      ) %>%
        layout(
          scene = list(
            xaxis = list(title = "Environment", tickangle = 45),
            yaxis = list(title = "Trait"),
            zaxis = list(title = "Proportion"),
            camera = list(
              eye = list(x = 2, y = 2, z = 0.5),
              up = list(x = 0, y = 0, z = 1)
            )
          ),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          margin = list(l = 70, r = 70, t = 70, b = 140),
          font = list(family = "Poppins", size = 12, color = "#2D3748"),
          showlegend = FALSE
        )
    }
  })
  
  # Phenotypic: Table outputs
  output$pheno_statsTable <- renderDT({
    req(rv_pheno$summary_traits)
    datatable(
      rv_pheno$summary_traits,
      options = list(
        pageLength = 10,
        scrollX = TRUE,
        dom = 'Bfrtip',
        buttons = c('copy', 'csv', 'excel', 'pdf', 'print'),
        columnDefs = list(list(className = 'dt-center', targets = '_all'))
      ),
      extensions = 'Buttons',
      class = 'cell-border stripe',
      caption = "Environment-Wise Descriptive Statistics"
    )
  })
  
  output$pheno_downloadStats <- downloadHandler(
    filename = function() {
      "descriptive_stats.csv"
    },
    content = function(file) {
      write.csv(rv_pheno$summary_traits, file, row.names = FALSE)
    }
  )
  
  # LME4: Process data
  lme4_process_data <- function(path) {
    message("LME4: Reading Excel file: ", path)
    data <- read_excel(path)
    
    required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
    missing_cols <- setdiff(required_cols, names(data))
    if (length(missing_cols) > 0) {
      stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
    }
    
    data$Genotype <- as.factor(data$Genotype)
    data$Block <- as.factor(data$Block)
    data$Row <- as.factor(data$Row)
    data$Rep <- as.factor(data$Rep)
    data$Column <- as.factor(data$Column)
    data$Environment <- as.factor(data$Environment)
    data$Environment <- factor(data$Environment, levels = unique(data$Environment))
    
    all_cols <- names(data)
    trait_cols <- all_cols[9:length(all_cols)]
    numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)]
    
    if (length(numeric_cols) == 0) {
      stop("No numeric columns found for traits starting from column 9")
    }
    
    combo_counts <- table(data$Environment, data$Genotype)
    zero_combinations <- sum(combo_counts == 0)
    if (zero_combinations > 0) {
      message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
    }
    if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
      message("LME4: Warning: Over 50% of Environment:Genotype combinations are missing, model fitting may fail")
    }
    
    missing_data <- data %>%
      group_by(Environment) %>%
      summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.)))
    bad_envs <- missing_data %>%
      pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>%
      filter(Missing > 0.2) %>%
      pull(Environment) %>%
      unique()
    if (length(bad_envs) > 0) {
      message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", "))
      data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels()
    }
    
    n_genotypes <- length(unique(data$Genotype))
    n_environments <- length(unique(data$Environment))
    n_reps <- length(unique(data$Rep))
    n_blocks <- length(unique(data$Block))
    message("LME4: Data summary: ",
            "Rows: ", nrow(data), ", ",
            "Genotypes: ", n_genotypes, ", ",
            "Environments: ", n_environments, ", ",
            "Reps: ", n_reps, ", ",
            "Blocks: ", n_blocks, ", ",
            "Numeric traits: ", length(numeric_cols), " (", paste(numeric_cols, collapse = ", "), ")")
    
    if (n_genotypes < 2 || n_environments < 2) {
      stop("Insufficient genotypes (", n_genotypes, ") or environments (", n_environments, ") for LME4 analysis")
    }
    
    return(list(data = data, traits = numeric_cols))
  }
  
  # LME4: Fit model
  lme4_fit_model <- function(data, trait) {
    message("LME4: Fitting lme4 model for trait: ", trait)
    formula_str <- if (input$lme4_include_interaction) {
      paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
    } else {
      paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
    }
    formula <- as.formula(formula_str)
    model <- NULL
    tryCatch({
      model <- lmer(formula, data = data, na.action = na.omit, control = lmerControl(check.rankX = "warn+drop.cols"))
      message("LME4: Successfully fitted model for ", trait)
      return(model)
    }, error = function(e) {
      message("LME4: Failed to fit model for ", trait, ": ", e$message)
      showNotification(paste("LME4: Failed to fit model for ", trait, ": ", e$message), type = "error", duration = 10)
      return(NULL)
    }, warning = function(w) {
      message("LME4: Warning in model fitting for ", trait, ": ", w$message)
      showNotification(paste("LME4: Warning for ", trait, ": ", w$message), type = "warning", duration = 10)
      return(model)
    })
  }
  
  # LME4: Get BLUEs
  lme4_get_blue <- function(model, trait) {
    if (is.null(model)) {
      message("LME4: No model for ", trait, ", returning dummy BLUEs")
      return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA))
    }
    tryCatch({
      emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
      blues <- emmeans(model, ~ Genotype:Environment)
      blues_df <- as.data.frame(blues) %>%
        rename(predicted.value = emmean) %>%
        mutate(Trait = trait) %>%
        select(Trait, Genotype, Environment, predicted.value)
      return(blues_df)
    }, error = function(e) {
      message("LME4: Error in BLUEs for ", trait, ": ", e$message)
      return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA))
    })
  }
  
  # LME4: Calculate heritability
  lme4_calculate_heritability <- function(model, trait) {
    message("LME4: Calculating heritability for trait: ", trait)
    if (is.null(model)) {
      message("LME4: No model for ", trait, ", returning dummy heritability")
      return(data.frame(Trait = trait, Heritability = NA, Error = "No model fitted"))
    }
    tryCatch({
      varcomp <- as.data.frame(VarCorr(model))
      vg <- varcomp$vcov[varcomp$grp == "Genotype"]
      if (length(vg) == 0 || is.na(vg) || vg <= 0) {
        message("LME4: Invalid or zero genetic variance for ", trait)
        return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid genetic variance"))
      }
      ve <- sigma(model)^2
      if (is.na(ve) || ve <= 0) {
        message("LME4: Invalid or zero residual variance for ", trait)
        return(data.frame(Trait = trait, Heritability = NA, Error = "Invalid residual variance"))
      }
      h2 <- vg / (vg + ve)
      if (h2 < 0 || h2 > 1) {
        message("LME4: Heritability out of bounds for ", trait, ": ", h2)
        return(data.frame(Trait = trait, Heritability = NA, Error = "Heritability out of bounds"))
      }
      return(data.frame(Trait = trait, Heritability = round(h2, 3), Error = NA))
    }, error = function(e) {
      message("LME4: Failed to calculate heritability for ", trait, ": ", e$message)
      return(data.frame(Trait = trait, Heritability = NA, Error = e$message))
    }, warning = function(w) {
      message("LME4: Warning in heritability calculation for ", trait, ": ", w$message)
      return(data.frame(Trait = trait, Heritability = NA, Error = w$message))
    })
  }
  
  # LME4: Finlay-Wilkinson stability
  lme4_finlay_wilkinson <- function(blues, trait) {
    blues_trait <- blues %>% filter(Trait == trait, !is.na(predicted.value))
    if (nrow(blues_trait) < 4) {
      message("LME4: Insufficient valid BLUEs for ", trait, " (", nrow(blues_trait), " rows)")
      return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "Insufficient data"))
    }
    env_means <- blues_trait %>% 
      group_by(Environment) %>% 
      summarize(mean_value = mean(predicted.value, na.rm = TRUE))
    blues_trait <- blues_trait %>% left_join(env_means, by = "Environment")
    
    if (nrow(blues_trait) == 0 || all(is.na(blues_trait$mean_value))) {
      message("LME4: No valid environment means for ", trait)
      return(data.frame(Genotype = NA, Slope = NA, R2 = NA, Trait = trait, Error = "No valid environment means"))
    }
    
    stability <- blues_trait %>%
      group_by(Genotype) %>%
      do({
        data_subset <- .
        model <- tryCatch({
          lm(predicted.value ~ mean_value, data = data_subset)
        }, error = function(e) {
          NULL
        })
        if (is.null(model) || nrow(data_subset) < 2) {
          data.frame(Slope = NA, R2 = NA, Error = "Model fitting failed or insufficient data")
        } else {
          data.frame(
            Slope = coef(model)[2],
            R2 = summary(model)$r.squared,
            Error = NA
          )
        }
      }) %>%
      mutate(Trait = trait)
    
    return(stability)
  }
  
  # LME4: File upload observer
  observeEvent(input$lme4_file, {
    req(input$lme4_file)
    message("LME4: File upload triggered: ", input$lme4_file$name)
    shinyjs::show("lme4_loader")
    on.exit(shinyjs::hide("lme4_loader"))
    
    tryCatch({
      result <- lme4_process_data(input$lme4_file$datapath)
      rv_lme4$data <- result$data
      rv_lme4$traits <- result$traits
      rv_lme4$trait <- result$traits[1]
      message("LME4: Data processed, rows: ", nrow(rv_lme4$data), ", traits: ", paste(rv_lme4$traits, collapse = ", "))
      
      updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
      
      shinyjs::show("lme4_data_stats")
      output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
      output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
      output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
      output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
      
      output$lme4_data_preview <- renderPrint({
        str(rv_lme4$data)
        message("LME4: Trait columns selected: ", paste(names(rv_lme4$data)[9:ncol(rv_lme4$data)], collapse = ", "))
      })
      
      debug_log <- c()
      
      withProgress(message = 'LME4: Analyzing data', value = 0, {
        lme4_models <- list()
        blues_list <- list()
        herit_list <- list()
        stability_list <- list()
        
        total_steps <- length(rv_lme4$traits) * 3 + 1
        step_increment <- 1 / total_steps
        
        for (trait in rv_lme4$traits) {
          incProgress(step_increment, detail = paste("Fitting model for", trait))
          model <- lme4_fit_model(rv_lme4$data, trait)
          lme4_models[[trait]] <- model
          debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success")))
          
          incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
          blues_list[[trait]] <- lme4_get_blue(model, trait)
          
          incProgress(step_increment, detail = paste("Calculating heritability for", trait))
          herit_list[[trait]] <- lme4_calculate_heritability(model, trait)
          
          incProgress(step_increment, detail = paste("Performing stability analysis for", trait))
          stability_list[[trait]] <- lme4_finlay_wilkinson(blues_list[[trait]], trait)
        }
        
        incProgress(step_increment, detail = "Calculating correlations")
        if (length(rv_lme4$traits) > 1) {
          trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits))
          cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
          cor_table <- as.data.frame(as.table(cor_matrix)) %>%
            rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq)
          rv_lme4$cor_matrix <- cor_matrix
          rv_lme4$cor_table <- cor_table
          debug_log <- c(debug_log, "Correlations: Success")
        } else {
          rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
          rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1)
          debug_log <- c(debug_log, "Correlations: Single trait, set to 1")
        }
        
        rv_lme4$lme4_models <- lme4_models
        rv_lme4$blues_all <- bind_rows(blues_list)
        rv_lme4$heritability_table <- bind_rows(herit_list)
        rv_lme4$stability_table <- bind_rows(stability_list)
        rv_lme4$debug_log <- debug_log
        
        shinyjs::hide("lme4_blues_placeholder")
        shinyjs::show("lme4_blues_content")
        shinyjs::hide("lme4_heritability_placeholder")
        shinyjs::show("lme4_heritability_content")
        shinyjs::hide("lme4_correlations_placeholder")
        shinyjs::show("lme4_correlations_content")
        shinyjs::hide("lme4_stability_placeholder")
        shinyjs::show("lme4_stability_content")
      })
      
      output$lme4_debug_log <- renderPrint({
        cat(paste(rv_lme4$debug_log, collapse = "\n"))
      })
      
      showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
    }, error = function(e) {
      message("LME4: Error in file processing: ", e$message)
      showNotification(paste("LME4 Error:", e$message), type = "error", duration = 10)
    })
  })
  
  # Update selected trait
  observe({
    req(input$lme4_selected_trait)
    rv_lme4$trait <- input$lme4_selected_trait
  })
  
  # LME4: Filtered reactives
  lme4_filtered_blues <- reactive({
    req(rv_lme4$blues_all, rv_lme4$trait)
    rv_lme4$blues_all %>% filter(Trait = rv_lme4$trait)
  })
  
  lme4_filtered_heritability <- reactive({
    req(rv_lme4$heritability_table, rv_lme4$trait)
    rv_lme4$heritability_table %>% filter(Trait = rv_lme4$trait)
  })
  
  lme4_filtered_stability <- reactive({
    req(rv_lme4$stability_table, rv_lme4$trait)
    rv_lme4$stability_table %>% filter(Trait = rv_lme4$trait)
  })
  
  # LME4: Plot outputs
  output$lme4_blues_plot <- renderPlotly({
    req(lme4_filtered_blues())
    data <- lme4_filtered_blues()
    if (all(is.na(data$predicted.value))) {
      plot_ly() %>%
        layout(
          title = paste("No valid predicted means for", rv_lme4$trait),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    } else {
      plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype,
              type = 'scatter', mode = 'lines+markers',
              colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>%
        layout(
          title = paste("Predicted Means for", rv_lme4$trait),
          xaxis = list(title = "Environment"),
          yaxis = list(title = "Predicted Value"),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    }
  })
  
  output$lme4_heritability_plot <- renderPlotly({
    req(lme4_filtered_heritability())
    data <- lme4_filtered_heritability()
    if (all(is.na(data$Heritability))) {
      plot_ly() %>%
        layout(
          title = paste("No valid heritability for", rv_lme4$trait, ":", unique(data$Error)),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    } else {
      plot_ly(data, x = ~Trait, y = ~Heritability, type = 'bar',
              color = ~Trait, colors = c('#FFB6C1', '#FFDAB9', '#B5EAD7', '#E6E6FA', '#FFFACD', '#FF9999')) %>%
        layout(
          title = "Heritability",
          xaxis = list(title = "Trait"),
          yaxis = list(title = "Heritability", range = c(0, 1)),
          showlegend = FALSE,
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    }
  })
  
  output$lme4_correlation_plot <- renderPlotly({
    req(rv_lme4$cor_matrix)
    if (ncol(rv_lme4$cor_matrix) < 2) {
      plot_ly() %>%
        layout(
          title = "Correlation plot requires at least two traits",
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    } else {
      plot_ly(
        x = colnames(rv_lme4$cor_matrix),
        y = rownames(rv_lme4$cor_matrix),
        z = rv_lme4$cor_matrix,
        type = "heatmap",
        colors = colorRamp(c('#E6E6FA', 'white', '#FFB6C1'))
      ) %>%
        layout(
          title = "Trait Correlation Matrix",
          xaxis = list(title = ""),
          yaxis = list(title = ""),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    }
  })
  
  output$lme4_stability_plot <- renderPlotly({
    req(lme4_filtered_stability())
    data <- lme4_filtered_stability()
    if (all(is.na(data$Slope))) {
      plot_ly() %>%
        layout(
          title = paste("No valid stability analysis for", rv_lme4$trait, ":", unique(data$Error)),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    } else {
      plot_ly(data, x = ~Slope, y = ~R2, text = ~Genotype, type = 'scatter', mode = 'markers+text',
              marker = list(size = 12, color = '#FFB6C1'),
              textposition = 'top') %>%
        layout(
          title = paste("Stability Analysis for", rv_lme4$trait),
          xaxis = list(title = "Slope"),
          yaxis = list(title = "R²"),
          plot_bgcolor = "transparent",
          paper_bgcolor = "transparent",
          font = list(family = "Poppins", size = 12, color = "#2D3748")
        )
    }
  })
  
  # LME4: Table outputs
  output$lme4_blues_table <- renderDT({
    req(lme4_filtered_blues())
    datatable(
      lme4_filtered_blues(),
      extensions = 'Buttons',
      options = list(scrollX = TRUE, dom = 'Bfrtip',
                     buttons = c('copy', 'excel', 'pdf', 'print'),
                     pageLength = 10),
      caption = paste("Predicted Means for", rv_lme4$trait)
    )
  })
  
  output$lme4_heritability_table <- renderDT({
    req(lme4_filtered_heritability())
    datatable(
      lme4_filtered_heritability(),
      extensions = 'Buttons',
      options = list(scrollX = TRUE, dom = 'Bfrtip',
                     buttons = c('copy', 'excel', 'pdf', 'print'),
                     pageLength = 10),
      caption = "Broad-Sense Heritability"
    )
  })
  
  output$lme4_cor_table <- renderDT({
    req(rv_lme4$cor_table)
    datatable(
      rv_lme4$cor_table,
      extensions = 'Buttons',
      options = list(scrollX = TRUE, dom = 'Bfrtip',
                     buttons = c('copy', 'excel', 'pdf', 'print'),
                     pageLength = 10),
      caption = "Correlation Between Traits"
    )
  })
  
  output$lme4_stability_table <- renderDT({
    req(lme4_filtered_stability())
    datatable(
      lme4_filtered_stability(),
      extensions = 'Buttons',
      options = list(scrollX = TRUE, dom = 'Bfrtip',
                     buttons = c('copy', 'excel', 'pdf', 'print'),
                     pageLength = 10),
      caption = paste("Stability Analysis for", rv_lme4$trait)
    )
  })
}

# Run the Shiny app
shinyApp(ui, server)
# Add health check middleware
app$staticPaths <- list("/health" = httpuv::staticPath(system.file("health", package = "shiny")))
app