File size: 60,501 Bytes
1021da9
 
 
2c53a1d
1021da9
e32d65b
f77a585
1021da9
d077a00
 
f77a585
 
 
 
 
1021da9
 
 
 
 
 
54f0cae
1021da9
54f0cae
1021da9
b23fb9c
 
0a29ddd
1021da9
 
 
311d2c7
 
70cfb96
 
e353ca4
1021da9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2b1e06
 
7c39179
8f07a93
a2b1e06
1021da9
 
07a4d86
e353ca4
b2e59e8
 
 
 
96aabe9
 
b2e59e8
185a85c
 
 
 
 
 
 
e353ca4
 
 
 
12804c6
e353ca4
e840845
 
90d5e18
185a85c
e840845
 
899c130
1e1b470
 
b5ed48b
1e1b470
b5ed48b
e353ca4
 
 
 
 
12804c6
e353ca4
64fdc53
e353ca4
 
 
 
12804c6
899c130
 
6c8b87b
 
2d5b5b0
 
39ad0c4
 
 
 
 
 
e353ca4
220e04f
e353ca4
 
ebf50e6
311d2c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebf50e6
311d2c7
 
 
ebf50e6
311d2c7
 
 
 
 
 
 
 
 
 
 
 
ebf50e6
311d2c7
 
 
 
 
 
 
54f0cae
311d2c7
ebf50e6
 
70cfb96
311d2c7
54f0cae
311d2c7
 
 
70cfb96
311d2c7
54f0cae
311d2c7
 
 
70cfb96
311d2c7
 
e353ca4
311d2c7
e353ca4
 
ebf50e6
e353ca4
ebf50e6
 
311d2c7
 
 
 
 
3d56cc9
ebf50e6
311d2c7
 
dcc25f6
5cba8aa
311d2c7
 
ebf50e6
311d2c7
 
 
 
 
3d56cc9
ebf50e6
311d2c7
 
dcc25f6
5cba8aa
311d2c7
 
ebf50e6
311d2c7
 
 
 
 
3d56cc9
ebf50e6
 
311d2c7
dcc25f6
5cba8aa
311d2c7
 
ebf50e6
 
 
54f0cae
ebf50e6
311d2c7
 
70cfb96
ebf50e6
54f0cae
ebf50e6
311d2c7
 
70cfb96
ebf50e6
54f0cae
ebf50e6
 
311d2c7
70cfb96
e353ca4
 
 
 
 
5369656
e353ca4
 
 
 
 
 
 
 
b206444
ae5a3d1
b206444
 
220e04f
b206444
ebf50e6
 
b206444
 
ae5a3d1
5b393f0
ae5a3d1
 
 
 
 
 
a33b237
87b7422
5369656
220e04f
5369656
 
2c53a1d
adbaf0a
f6721c0
b206444
9c7ad76
4d5a500
aa508ab
d011b1f
aa508ab
 
 
89bf41c
6f594e5
 
 
 
 
 
 
 
 
 
 
 
 
 
5042463
44fbcd2
e27c475
 
 
 
 
 
44fbcd2
 
 
e27c475
 
 
 
 
 
44fbcd2
 
 
 
 
 
 
 
6c8b87b
 
 
 
1244250
6c8b87b
 
39ad0c4
1244250
6c8b87b
 
39ad0c4
1244250
6c8b87b
 
 
39ad0c4
1244250
6c8b87b
 
39ad0c4
1244250
6c8b87b
 
39ad0c4
1244250
5042463
6f594e5
 
a0c9fd6
6f594e5
 
a0c9fd6
89bf41c
1e8363d
6f594e5
b8e8bdb
741d267
1e8363d
aa508ab
 
252a303
40ab0f4
1021da9
2c53a1d
adbaf0a
6900faf
b206444
db1e9fe
69b11f3
66c8e7d
db1e9fe
 
b86749e
db1e9fe
 
b86749e
 
 
 
 
efa96d9
1e8363d
1e1b470
 
40cfac2
66c8e7d
40cfac2
66c8e7d
dcc25f6
66c8e7d
dcc25f6
1e1b470
1e8363d
1e1b470
 
40cfac2
66c8e7d
40cfac2
66c8e7d
dcc25f6
66c8e7d
dcc25f6
436ee56
efa96d9
3d56cc9
efa96d9
3d56cc9
efa96d9
3d56cc9
436ee56
efa96d9
a25e372
1e8363d
b16a86d
1e8363d
b16a86d
f5130d3
 
b16a86d
f5130d3
b16a86d
f5130d3
b16a86d
db1e9fe
 
 
b86749e
 
 
db1e9fe
f374e83
 
a2e8e4e
f374e83
a2e8e4e
f374e83
df80a5c
 
64fdc53
1e8363d
8dcbd5a
de89206
b8e8bdb
40ab0f4
8dcbd5a
252a303
40ab0f4
252a303
1e8363d
8dcbd5a
252a303
939415c
8dcbd5a
252a303
939415c
1021da9
2c53a1d
adbaf0a
e353ca4
fb0e7f5
 
69b11f3
fb0e7f5
 
 
 
69b11f3
fb0e7f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e8363d
fb0e7f5
 
1e8363d
fb0e7f5
 
e353ca4
 
1e8363d
8d20291
e353ca4
 
70cfb96
8d20291
e353ca4
70cfb96
e353ca4
7f643e6
ca50776
70cfb96
e353ca4
1e8363d
e353ca4
8d20291
e353ca4
 
70cfb96
8d20291
e353ca4
70cfb96
 
ca50776
7f643e6
e353ca4
fb0e7f5
d485820
a835e4e
76ff10d
7f643e6
 
 
 
76ff10d
 
 
7f643e6
 
 
 
76ff10d
 
e353ca4
d485820
e353ca4
 
 
 
d485820
 
 
 
 
 
e353ca4
1e8363d
e353ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e8363d
e353ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c19bf2
 
e353ca4
d485820
220e04f
7f643e6
 
 
 
76ff10d
 
220e04f
7f643e6
 
 
 
76ff10d
 
e353ca4
 
 
 
 
1e8363d
e353ca4
1e8363d
e353ca4
 
 
 
d485820
e353ca4
 
 
 
d485820
 
 
 
 
 
e353ca4
 
7f643e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e353ca4
 
 
 
 
1e8363d
ca50776
 
 
f746fee
1e8363d
ca50776
 
 
f746fee
e353ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e8363d
ca50776
 
 
 
1e8363d
ca50776
 
 
 
e353ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87b7422
 
 
 
 
e32d65b
 
 
 
 
 
 
 
 
 
 
 
78266ef
 
2b2c50a
78266ef
 
 
 
 
e32d65b
78266ef
45ce301
63cac6f
 
 
 
 
45ce301
 
 
 
 
 
 
 
 
4263647
45ce301
4263647
 
2b2c50a
45ce301
2b2c50a
cd79eb2
e32d65b
 
 
 
 
 
 
 
 
34460c9
1ddfb47
cd79eb2
 
 
4263647
7e14434
4263647
ed2145b
1ddfb47
 
 
6362b12
eb50214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70073ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25c6d27
70073ad
25c6d27
 
70073ad
25c6d27
70073ad
25c6d27
70073ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6362b12
 
8348fb9
fa0e4a7
 
 
3f22d0e
fa0e4a7
 
 
 
8852749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0e4a7
 
 
0720ad1
 
93f2f42
0720ad1
 
 
fa0e4a7
cc2af39
e9c95d8
a5d3c74
0720ad1
 
 
 
 
 
 
 
 
 
 
a5d3c74
fa0e4a7
 
 
2b2c50a
fa0e4a7
 
a5d3c74
 
e32d65b
fa0e4a7
aa1ddcc
e32d65b
a5d3c74
 
 
2b2c50a
a5d3c74
 
74d3eb1
6b178bc
f77a585
 
 
 
 
 
6b178bc
ea83f72
 
 
74d3eb1
ea83f72
 
 
 
 
 
74d3eb1
ea83f72
 
 
c1b6b3a
 
cf1b155
 
ec05986
 
 
 
 
 
 
cf1b155
 
 
ec05986
 
 
 
 
 
 
cf1b155
9274561
 
 
2b2c50a
9274561
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
import streamlit as st
import numpy as np
import pandas as pd
import gspread
import pymongo
import re
from streamlit_javascript import st_javascript

st.set_page_config(layout="wide")

screen_width = st_javascript("window.innerWidth")
# Default to desktop if JS fails
if screen_width is None:
    screen_width = 1200

@st.cache_resource
def init_conn():
        uri = st.secrets['mongo_uri']
        client = pymongo.MongoClient(uri, retryWrites=True, serverSelectionTimeoutMS=500000)
        db = client["MLB_Database"]

        return db
    
db = init_conn()

game_format = {'Win%': '{:.2%}','First Inning Lead Percentage': '{:.2%}', 'Top Score': '{:.2%}',
              'Fifth Inning Lead Percentage': '{:.2%}', '8+ Runs': '{:.2%}', 'LevX': '{:.2%}'}

player_roo_format = {'Top_finish': '{:.2%}','Top_5_finish': '{:.2%}', 'Top_10_finish': '{:.2%}', '20+%': '{:.2%}', '2x%': '{:.2%}', '3x%': '{:.2%}',
                   '4x%': '{:.2%}'}

dk_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
fd_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
dk_sd_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']
fd_sd_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']

st.markdown("""
<style>
    /* Tab styling */
    .stTabs [data-baseweb="tab-list"] {
        gap: 8px;
        padding: 4px;
    }
    .stTabs [data-baseweb="tab"] {
        height: 50px;
        white-space: pre-wrap;
        background-color: #DAA520;
        color: white;
        border-radius: 10px;
        gap: 1px;
        padding: 10px 20px;
        font-weight: bold;
        transition: all 0.3s ease;
    }
    .stTabs [aria-selected="true"] {
        background-color: #DAA520;
        border: 3px solid #FFD700;
        color: white;
    }
    .stTabs [data-baseweb="tab"]:hover {
        background-color: #FFD700;
        cursor: pointer;
    }

    div[data-baseweb="select"] > div {
        background-color: #DAA520;
        color: white;
    }
</style>""", unsafe_allow_html=True)

@st.cache_resource(ttl = 61)
def init_baselines():

    collection = db["Hitter_Info"] 
    cursor = collection.find()
    Hitter_info = pd.DataFrame(cursor)
    LHP_Info = Hitter_info[Hitter_info['Set'] == 'LHP'].drop_duplicates(subset=['Player'])
    RHP_Info = Hitter_info[Hitter_info['Set'] == 'RHP'].drop_duplicates(subset=['Player'])

    collection = db["Pitcher_Info"] 
    cursor = collection.find()
    Pitcher_info = pd.DataFrame(cursor)
    Pitcher_info = Pitcher_info.rename(columns={'Names':'Player'})
    LHH_Info = Pitcher_info[Pitcher_info['Set'] == 'LHH'].drop_duplicates(subset=['Player'])
    RHH_Info = Pitcher_info[Pitcher_info['Set'] == 'RHH'].drop_duplicates(subset=['Player'])

    collection = db["Player_Range_Of_Outcomes"] 
    cursor = collection.find()
    player_frame = pd.DataFrame(cursor)

    roo_data = player_frame.drop(columns=['_id'])
    roo_data['Salary'] = roo_data['Salary'].astype(int)
    hold_frame = roo_data.copy()
    
    hold_frame['Order'] = np.where(hold_frame['pos_group'] == 'Hitters', hold_frame['Player'].map(RHP_Info.set_index('Player')['Order']), 0)
    hold_frame['Hand'] = np.where(hold_frame['pos_group'] == 'Hitters', hold_frame['Player'].map(RHP_Info.set_index('Player')['bats']), hold_frame['Player'].map(RHH_Info.set_index('Player')['Hand']))

    roo_data.insert(3, 'Hand', hold_frame['Hand'])
    roo_data.insert(4, 'Order', hold_frame['Order'].astype(int))
    
    dk_roo = roo_data[roo_data['Site'] == 'Draftkings']
    dk_id_map = dict(zip(dk_roo['Player'], dk_roo['player_ID']))
    fd_roo = roo_data[roo_data['Site'] == 'Fanduel']
    fd_id_map = dict(zip(fd_roo['Player'], fd_roo['player_ID']))

    collection = db["Player_SD_Range_Of_Outcomes"] 
    cursor = collection.find()
    player_frame = pd.DataFrame(cursor)

    sd_roo_data = player_frame.drop(columns=['_id'])
    sd_roo_data['Salary'] = sd_roo_data['Salary'].astype(int)
    sd_roo_data = sd_roo_data.rename(columns={'Own': 'Own%'})

    collection = db["Scoring_Percentages"] 
    cursor = collection.find()
    team_frame = pd.DataFrame(cursor)
    scoring_percentages = team_frame.drop(columns=['_id'])
    scoring_percentages['Runs/$'] = scoring_percentages['Avg Score'] / (scoring_percentages['Avg_Salary'] / 1000)
    scoring_percentages = scoring_percentages[['Names', 'Avg_Salary', 'Stack_Prio', 'Opp_SP', 'Avg First Inning', 'First Inning Lead Percentage', 'Avg Fifth Inning', 'Fifth Inning Lead Percentage', 'Avg Score', 'Runs/$', '8+ runs', 'Win Percentage',
    'DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'DK Main Top Score', 'FD Main Top Score', 'DK Secondary Top Score', 'FD Secondary Top Score',
    'DK Turbo Top Score', 'FD Turbo Top Score']]
    scoring_percentages['8+ runs'] = scoring_percentages['8+ runs'].replace('%', '', regex=True).astype(float)
    scoring_percentages['Win Percentage'] = scoring_percentages['Win Percentage'].replace('%', '', regex=True).astype(float)
    scoring_percentages['DK Main Top Score'] = scoring_percentages['DK Main Top Score'].replace('', np.nan).astype(float)
    scoring_percentages['FD Main Top Score'] = scoring_percentages['FD Main Top Score'].replace('', np.nan).astype(float)
    scoring_percentages['DK Secondary Top Score'] = scoring_percentages['DK Secondary Top Score'].replace('', np.nan).astype(float)
    scoring_percentages['FD Secondary Top Score'] = scoring_percentages['FD Secondary Top Score'].replace('', np.nan).astype(float)
    scoring_percentages['DK Turbo Top Score'] = scoring_percentages['DK Turbo Top Score'].replace('', np.nan).astype(float)
    scoring_percentages['FD Turbo Top Score'] = scoring_percentages['FD Turbo Top Score'].replace('', np.nan).astype(float)
    
    return roo_data, sd_roo_data, scoring_percentages, dk_roo, fd_roo, dk_id_map, fd_id_map

@st.cache_data(ttl = 60)
def init_DK_lineups(type_var, slate_var):  
    
    if type_var == 'Regular':
        if slate_var == 'Main':
            collection = db['DK_MLB_name_map']
            cursor = collection.find()
            raw_data = pd.DataFrame(list(cursor))
            names_dict = dict(zip(raw_data['key'], raw_data['value']))

            collection = db['DK_MLB_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
            dict_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3']
            # Map names
            raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))
        elif slate_var == 'Secondary':
            collection = db['DK_MLB_Secondary_name_map']
            cursor = collection.find()
            raw_data = pd.DataFrame(list(cursor))
            names_dict = dict(zip(raw_data['key'], raw_data['value']))
            
            collection = db['DK_MLB_Secondary_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
            dict_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3']
            # Map names
            raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))
        elif slate_var == 'Auxiliary':
            collection = db['DK_MLB_Turbo_name_map']
            cursor = collection.find()
            raw_data = pd.DataFrame(list(cursor))
            names_dict = dict(zip(raw_data['key'], raw_data['value']))
            
            collection = db['DK_MLB_Turbo_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
            dict_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3']
            # Map names
            raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))
    elif type_var == 'Showdown':
        if slate_var == 'Main':
            collection = db['DK_MLB_SD1_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
        elif slate_var == 'Secondary':
            collection = db['DK_MLB_SD2_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
        elif slate_var == 'Auxiliary':
            collection = db['DK_MLB_SD3_seed_frame']
            cursor = collection.find().limit(10000)

            raw_display = pd.DataFrame(list(cursor))
            raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]

    DK_seed = raw_display.to_numpy()

    return DK_seed

@st.cache_data(ttl = 60)
def init_FD_lineups(type_var,slate_var):  
        
        if type_var == 'Regular':
            if slate_var == 'Main':
                collection = db['FD_MLB_name_map']
                cursor = collection.find()
                raw_data = pd.DataFrame(list(cursor))
                names_dict = dict(zip(raw_data['key'], raw_data['value']))

                collection = db['FD_MLB_seed_frame']
                cursor = collection.find().limit(10000)

                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
                dict_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL']
                # Map names
                raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))
            elif slate_var == 'Secondary':
                collection = db['FD_MLB_Secondary_name_map']
                cursor = collection.find()
                raw_data = pd.DataFrame(list(cursor))
                names_dict = dict(zip(raw_data['key'], raw_data['value']))

                collection = db['FD_MLB_Secondary_seed_frame']
                cursor = collection.find().limit(10000)

                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
                dict_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL']
                # Map names
                raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))
            elif slate_var == 'Auxiliary':
                collection = db['FD_MLB_Turbo_name_map']
                cursor = collection.find()
                raw_data = pd.DataFrame(list(cursor))
                names_dict = dict(zip(raw_data['key'], raw_data['value']))

                collection = db['FD_MLB_Turbo_seed_frame']
                cursor = collection.find().limit(10000)
            
                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
                dict_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL']
                # Map names
                raw_display[dict_columns] = raw_display[dict_columns].apply(lambda x: x.map(names_dict))

        elif type_var == 'Showdown':
            if slate_var == 'Main':
                collection = db['FD_MLB_SD1_seed_frame']
                cursor = collection.find().limit(10000)

                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
            elif slate_var == 'Secondary':
                collection = db['FD_MLB_SD2_seed_frame']
                cursor = collection.find().limit(10000)

                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
            elif slate_var == 'Auxiliary':
                collection = db['FD_MLB_SD3_seed_frame']
                cursor = collection.find().limit(10000)
            
                raw_display = pd.DataFrame(list(cursor))
                raw_display = raw_display[['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'salary', 'proj', 'Team', 'Team_count', 'Secondary', 'Secondary_count', 'Own']]
    
        FD_seed = raw_display.to_numpy()

        return FD_seed

@st.cache_data
def convert_df_to_csv(df):
    return df.to_csv().encode('utf-8')

@st.cache_data
def convert_df(array):
    array = pd.DataFrame(array, columns=column_names)
    return array.to_csv().encode('utf-8')

col1, col2 = st.columns([1, 9])
with col1:
    if st.button("Load/Reset Data", key='reset'):
        st.cache_data.clear()
        roo_data, sd_roo_data, scoring_percentages, dk_roo, fd_roo, dk_id_map, fd_id_map = init_baselines()
        hold_display = roo_data
        dk_lineups = init_DK_lineups('Regular', 'Main')
        fd_lineups = init_FD_lineups('Regular', 'Main')
        for key in st.session_state.keys():
            del st.session_state[key]
with col2:
    with st.container():
        col1, col2 = st.columns([3, 3])
        with col1:
            view_var = st.selectbox("Select view", ["Simple", "Advanced"], key='view_var')
        with col2:
            site_var = st.selectbox("What site do you want to view?", ('Draftkings', 'Fanduel'), key='site_var')
        

tab1, tab2, tab3, tab4 = st.tabs(["Scoring Percentages", "Player ROO", "Optimals", "Handbuilder"])

roo_data, sd_roo_data, scoring_percentages, dk_roo, fd_roo, dk_id_map, fd_id_map = init_baselines()
hold_display = roo_data

with tab1:
    st.header("Scoring Percentages")
    with st.expander("Info and Filters"):
        with st.container():
            slate_var1 = st.radio("Which data are you loading?", ('Main Slate', 'Secondary Slate', 'Turbo Slate'), key='slate_var1')
            prio_split = st.radio("Do you want to isolate a specific Stack Priority?", ('No', 'Yes'), key='prio_split')
            if prio_split == 'Yes':
                prio_var = st.radio("Which Stack Priority are you looking for?", ['OF_Prio', 'IF_Prio'], key='prio_var')
            else:
                prio_var = None

    
    if site_var == 'Draftkings':
        if slate_var1 == 'Main Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['DK Main Slate'] == 1]
        elif slate_var1 == 'Secondary Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['DK Secondary Slate'] == 1]
        elif slate_var1 == 'Turbo Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['DK Turbo Slate'] == 1]
    elif site_var == 'Fanduel':
        if slate_var1 == 'Main Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['FD Main Slate'] == 1]
        elif slate_var1 == 'Secondary Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['FD Secondary Slate'] == 1]
        elif slate_var1 == 'Turbo Slate':
            scoring_percentages = scoring_percentages[scoring_percentages['FD Turbo Slate'] == 1]

    dk_hitters_only = dk_roo[dk_roo['pos_group'] != 'Pitchers']
    if slate_var1 == 'Main Slate':
        dk_hitters_only = dk_hitters_only[dk_hitters_only['Slate'] == 'main_slate']
    elif slate_var1 == 'Secondary Slate':
        dk_hitters_only = dk_hitters_only[dk_hitters_only['Slate'] == 'secondary_slate']
    elif slate_var1 == 'Turbo Slate':
        dk_hitters_only = dk_hitters_only[dk_hitters_only['Slate'] == 'turbo_slate']
    dk_hitters_only = dk_hitters_only.replace('CWS', 'CHW')
    dk_team_ownership = dk_hitters_only.groupby('Team')['Own%'].sum().reset_index()
    fd_hitters_only = fd_roo[fd_roo['pos_group'] != 'Pitchers']
    if slate_var1 == 'Main Slate':
        fd_hitters_only = fd_hitters_only[fd_hitters_only['Slate'] == 'main_slate']
    elif slate_var1 == 'Secondary Slate':
        fd_hitters_only = fd_hitters_only[fd_hitters_only['Slate'] == 'secondary_slate']
    elif slate_var1 == 'Turbo Slate':
        fd_hitters_only = fd_hitters_only[fd_hitters_only['Slate'] == 'turbo_slate']
    fd_hitters_only = fd_hitters_only.replace('CWS', 'CHW')
    fd_team_ownership = fd_hitters_only.groupby('Team')['Own%'].sum().reset_index()
    scoring_percentages = scoring_percentages.merge(dk_team_ownership, left_on='Names', right_on='Team', how='left')
    scoring_percentages.rename(columns={'Own%': 'DK Own%'}, inplace=True)
    scoring_percentages.drop('Team', axis=1, inplace=True)
    scoring_percentages = scoring_percentages.merge(fd_team_ownership, left_on='Names', right_on='Team', how='left')
    scoring_percentages.rename(columns={'Own%': 'FD Own%'}, inplace=True)
    scoring_percentages.drop('Team', axis=1, inplace=True)
    if site_var == 'Draftkings':
        if slate_var1 == 'Main Slate':
            scoring_percentages['DK LevX'] = scoring_percentages['DK Main Top Score'].rank(pct=True).astype(float) - scoring_percentages['DK Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'DK Main Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'FD Main Top Score', 'DK Secondary Top Score', 'FD Secondary Top Score', 'DK Turbo Top Score', 'FD Turbo Top Score'], axis=1)
        elif slate_var1 == 'Secondary Slate':
            scoring_percentages['DK LevX'] = scoring_percentages['DK Secondary Top Score'].rank(pct=True).astype(float) - scoring_percentages['DK Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'DK Secondary Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'FD Main Top Score', 'DK Main Top Score', 'FD Secondary Top Score', 'DK Turbo Top Score', 'FD Turbo Top Score'], axis=1)
        elif slate_var1 == 'Turbo Slate':
            scoring_percentages['DK LevX'] = scoring_percentages['DK Turbo Top Score'].rank(pct=True).astype(float) - scoring_percentages['DK Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'DK Turbo Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'FD Main Top Score', 'DK Main Top Score', 'FD Secondary Top Score', 'DK Secondary Top Score', 'FD Turbo Top Score'], axis=1)
    elif site_var == 'Fanduel':
        if slate_var1 == 'Main Slate':
            scoring_percentages['FD LevX'] = scoring_percentages['FD Main Top Score'].rank(pct=True).astype(float) - scoring_percentages['FD Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'FD Main Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'DK Main Top Score', 'DK Secondary Top Score', 'FD Secondary Top Score', 'DK Turbo Top Score', 'FD Turbo Top Score'], axis=1)
        elif slate_var1 == 'Secondary Slate':
            scoring_percentages['FD LevX'] = scoring_percentages['FD Secondary Top Score'].rank(pct=True).astype(float) - scoring_percentages['FD Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'FD Secondary Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'FD Main Top Score', 'DK Main Top Score', 'DK Secondary Top Score', 'DK Turbo Top Score', 'FD Turbo Top Score'], axis=1)
        elif slate_var1 == 'Turbo Slate':
            scoring_percentages['FD LevX'] = scoring_percentages['FD Turbo Top Score'].rank(pct=True).astype(float) - scoring_percentages['FD Own%'].rank(pct=True).astype(float)
            scoring_percentages = scoring_percentages.rename(columns={'FD Turbo Top Score': 'Top Score'})
            scoring_percentages = scoring_percentages.drop(['DK Main Slate', 'DK Secondary Slate', 'DK Turbo Slate', 'FD Main Slate', 'FD Secondary Slate', 'FD Turbo Slate', 'FD Main Top Score', 'DK Main Top Score', 'FD Secondary Top Score', 'DK Secondary Top Score', 'DK Turbo Top Score'], axis=1)
    scoring_percentages = scoring_percentages.sort_values(by='8+ runs', ascending=False)
    if site_var == 'Draftkings':
        scoring_percentages = scoring_percentages.rename(columns={'DK LevX': 'LevX', 'DK Own%': 'Own%', 'Avg Score': 'Runs', 'Win Percentage': 'Win%', '8+ runs': '8+ Runs'})
        scoring_percentages = scoring_percentages.drop(['FD Own%'], axis=1)
    elif site_var == 'Fanduel':
        scoring_percentages = scoring_percentages.rename(columns={'FD LevX': 'LevX', 'FD Own%': 'Own%', 'Avg Score': 'Runs', 'Win Percentage': 'Win%', '8+ runs': '8+ Runs'})
        scoring_percentages = scoring_percentages.drop(['DK Own%'], axis=1)
    
    if view_var == "Simple":
        scoring_percentages = scoring_percentages[['Names', 'Runs', '8+ Runs', 'Win%', 'LevX', 'Own%']]
        scoring_percentages = scoring_percentages.set_index('Names', drop=True)
        st.dataframe(scoring_percentages.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Own%']).format(game_format, precision=2), height=750, use_container_width = True)
    elif view_var == "Advanced":
        if prio_var is not None:
            scoring_percentages = scoring_percentages[scoring_percentages['Stack_Prio'] == prio_var]
        scoring_percentages = scoring_percentages.set_index('Names', drop=True)
        st.dataframe(scoring_percentages.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Avg_Salary', 'Own%']).format(game_format, precision=2), height=750, use_container_width = True)

with tab2:
    st.header("Player ROO")
    with st.expander("Info and Filters"):
        with st.container():
            slate_type_var2 = st.radio("Which slate type are you loading?", ('Regular', 'Showdown'), key='slate_type_var2')
            slate_var2 = st.radio("Which slate data are you loading?", ('Main', 'Secondary', 'Auxiliary'), key='slate_var2')
            group_var2 = st.radio("Which position group would you like to view?", ('All', 'Pitchers', 'Hitters'), key='group_var2')
            team_var2 = st.selectbox("Which team would you like to view?",  ['All', 'Specific'], key='team_var2')
            if team_var2 == 'Specific':
                team_select2 = st.multiselect("Select your team(s)", roo_data['Team'].unique(), key='team_select2')
            else:
                team_select2 = None
            pos_var2 = st.selectbox("Which position(s) would you like to view?",  ['All', 'Specific'], key='pos_var2')
            if pos_var2 == 'Specific':
                pos_select2 = st.multiselect("Select your position(s)", roo_data['Position'].unique(), key='pos_select2')
            else:
                pos_select2 = None
    if slate_type_var2 == 'Regular':
        if site_var == 'Draftkings':
        
            player_roo_raw = dk_roo.copy()

            if group_var2 == 'All':
                pass
            elif group_var2 == 'Pitchers':
                player_roo_raw = player_roo_raw[player_roo_raw['pos_group'] == 'Pitchers']
            elif group_var2 == 'Hitters':
                player_roo_raw = player_roo_raw[player_roo_raw['pos_group'] == 'Hitters']

        elif site_var == 'Fanduel':
            
            player_roo_raw = fd_roo.copy()

            if group_var2 == 'All':
                pass
            elif group_var2 == 'Pitchers':
                player_roo_raw = player_roo_raw[player_roo_raw['pos_group'] == 'Pitchers']
            elif group_var2 == 'Hitters':
                player_roo_raw = player_roo_raw[player_roo_raw['pos_group'] == 'Hitters']
        
        if slate_var2 == 'Main':
            player_roo_raw = player_roo_raw[player_roo_raw['Slate'] == 'main_slate']
        elif slate_var2 == 'Secondary':
            player_roo_raw = player_roo_raw[player_roo_raw['Slate'] == 'secondary_slate']
        elif slate_var2 == 'Auxiliary':
            player_roo_raw = player_roo_raw[player_roo_raw['Slate'] == 'turbo_slate']
            
    elif slate_type_var2 == 'Showdown':
        player_roo_raw = sd_roo_data.copy()
        if site_var == 'Draftkings':
            player_roo_raw['site'] = 'Draftkings'
        elif site_var == 'Fanduel':
            player_roo_raw['site'] = 'Fanduel'

        if slate_var2 == 'Main':
            player_roo_raw = player_roo_raw[player_roo_raw['slate'] == 'DK SD1']
        elif slate_var2 == 'Secondary':
            player_roo_raw = player_roo_raw[player_roo_raw['slate'] == 'DK SD2']
        elif slate_var2 == 'Auxiliary':
            player_roo_raw = player_roo_raw[player_roo_raw['slate'] == 'DK SD3']
    
    if team_select2:
        player_roo_raw = player_roo_raw[player_roo_raw['Team'].isin(team_select2)]
    if pos_select2:
        position_mask = player_roo_raw['Position'].apply(lambda x: any(pos in x for pos in pos_select2))
        player_roo_raw = player_roo_raw[position_mask]
    
    player_roo_disp = player_roo_raw
    
    if slate_type_var2 == 'Regular':
        player_roo_disp = player_roo_disp.drop(columns=['Site', 'Slate', 'pos_group', 'timestamp', 'player_ID'])
    elif slate_type_var2 == 'Showdown':
        player_roo_disp = player_roo_disp.drop(columns=['site', 'slate', 'version', 'timestamp'])
    
    player_roo_disp = player_roo_disp.drop_duplicates(subset=['Player'])

    if view_var == "Simple":
        try:
            player_roo_disp = player_roo_disp[['Player', 'Salary', 'Median', 'Ceiling', 'Own%', 'Position', 'Team']]
            player_roo_disp = player_roo_disp.set_index('Player', drop=True)
            st.dataframe(player_roo_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Salary', 'Own%']).format(player_roo_format, precision=2), height=750, use_container_width = True)
        except:
            player_roo_disp = player_roo_disp.set_index('Player', drop=True)
            st.dataframe(player_roo_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Salary', 'Own%']).format(player_roo_format, precision=2), height=750, use_container_width = True)
            
    elif view_var == "Advanced":
        try:
            player_roo_disp = player_roo_disp.set_index('Player', drop=True)
            st.dataframe(player_roo_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Order', 'Salary', 'Own%', 'Small Field Own%', 'Large Field Own%', 'Cash Own%']).format(player_roo_format, precision=2), height=750, use_container_width = True)
        except:
            player_roo_disp = player_roo_disp.set_index('Player', drop=True)
            st.dataframe(player_roo_disp.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Order', 'Salary', 'Own%', 'Small Field Own%', 'Large Field Own%', 'Cash Own%']).format(player_roo_format, precision=2), height=750, use_container_width = True)

with tab3:
    st.header("Optimals")
    with st.expander("Info and Filters"):
        col1, col2, col3 = st.columns(3)
        with col1:
            slate_type_var3 = st.radio("Which slate type are you loading?", ('Regular', 'Showdown'), key='slate_type_var3')
            if slate_type_var3 == 'Regular':
                raw_baselines = roo_data
            elif slate_type_var3 == 'Showdown':
                raw_baselines = sd_roo_data
            slate_var3 = st.radio("Which slate data are you loading?", ('Main', 'Secondary', 'Auxiliary'), key='slate_var3')
            if slate_type_var3 == 'Regular':
                if site_var == 'Draftkings':
                    dk_lineups = init_DK_lineups(slate_type_var3, slate_var3)
                elif site_var == 'Fanduel':
                    fd_lineups = init_FD_lineups(slate_type_var3, slate_var3)
            elif slate_type_var3 == 'Showdown':
                if site_var == 'Draftkings':
                    dk_lineups = init_DK_lineups(slate_type_var3, slate_var3)
                elif site_var == 'Fanduel':
                    fd_lineups = init_FD_lineups(slate_type_var3, slate_var3)
        with col2:
            lineup_num_var = st.number_input("How many lineups do you want to display?", min_value=1, max_value=1000, value=150, step=1)
            player_var1 = st.radio("Do you want a frame with specific Players?", ('Full Slate', 'Specific Players'), key='player_var1')
            if player_var1 == 'Specific Players':
                player_var2 = st.multiselect('Which players do you want?', options = raw_baselines['Player'].unique())
            elif player_var1 == 'Full Slate':
                    player_var2 = raw_baselines.Player.values.tolist()
        with col3:
            if site_var == 'Draftkings':
                salary_min_var = st.number_input("Minimum salary used", min_value = 0, max_value = 50000, value = 49000, step = 100, key = 'salary_min_var')
                salary_max_var = st.number_input("Maximum salary used", min_value = 0, max_value = 50000, value = 50000, step = 100, key = 'salary_max_var')
            elif site_var == 'Fanduel':
                salary_min_var = st.number_input("Minimum salary used", min_value = 0, max_value = 35000, value = 34000, step = 100, key = 'salary_min_var')
                salary_max_var = st.number_input("Maximum salary used", min_value = 0, max_value = 35000, value = 35000, step = 100, key = 'salary_max_var')
        
        
        if site_var == 'Draftkings':
            if slate_type_var3 == 'Regular':
                ROO_slice = raw_baselines[raw_baselines['Site'] == 'Draftkings']
                player_salaries = dict(zip(ROO_slice['Player'], ROO_slice['Salary']))
                column_names = dk_columns
            elif slate_type_var3 == 'Showdown':
                player_salaries = dict(zip(raw_baselines['Player'], raw_baselines['Salary']))
                column_names = dk_sd_columns
            # Get the minimum and maximum ownership values from dk_lineups
            min_own = np.min(dk_lineups[:,12])
            max_own = np.max(dk_lineups[:,12])
            
                    
        elif site_var == 'Fanduel':
            raw_baselines = hold_display
            if slate_type_var3 == 'Regular':
                ROO_slice = raw_baselines[raw_baselines['Site'] == 'Fanduel']
                player_salaries = dict(zip(ROO_slice['Player'], ROO_slice['Salary']))
                column_names = fd_columns
            elif slate_type_var3 == 'Showdown':
                player_salaries = dict(zip(raw_baselines['Player'], raw_baselines['Salary']))
                column_names = fd_sd_columns
            # Get the minimum and maximum ownership values from dk_lineups
            min_own = np.min(fd_lineups[:,11])
            max_own = np.max(fd_lineups[:,11])

        if st.button("Prepare full data export", key='data_export'):
            name_export = pd.DataFrame(st.session_state.working_seed.copy(), columns=column_names)
            data_export = pd.DataFrame(st.session_state.working_seed.copy(), columns=column_names)
            if site_var == 'Draftkings':
                if slate_type_var3 == 'Regular':
                    map_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3']
                elif slate_type_var3 == 'Showdown':
                    map_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5']
                for col_idx in map_columns:
                    data_export[col_idx] = data_export[col_idx].map(dk_id_map)
            elif site_var == 'Fanduel':
                if slate_type_var3 == 'Regular':
                    map_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL']
                elif slate_type_var3 == 'Showdown':
                    map_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4']
                for col_idx in map_columns:
                    data_export[col_idx] = data_export[col_idx].map(fd_id_map)
            st.download_button(
                label="Export optimals set (IDs)",
                data=convert_df(data_export),
                file_name='MLB_optimals_export.csv',
                mime='text/csv',
            )
            st.download_button(
                label="Export optimals set (Names)",
                data=convert_df(name_export),
                file_name='MLB_optimals_export.csv',
                mime='text/csv',
            )
        
    if site_var == 'Draftkings':
        if 'working_seed' in st.session_state:
            st.session_state.working_seed = st.session_state.working_seed
            if player_var1 == 'Specific Players':
                st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
            elif player_var1 == 'Full Slate':
                st.session_state.working_seed = dk_lineups.copy()
            st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
        elif 'working_seed' not in st.session_state:
            st.session_state.working_seed = dk_lineups.copy()
            st.session_state.working_seed = st.session_state.working_seed
            if player_var1 == 'Specific Players':
                st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
            elif player_var1 == 'Full Slate':
                st.session_state.working_seed = dk_lineups.copy()
            st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
        
    elif site_var == 'Fanduel':
        if 'working_seed' in st.session_state:
            st.session_state.working_seed = st.session_state.working_seed
            if player_var1 == 'Specific Players':
                st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
            elif player_var1 == 'Full Slate':
                st.session_state.working_seed = fd_lineups.copy()
            st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
        elif 'working_seed' not in st.session_state:
            st.session_state.working_seed = fd_lineups.copy()
            st.session_state.working_seed = st.session_state.working_seed
            if player_var1 == 'Specific Players':
                st.session_state.working_seed = st.session_state.working_seed[np.equal.outer(st.session_state.working_seed, player_var2).any(axis=1).all(axis=1)]
            elif player_var1 == 'Full Slate':
                st.session_state.working_seed = fd_lineups.copy()
            st.session_state.data_export_display = pd.DataFrame(st.session_state.working_seed[0:lineup_num_var], columns=column_names)
    st.session_state.data_export_display = st.session_state.data_export_display[st.session_state.data_export_display['salary'] >= salary_min_var]
    st.session_state.data_export_display = st.session_state.data_export_display[st.session_state.data_export_display['salary'] <= salary_max_var]
    export_file = st.session_state.data_export_display.copy()
    name_export = st.session_state.data_export_display.copy()
    if site_var == 'Draftkings':
        if slate_type_var3 == 'Regular':
            map_columns = ['SP1', 'SP2', 'C', '1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3']
        elif slate_type_var3 == 'Showdown':
            map_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4', 'FLEX5']
        for col_idx in map_columns:
            export_file[col_idx] = export_file[col_idx].map(dk_id_map)
    elif site_var == 'Fanduel':
        if slate_type_var3 == 'Regular':
            map_columns = ['P', 'C_1B', '2B', '3B', 'SS', 'OF1', 'OF2', 'OF3', 'UTIL']
        elif slate_type_var3 == 'Showdown':
            map_columns = ['CPT', 'FLEX1', 'FLEX2', 'FLEX3', 'FLEX4']
        for col_idx in map_columns:
            export_file[col_idx] = export_file[col_idx].map(fd_id_map)
            
    with st.container():
        if st.button("Reset Optimals", key='reset3'):
            for key in st.session_state.keys():
                del st.session_state[key]
            if site_var == 'Draftkings':
                st.session_state.working_seed = dk_lineups.copy()
            elif site_var == 'Fanduel':
                st.session_state.working_seed = fd_lineups.copy()
        if 'data_export_display' in st.session_state:
            st.dataframe(st.session_state.data_export_display.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').format(precision=2), height=500, use_container_width = True)
        st.download_button(
            label="Export display optimals (IDs)",
            data=convert_df(export_file),
            file_name='MLB_display_optimals.csv',
            mime='text/csv',
        )
        st.download_button(
            label="Export display optimals (Names)",
            data=convert_df(name_export),
            file_name='MLB_display_optimals.csv',
            mime='text/csv',
        )
    
    with st.container():
        if slate_type_var3 == 'Regular':
            if 'working_seed' in st.session_state:
                # Create a new dataframe with summary statistics
                if site_var == 'Draftkings':
                    summary_df = pd.DataFrame({
                        'Metric': ['Min', 'Average', 'Max', 'STDdev'],
                        'Salary': [
                            np.min(st.session_state.working_seed[:,10]),
                            np.mean(st.session_state.working_seed[:,10]),
                            np.max(st.session_state.working_seed[:,10]),
                            np.std(st.session_state.working_seed[:,10])
                        ],
                        'Proj': [
                            np.min(st.session_state.working_seed[:,11]),
                            np.mean(st.session_state.working_seed[:,11]),
                            np.max(st.session_state.working_seed[:,11]),
                            np.std(st.session_state.working_seed[:,11])
                        ],
                        'Own': [
                            np.min(st.session_state.working_seed[:,16]),
                            np.mean(st.session_state.working_seed[:,16]),
                            np.max(st.session_state.working_seed[:,16]),
                            np.std(st.session_state.working_seed[:,16])
                        ]
                    })
                elif site_var == 'Fanduel':
                    summary_df = pd.DataFrame({
                        'Metric': ['Min', 'Average', 'Max', 'STDdev'],
                        'Salary': [
                            np.min(st.session_state.working_seed[:,9]),
                            np.mean(st.session_state.working_seed[:,9]),
                            np.max(st.session_state.working_seed[:,9]),
                            np.std(st.session_state.working_seed[:,9])
                        ],
                        'Proj': [
                            np.min(st.session_state.working_seed[:,10]),
                            np.mean(st.session_state.working_seed[:,10]),
                            np.max(st.session_state.working_seed[:,10]),
                            np.std(st.session_state.working_seed[:,10])
                        ],
                        'Own': [
                            np.min(st.session_state.working_seed[:,15]),
                            np.mean(st.session_state.working_seed[:,15]),
                            np.max(st.session_state.working_seed[:,15]),
                            np.std(st.session_state.working_seed[:,15])
                        ]
                    })

                # Set the index of the summary dataframe as the "Metric" column
                summary_df = summary_df.set_index('Metric')

                # Display the summary dataframe
                st.subheader("Optimal Statistics")
                st.dataframe(summary_df.style.format({
                    'Salary': '{:.2f}',
                    'Proj': '{:.2f}',
                    'Own': '{:.2f}'
                }).background_gradient(cmap='RdYlGn', axis=0, subset=['Salary', 'Proj', 'Own']), use_container_width=True)

    with st.container():
        tab1, tab2 = st.tabs(["Display Frequency", "Seed Frame Frequency"])
        with tab1:
            if 'data_export_display' in st.session_state:
                if site_var == 'Draftkings':
                    if slate_type_var3 == 'Regular':
                        player_columns = st.session_state.data_export_display.iloc[:, :10]
                    elif slate_type_var3 == 'Showdown':
                        player_columns = st.session_state.data_export_display.iloc[:, :6]
                elif site_var == 'Fanduel':
                    if slate_type_var3 == 'Regular':
                        player_columns = st.session_state.data_export_display.iloc[:, :9]
                    elif slate_type_var3 == 'Showdown':
                        player_columns = st.session_state.data_export_display.iloc[:, :5]
                
                # Flatten the DataFrame and count unique values
                value_counts = player_columns.values.flatten().tolist()
                value_counts = pd.Series(value_counts).value_counts()
                
                percentages = (value_counts / lineup_num_var * 100).round(2)
                
                # Create a DataFrame with the results
                summary_df = pd.DataFrame({
                    'Player': value_counts.index,
                    'Frequency': value_counts.values,
                    'Percentage': percentages.values
                })
                
                # Sort by frequency in descending order
                summary_df['Salary'] = summary_df['Player'].map(player_salaries)
                summary_df = summary_df[['Player', 'Salary', 'Frequency', 'Percentage']]
                summary_df = summary_df.sort_values('Frequency', ascending=False)
                summary_df = summary_df.set_index('Player')
                
                # Display the table
                st.write("Player Frequency Table:")
                st.dataframe(summary_df.style.format({'Percentage': '{:.2f}%'}), height=500, use_container_width=True)
            
                st.download_button(
                    label="Export player frequency",
                    data=convert_df_to_csv(summary_df),
                    file_name='MLB_player_frequency.csv',
                    mime='text/csv',
                )
        with tab2:
            if 'working_seed' in st.session_state:
                if site_var == 'Draftkings':
                    if slate_type_var3 == 'Regular':
                        player_columns = st.session_state.working_seed[:, :10]
                    elif slate_type_var3 == 'Showdown':
                        player_columns = st.session_state.working_seed[:, :7]
                elif site_var == 'Fanduel':
                    if slate_type_var3 == 'Regular':
                        player_columns = st.session_state.working_seed[:, :9]
                    elif slate_type_var3 == 'Showdown':
                        player_columns = st.session_state.working_seed[:, :6]
                
                # Flatten the DataFrame and count unique values
                value_counts = player_columns.flatten().tolist()
                value_counts = pd.Series(value_counts).value_counts()
                
                percentages = (value_counts / len(st.session_state.working_seed) * 100).round(2)
                # Create a DataFrame with the results
                summary_df = pd.DataFrame({
                    'Player': value_counts.index,
                    'Frequency': value_counts.values,
                    'Percentage': percentages.values
                })
                
                # Sort by frequency in descending order
                summary_df['Salary'] = summary_df['Player'].map(player_salaries)
                summary_df = summary_df[['Player', 'Salary', 'Frequency', 'Percentage']]
                summary_df = summary_df.sort_values('Frequency', ascending=False)
                summary_df = summary_df.set_index('Player')
                
                # Display the table
                st.write("Seed Frame Frequency Table:")
                st.dataframe(summary_df.style.format({'Percentage': '{:.2f}%'}), height=500, use_container_width=True)
            
                st.download_button(
                    label="Export seed frame frequency",
                    data=convert_df_to_csv(summary_df),
                    file_name='MLB_seed_frame_frequency.csv',
                    mime='text/csv',
                )

with tab4:
    st.header("Handbuilder")

    # --- POSITION LIMITS ---
    position_limits = {
        'SP': 2,
        'C': 1,
        '1B': 1,
        '2B': 1,
        '3B': 1,
        'SS': 1,
        'OF': 3,
        # Add more as needed
    }

    # --- LINEUP STATE ---
    if 'handbuilder_lineup' not in st.session_state:
        st.session_state['handbuilder_lineup'] = pd.DataFrame(columns=['Player', 'Order', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Own%'])
    if 'handbuilder_select_key' not in st.session_state:
        st.session_state['handbuilder_select_key'] = 0

    # Count positions in the current lineup
    lineup = st.session_state['handbuilder_lineup']
    slot_counts = lineup['Slot'].value_counts() if not lineup.empty else {}

    # --- TEAM FILTER UI ---
    with st.expander("Team Filters"):
        all_teams = sorted(dk_roo['Team'].unique())
        st.markdown("**Toggle teams to include:**")
        team_cols = st.columns(len(all_teams) // 2 + 1)
    
    selected_teams = []
    for idx, team in enumerate(all_teams):
        col = team_cols[idx % len(team_cols)]
        if f"handbuilder_team_{team}" not in st.session_state:
            st.session_state[f"handbuilder_team_{team}"] = False
        checked = col.toggle(team, value=st.session_state[f"handbuilder_team_{team}"], key=f"handbuilder_team_{team}")
        if checked:
            selected_teams.append(team)

    # If no teams selected, show all teams
    if selected_teams:
        player_select_df = dk_roo[
            dk_roo['Team'].isin(selected_teams)
        ][['Player', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Order', 'Hand', 'Own%']].drop_duplicates(subset=['Player', 'Team']).sort_values(by='Order', ascending=True).copy()
    else:
        player_select_df = dk_roo[['Player', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Order', 'Hand', 'Own%']].drop_duplicates(subset=['Player', 'Team']).copy()

    # --- FILTER OUT PLAYERS WHOSE ALL ELIGIBLE POSITIONS ARE FILLED ---
    def is_player_eligible(row):
        eligible_positions = re.split(r'[/, ]+', row['Position'])
        # Player is eligible if at least one of their positions is not at max
        for pos in eligible_positions:
            if slot_counts.get(pos, 0) < position_limits.get(pos, 0):
                return True
        return False

    # player_select_df = player_select_df[player_select_df.apply(is_player_eligible, axis=1)]

    col1, col2 = st.columns([1, 2])
    with col2:
        st.subheader("Player Select")
        event = st.dataframe(
            player_select_df.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn').background_gradient(cmap='RdYlGn_r', subset=['Order', 'Salary', 'Own%']).format(precision=2),
            on_select="rerun",
            selection_mode=["single-row"],
            key=f"handbuilder_select_{st.session_state['handbuilder_select_key']}",
            height=500,
            hide_index=True
        )
        # If a row is selected, add that player to the lineup and reset selection
        if event and "rows" in event.selection and len(event.selection["rows"]) > 0:
            idx = event.selection["rows"][0]
            player_row = player_select_df.iloc[[idx]]
            eligible_positions = re.split(r'[/, ]+', player_row['Position'].iloc[0])
            # Find the first eligible slot that is not full
            slot_to_fill = None
            for pos in eligible_positions:
                if slot_counts.get(pos, 0) < position_limits.get(pos, 0):
                    slot_to_fill = pos
                    break
            if slot_to_fill is not None:
                # Avoid duplicates
                if not player_row['Player'].iloc[0] in st.session_state['handbuilder_lineup']['Player'].values:
                    # Add the slot info
                    player_row = player_row.assign(Slot=slot_to_fill)
                    st.session_state['handbuilder_lineup'] = pd.concat(
                        [st.session_state['handbuilder_lineup'], player_row[['Player', 'Order', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Own%', 'Slot']]],
                        ignore_index=True
                    )
                st.session_state['handbuilder_select_key'] += 1
                st.rerun()
        
        with st.expander("Quick Fill Options"):
                auto_team_var = st.selectbox("Auto Fill Team", options=all_teams)
                auto_size_var = st.selectbox("Auto Fill Size", options=[3, 4, 5])
                auto_range_var = st.selectbox("Auto Fill Order", options=['Top', 'Mid', 'Wrap'])
                # --- QUICK FILL LOGIC ---
                if st.button("Quick Fill", key="quick_fill"):
                    # 1. Get all eligible players from the selected team, not already in the lineup
                    current_players = set(st.session_state['handbuilder_lineup']['Player'])
                    team_players = player_select_df[
                        (player_select_df['Team'] == auto_team_var) &
                        (~player_select_df['Player'].isin(current_players))
                    ].copy()

                    # 2. Sort by Order
                    team_players = team_players.sort_values(by='Order')

                    # 3. Select the order range
                    if auto_range_var == 'Top':
                        selected_players = team_players[team_players['Order'] > 0].head(auto_size_var)
                    elif auto_range_var == 'Mid':
                        mid_start = max(0, (len(team_players[team_players['Order'] > 0]) - auto_size_var) // 2)
                        selected_players = team_players[team_players['Order'] > 0].iloc[mid_start:mid_start + auto_size_var]
                    elif auto_range_var == 'Wrap':
                        selected_players = team_players[team_players['Order'] > 0].tail(auto_size_var)
                    else:
                        selected_players = team_players[team_players['Order'] > 0].head(auto_size_var)

                    # 4. Add each player to the lineup, filling the first available eligible slot
                    for _, player_row in selected_players.iterrows():
                        eligible_positions = re.split(r'[/, ]+', player_row['Position'])
                        slot_to_fill = None
                        for pos in eligible_positions:
                            if slot_counts.get(pos, 0) < position_limits.get(pos, 0):
                                slot_to_fill = pos
                                break
                        if slot_to_fill is not None:
                            # Avoid duplicates
                            if player_row['Player'] not in st.session_state['handbuilder_lineup']['Player'].values:
                                add_row = player_row.copy()
                                add_row['Slot'] = slot_to_fill
                                st.session_state['handbuilder_lineup'] = pd.concat(
                                    [st.session_state['handbuilder_lineup'], pd.DataFrame([add_row[[
                                        'Player', 'Order', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Own%', 'Slot'
                                    ]]])],
                                    ignore_index=True
                                )
                                # Update slot_counts for next player
                                slot_counts[slot_to_fill] = slot_counts.get(slot_to_fill, 0) + 1
                    st.rerun()


    with col1:
        st.subheader("Lineup Build")

        # --- EXPLICIT LINEUP ORDER ---
        lineup_slots = ['SP', 'SP', 'C', '1B', '2B', '3B', 'SS', 'OF', 'OF', 'OF']
        display_columns = ['Slot', 'Player', 'Order', 'Team', 'Salary', 'Median', 'Own%']

        filled_lineup = st.session_state['handbuilder_lineup']
        display_rows = []
        used_indices = set()
        if not filled_lineup.empty:
            for slot in lineup_slots:
                match = filled_lineup[(filled_lineup['Slot'] == slot) & (~filled_lineup.index.isin(used_indices))]
                if not match.empty:
                    row = match.iloc[0]
                    used_indices.add(match.index[0])
                    display_rows.append({
                        'Slot': slot,
                        'Player': row['Player'],
                        'Order': row['Order'],
                        'Position': row['Position'],
                        'Team': row['Team'],
                        'Salary': row['Salary'],
                        'Median': row['Median'],
                        '2x%': row['2x%'],
                        'Own%': row['Own%']
                    })
                else:
                    display_rows.append({
                        'Slot': slot,
                        'Player': '',
                        'Order': np.nan,
                        'Position': '',
                        'Team': '',
                        'Salary': np.nan,
                        'Median': np.nan,
                        '2x%': np.nan,
                        'Own%': np.nan
                    })

        lineup_display_df = pd.DataFrame(display_rows, columns=display_columns)

        # Show the lineup table with single-row selection for removal
        event_remove = st.dataframe(
            lineup_display_df.style.background_gradient(axis=0).background_gradient(cmap='RdYlGn', subset=['Median']).background_gradient(cmap='RdYlGn_r', subset=['Order', 'Salary', 'Own%']).format(precision=2),
            on_select="rerun",
            selection_mode=["single-row"],
            key="lineup_remove",
            height=445,
            hide_index=True
        )

        # If a row is selected and not blank, remove that player from the lineup
        if event_remove and "rows" in event_remove.selection and len(event_remove.selection["rows"]) > 0:
            idx = event_remove.selection["rows"][0]
            player_to_remove = lineup_display_df.iloc[idx]['Player']
            slot_to_remove = lineup_display_df.iloc[idx]['Slot']
            if player_to_remove:  # Only remove if not blank
                st.session_state['handbuilder_lineup'] = filled_lineup[
                    ~((filled_lineup['Player'] == player_to_remove) & (filled_lineup['Slot'] == slot_to_remove))
                ]
                st.rerun()

        # --- SUMMARY ROW ---
        if not filled_lineup.empty:
            total_salary = filled_lineup['Salary'].sum()
            total_median = filled_lineup['Median'].sum()
            avg_2x = filled_lineup['2x%'].mean()
            total_own = filled_lineup['Own%'].sum()
            most_common_team = filled_lineup['Team'].mode()[0] if not filled_lineup['Team'].mode().empty else ""

            summary_row = pd.DataFrame({
                'Slot': [''],
                'Player': ['TOTAL'],
                'Order': [''],
                'Position': [''],
                'Team': [most_common_team],
                'Salary': [total_salary],
                'Median': [total_median],
                '2x%': [avg_2x],
                'Own%': [total_own]
            })
            summary_row = summary_row[['Salary', 'Median', 'Own%']].head(10)
            
            if screen_width < 700:
                # Mobile: Only two columns
                col1, col3 = st.columns([2, 3])
                col2 = None
            else:
                col1, col2, col3 = st.columns([2, 1, 3])
            with col1:
                if (10 - len(filled_lineup)) > 0:
                    st.markdown(f"""
                            <div style='text-align: left'>
                                <b>πŸ’° Per Player:</b> ${round((50000 - total_salary) / (10 - len(filled_lineup)), 0)} &nbsp;
                            </div>
                            """,
                            unsafe_allow_html=True)
                else:
                    st.markdown(f"""
                            <div style='text-align: left'>
                                <b>πŸ’° Leftover:</b> ${round(50000 - total_salary, 0)} &nbsp;
                            </div>
                            """,
                            unsafe_allow_html=True)

            with col3:
                if total_salary <= 50000:
                    st.markdown(
                        f"""
                        <div style='text-align: right'>
                            <b>πŸ’° Salary:</b> ${round(total_salary, 0)} &nbsp;
                            <b>πŸ”₯ Median:</b> {round(total_median, 2)} &nbsp;
                        </div>
                        """,
                        unsafe_allow_html=True
                    )
                else:
                    st.markdown(
                        f"""
                        <div style='text-align: right'>
                            <b>❌ Salary:</b> ${round(total_salary, 0)} &nbsp;
                            <b>πŸ”₯ Median:</b> {round(total_median, 2)} &nbsp;
                        </div>
                        """,
                        unsafe_allow_html=True
                    )

    # Optionally, add a button to clear the lineup
    if st.button("Clear Lineup", key='clear_lineup'):
        st.session_state['handbuilder_lineup'] = pd.DataFrame(columns=['Player', 'Position', 'Team', 'Salary', 'Median', '2x%', 'Own%', 'Slot', 'Order'])
        st.rerun()