File size: 48,811 Bytes
93b4e36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Key fixes for deployment:

# โœ… Converted numpy.int64 to Python int
# โœ… Set share=True in launch()
# โœ… Added warnings filter
# โœ… All values converted to standard Python types

# The complete working code is in the artifact above. Just copy it and run!

import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import warnings
warnings.filterwarnings('ignore')

# Load data
df = pd.read_csv('nba_games1_feature_engineered.csv')
df['GAME_DATE_EST'] = pd.to_datetime(df['GAME_DATE_EST'])

# Extract unique teams and seasons - CONVERT TO PYTHON INT
teams = [int(x) for x in sorted(set(df['HOME_TEAM_ID']).union(set(df['VISITOR_TEAM_ID'])))]
seasons = [int(x) for x in sorted(df['SEASON'].unique())]

COLORS = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E2', '#F8B739', '#52B788']
DARK_BG = '#000000'

plt.style.use('dark_background')
plt.rcParams['font.family'] = 'monospace'

def filter_df(sel_seasons, sel_teams):
    d = df.copy()
    if sel_seasons: 
        d = d[d['SEASON'].isin(sel_seasons)]
    if sel_teams:
        d = d[(d['HOME_TEAM_ID'].isin(sel_teams)) | (d['VISITOR_TEAM_ID'].isin(sel_teams))]
    return d

# [Include all 9 tab functions here - match_outcomes, scoring_shooting, possession_control, etc.]
def match_outcomes(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        x = np.arange(len(teams_to_plot))
        width = 0.35
        
        home_wins = []
        away_wins = []
        
        for team in teams_to_plot:
            team_home = d[d['HOME_TEAM_ID'] == team]['HOME_WIN'].sum()
            team_away = d[d['VISITOR_TEAM_ID'] == team]['AWAY_WIN'].sum()
            home_wins.append(team_home)
            away_wins.append(team_away)
        
        bars1 = ax1.bar(x - width/2, home_wins, width, label='Home Wins', color='#FF3333', edgecolor='white', linewidth=2)
        bars2 = ax1.bar(x + width/2, away_wins, width, label='Away Wins', color='#4ECDC4', edgecolor='white', linewidth=2)
        
        for bar in bars1:
            height = bar.get_height()
            if height > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', 
                        ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        for bar in bars2:
            height = bar.get_height()
            if height > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', 
                        ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        
        ax1.set_xticks(x)
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('๐Ÿ€ Home vs Away Wins - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.legend(fontsize=12, framealpha=0.9)
    else:
        wins_data = pd.Series({
            "Home Wins": d['HOME_WIN'].sum(),
            "Away Wins": d['AWAY_WIN'].sum()
        })
        bars = ax1.bar(wins_data.index, wins_data.values, color=['#FF3333', '#4ECDC4'], width=0.6, edgecolor='white', linewidth=2)
        
        for bar in bars:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', 
                    ha='center', va='bottom', fontsize=14, fontweight='bold', color='white')
        
        ax1.set_title('๐Ÿ€ Home vs Away Wins - Overall', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax1.set_ylabel('Number of Games', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
                season_home = team_data[team_data['HOME_TEAM_ID'] == team].groupby('SEASON')['HOME_WIN'].sum()
                season_away = team_data[team_data['VISITOR_TEAM_ID'] == team].groupby('SEASON')['AWAY_WIN'].sum()
                total_wins = season_home.add(season_away, fill_value=0)
                
                ax2.plot(total_wins.index, total_wins.values, marker='o', linewidth=3, 
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            ax2.set_title('๐Ÿ“ˆ Win Trends Across Seasons - By Team', fontsize=18, fontweight='bold', pad=20, color='white')
        else:
            home_by_season = d.groupby('SEASON')['HOME_WIN'].sum()
            away_by_season = d.groupby('SEASON')['AWAY_WIN'].sum()
            
            ax2.plot(home_by_season.index, home_by_season.values, marker='o', linewidth=3, 
                    label='Home Wins', color='#FF3333', markersize=10)
            ax2.plot(away_by_season.index, away_by_season.values, marker='s', linewidth=3, 
                    label='Away Wins', color='#4ECDC4', markersize=10)
            ax2.set_title('๐Ÿ“ˆ Win Trends Across Seasons - League Wide', fontsize=18, fontweight='bold', pad=20, color='white')
        
        ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
        ax2.set_ylabel('Total Wins', fontsize=14, fontweight='bold', color='white')
        ax2.legend(loc='best', fontsize=12, framealpha=0.9)
        ax2.tick_params(colors='white', labelsize=11)
        ax2.grid(alpha=0.3, linestyle='--', color='gray')
    else:
        game_types = pd.Series({
            "Close": d['CLOSE_GAME_FLAG'].sum(),
            "Blowout": d['BLOWOUT_FLAG'].sum(),
            "Normal": len(d) - d['CLOSE_GAME_FLAG'].sum() - d['BLOWOUT_FLAG'].sum()
        })
        
        colors_pie = ['#45B7D1', '#FF3333', '#98D8C8']
        wedges, texts, autotexts = ax2.pie(game_types.values, labels=game_types.index, autopct='%1.1f%%',
                                             colors=colors_pie, startangle=90, textprops={'fontsize': 14, 'fontweight': 'bold'},
                                             explode=[0.05, 0.05, 0.05])
        
        for autotext in autotexts:
            autotext.set_color('white')
            autotext.set_fontsize(13)
        for text in texts:
            text.set_color('white')
            text.set_fontsize(14)
        
        ax2.set_title('๐Ÿ“Š Game Type Distribution', fontsize=18, fontweight='bold', pad=20, color='white')
    
    plt.tight_layout()
    return fig1, fig2

# ---------- TAB 2: Scoring & Shooting ----------
def scoring_shooting(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        team_avg_points = []
        
        for team in teams_to_plot:
            team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
            avg_pts = team_data['TOTAL_PTS'].mean()
            team_avg_points.append(avg_pts)
        
        bars = ax1.bar(range(len(teams_to_plot)), team_avg_points,
                      color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))],
                      edgecolor='white', linewidth=2, width=0.7)
        
        for i, bar in enumerate(bars):
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.1f}', ha='center', va='bottom', fontsize=12, fontweight='bold', color='white')
        
        ax1.set_xticks(range(len(teams_to_plot)))
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('๐ŸŽฏ Average Total Points - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white')
    else:
        season_avg = d.groupby('SEASON')['TOTAL_PTS'].mean()
        bars = ax1.bar(season_avg.index, season_avg.values, color='#FF3333', edgecolor='white', linewidth=2)
        
        for bar in bars:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.1f}', ha='center', va='bottom', fontsize=11, color='white')
        
        ax1.set_title('๐ŸŽฏ Season-wise Avg Total Points', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax1.set_ylabel('Avg Points', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
                season_avg = team_data.groupby('SEASON')['TOTAL_PTS'].mean()
                ax2.plot(season_avg.index, season_avg.values, marker='o', linewidth=3,
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            ax2.set_title('๐Ÿ“ˆ Scoring Trends Across Seasons - By Team', fontsize=18, fontweight='bold', pad=20, color='white')
        else:
            season_avg = d.groupby('SEASON')['TOTAL_PTS'].mean()
            ax2.plot(season_avg.index, season_avg.values, marker='o', linewidth=4,
                    color='#FF3333', markersize=12, markerfacecolor='#4ECDC4',
                    markeredgecolor='white', markeredgewidth=2)
            ax2.set_title('๐Ÿ“ˆ League-wide Scoring Trend', fontsize=18, fontweight='bold', pad=20, color='white')
        
        ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
        ax2.set_ylabel('Avg Total Points', fontsize=14, fontweight='bold', color='white')
        ax2.legend(loc='best', fontsize=12, framealpha=0.9)
        ax2.tick_params(colors='white', labelsize=11)
    else:
        shooting_diff = d[['FG_PCT_DIFF', 'FT_PCT_DIFF', 'FG3_PCT_DIFF']].mean()
        bars = ax2.bar(['FG %', 'FT %', '3PT %'], shooting_diff.values,
                      color=['#FF3333', '#4ECDC4', '#45B7D1'], edgecolor='white', linewidth=2, width=0.6)
        
        for bar in bars:
            height = bar.get_height()
            ax2.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.4f}', ha='center', va='bottom' if height > 0 else 'top', 
                    fontsize=12, fontweight='bold', color='white')
        
        ax2.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5)
        ax2.set_title('๐ŸŽฏ Average Shooting Superiority (Home - Away)', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white')
        ax2.tick_params(colors='white', labelsize=11)
    
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# ---------- TAB 9: Forecasting ----------
def forecasting_analysis(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    # Single Plot: Team-wise Scoring Trends (Actual Only)
    fig1, ax1 = plt.subplots(figsize=(10, 6), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        # Plot multiple teams
        for idx, team in enumerate(sel_teams[:5]):
            team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
            trend = team_data.groupby('SEASON')['TOTAL_PTS'].mean()
            
            if len(trend) > 0:
                ax1.plot(trend.index, trend.values, marker='o', linewidth=3, 
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
        
        ax1.set_title('๐Ÿ“ˆ NBA Scoring Trend - Team Comparison', fontsize=20, fontweight='bold', pad=20, color='white')
    else:
        # Overall league trend
        trend = d.groupby('SEASON')['TOTAL_PTS'].mean()
        
        if len(trend) > 0:
            ax1.plot(trend.index, trend.values, marker='o', linewidth=4, 
                    label='League Average', color='#FF3333', markersize=12)
            
            ax1.set_title('๐Ÿ“ˆ NBA Scoring Trend - League Wide', fontsize=20, fontweight='bold', pad=20, color='white')
    
    ax1.set_xlabel('Season', fontsize=16, fontweight='bold', color='white')
    ax1.set_ylabel('Avg Total Points', fontsize=16, fontweight='bold', color='white')
    ax1.legend(loc='best', fontsize=13, framealpha=0.9)
    ax1.tick_params(colors='white', labelsize=12)
    ax1.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    return fig1

# ---------- TAB 3: Possession Control ----------
def possession_control(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        x = np.arange(len(teams_to_plot))
        width = 0.35
        
        ast_vals = []
        reb_vals = []
        
        for team in teams_to_plot:
            team_data = d[(d['HOME_TEAM_ID']==team) | (d['VISITOR_TEAM_ID']==team)]
            ast_vals.append(team_data['AST_DIFF'].mean())
            reb_vals.append(team_data['REB_DIFF'].mean())
        
        bars1 = ax1.bar(x - width/2, ast_vals, width, label='AST Diff', color='#FF3333', edgecolor='white', linewidth=2)
        bars2 = ax1.bar(x + width/2, reb_vals, width, label='REB Diff', color='#4ECDC4', edgecolor='white', linewidth=2)
        
        ax1.set_xticks(x)
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('๐Ÿ‹ Assist & Rebound Advantage by Team', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.legend(fontsize=12, framealpha=0.9)
    else:
        diff_data = d[['AST_DIFF', 'REB_DIFF']].mean()
        bars = ax1.bar(['AST Diff', 'REB Diff'], diff_data.values, 
                       color=['#FF3333', '#4ECDC4'], edgecolor='white', linewidth=2, width=0.5)
        
        for bar in bars:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.2f}', ha='center', va='bottom' if height > 0 else 'top', 
                    fontsize=13, fontweight='bold', color='white')
        
        ax1.set_title('๐Ÿ‹ Average Assist & Rebound Advantage', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax1.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5)
    ax1.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        season_ast = d.groupby('SEASON')['AST_DIFF'].mean()
        season_reb = d.groupby('SEASON')['REB_DIFF'].mean()
        
        ax2.plot(season_ast.index, season_ast.values, marker='o', linewidth=3, 
                label='AST Diff', color='#FF3333', markersize=10)
        ax2.plot(season_reb.index, season_reb.values, marker='s', linewidth=3, 
                label='REB Diff', color='#4ECDC4', markersize=10)
        
        ax2.set_title('๐Ÿ“ˆ Season Trend: Assists & Rebounds', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
        ax2.set_ylabel('Avg Difference', fontsize=14, fontweight='bold', color='white')
        ax2.legend(fontsize=12, framealpha=0.9)
        ax2.tick_params(colors='white', labelsize=11)
    else:
        home_ast = d.groupby('HOME_TEAM_ID')['AST_DIFF'].mean()
        away_ast = d.groupby('VISITOR_TEAM_ID')['AST_DIFF'].mean()
        combined_ast = pd.concat([home_ast, away_ast]).groupby(level=0).mean().sort_values(ascending=False).head(10)
        
        bars = ax2.barh(range(len(combined_ast)), combined_ast.values, color='#45B7D1', edgecolor='white', linewidth=2)
        ax2.set_yticks(range(len(combined_ast)))
        ax2.set_yticklabels([f'Team {int(t)}' for t in combined_ast.index], fontsize=11, color='white')
        ax2.set_title('๐Ÿ† Top 10 Teams by Assist Advantage', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_xlabel('Avg AST Difference', fontsize=14, fontweight='bold', color='white')
        ax2.tick_params(colors='white', labelsize=11)
    
    ax2.axvline(x=0, color='white', linestyle='-', linewidth=1, alpha=0.5)
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# ---------- TAB 4: Game Intensity ----------
def game_intensity(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        pace_by_team = []
        
        for team in teams_to_plot:
            team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
            pace_by_team.append(team_data['GAME_PACE_SCORE'].mean())
        
        bars = ax1.bar(range(len(teams_to_plot)), pace_by_team,
                      color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))],
                      edgecolor='white', linewidth=2, width=0.7)
        
        for i, bar in enumerate(bars):
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.2f}', ha='center', va='bottom', fontsize=12, fontweight='bold', color='white')
        
        ax1.set_xticks(range(len(teams_to_plot)))
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('โšก Average Game Pace - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white')
    else:
        ax1.hist(d['GAME_PACE_SCORE'], bins=30, color='#4ECDC4', edgecolor='white', linewidth=2, alpha=0.8)
        ax1.axvline(d['GAME_PACE_SCORE'].mean(), color='#FF3333', linestyle='--', linewidth=3, 
                   label=f"Mean: {d['GAME_PACE_SCORE'].mean():.2f}")
        ax1.set_title('โšก Game Pace Distribution', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.set_xlabel('Game Pace Score', fontsize=14, fontweight='bold', color='white')
        ax1.legend(fontsize=12, framealpha=0.9)
    
    ax1.set_ylabel('Avg Pace Score' if sel_teams else 'Frequency', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
                pace_trend = team_data.groupby('SEASON')['GAME_PACE_SCORE'].mean()
                ax2.plot(pace_trend.index, pace_trend.values, marker='o', linewidth=3,
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            ax2.set_title('๐Ÿ“ˆ Game Pace Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white')
        else:
            pace_trend = d.groupby('SEASON')['GAME_PACE_SCORE'].mean()
            ax2.plot(pace_trend.index, pace_trend.values, marker='o', linewidth=4,
                    color='#45B7D1', markersize=12, markerfacecolor='#FF3333',
                    markeredgecolor='white', markeredgewidth=2)
            
            z = np.polyfit(pace_trend.index, pace_trend.values, 1)
            p = np.poly1d(z)
            ax2.plot(pace_trend.index, p(pace_trend.index), linestyle='--', 
                    color='#FFA07A', linewidth=3, alpha=0.7, label='Trend')
            
            ax2.set_title('๐Ÿ“ˆ NBA Game Pace Evolution', fontsize=18, fontweight='bold', pad=20, color='white')
        
        ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
        ax2.set_ylabel('Avg Game Pace Score', fontsize=14, fontweight='bold', color='white')
        ax2.legend(loc='best', fontsize=12, framealpha=0.9)
        ax2.tick_params(colors='white', labelsize=11)
    else:
        pace_by_season = d.groupby('SEASON')['GAME_PACE_SCORE'].mean()
        bars = ax2.bar(pace_by_season.index, pace_by_season.values, 
                      color='#FF3333', edgecolor='white', linewidth=2)
        
        for bar in bars:
            height = bar.get_height()
            ax2.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        
        ax2.set_title('โšก Average Game Pace by Season', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_ylabel('Avg Pace Score', fontsize=14, fontweight='bold', color='white')
        ax2.tick_params(colors='white', labelsize=11)
    
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# ---------- TAB 5: Home Advantage ----------
def home_advantage(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        home_dom_vals = []
        
        for team in teams_to_plot:
            team_home = d[d['HOME_TEAM_ID'] == team]['HOME_DOMINANCE_SCORE'].mean()
            home_dom_vals.append(team_home)
        
        bars = ax1.bar(range(len(teams_to_plot)), home_dom_vals,
                      color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))],
                      edgecolor='white', linewidth=2, width=0.7)
        
        for i, bar in enumerate(bars):
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.3f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        
        ax1.set_xticks(range(len(teams_to_plot)))
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('๐Ÿ  Home Dominance Score - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.set_ylabel('Dominance Score', fontsize=14, fontweight='bold', color='white')
    else:
        home_dom = d.groupby('HOME_TEAM_ID')['HOME_DOMINANCE_SCORE'].mean().sort_values(ascending=False).head(10)
        bars = ax1.barh(range(len(home_dom)), home_dom.values, 
                       color=[COLORS[i % len(COLORS)] for i in range(len(home_dom))],
                       edgecolor='white', linewidth=2)
        
        ax1.set_yticks(range(len(home_dom)))
        ax1.set_yticklabels([f'Team {int(t)}' for t in home_dom.index], fontsize=11, color='white')
        
        for i, bar in enumerate(bars):
            width = bar.get_width()
            ax1.text(width, bar.get_y() + bar.get_height()/2.,
                    f' {width:.3f}', ha='left', va='center', fontsize=11, fontweight='bold', color='white')
        
        ax1.set_title('๐Ÿ† Top 10 Home Dominant Teams', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.set_xlabel('Dominance Score', fontsize=14, fontweight='bold', color='white')
    
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[d['HOME_TEAM_ID'] == team]
                season_dom = team_data.groupby('SEASON')['HOME_DOMINANCE_SCORE'].mean()
                ax2.plot(season_dom.index, season_dom.values, marker='o', linewidth=3,
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            ax2.set_title('๐Ÿ“ˆ Home Dominance Trends', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Dominance Score', fontsize=14, fontweight='bold', color='white')
            ax2.legend(loc='best', fontsize=12, framealpha=0.9)
            ax2.tick_params(colors='white', labelsize=11)
        else:
            home_adv = d.groupby('SEASON')['HOME_DOMINANCE_SCORE'].mean()
            ax2.plot(home_adv.index, home_adv.values, marker='o', linewidth=4,
                    color='#FF3333', markersize=12, markerfacecolor='#4ECDC4',
                    markeredgecolor='white', markeredgewidth=2)
            ax2.set_title('๐Ÿ“ˆ Home Advantage Evolution', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Avg Dominance Score', fontsize=14, fontweight='bold', color='white')
            ax2.tick_params(colors='white', labelsize=11)
    else:
        shoot_edge = pd.cut(d['HOME_SHOOTING_EDGE'], bins=[-1, -0.05, 0.05, 1], 
                           labels=['Away Better', 'Even', 'Home Better'])
        edge_counts = shoot_edge.value_counts()
        
        colors_pie = ['#FF3333', '#FFA07A', '#4ECDC4']
        wedges, texts, autotexts = ax2.pie(edge_counts.values, labels=edge_counts.index, autopct='%1.1f%%',
                                            colors=colors_pie, startangle=90, 
                                            textprops={'fontsize': 14, 'fontweight': 'bold'},
                                            explode=[0.05, 0.05, 0.05])
        
        for autotext in autotexts:
            autotext.set_color('white')
            autotext.set_fontsize(13)
        for text in texts:
            text.set_color('white')
            text.set_fontsize(14)
        
        ax2.set_title('๐ŸŽฏ Home vs Away Shooting Superiority', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# Continue with remaining tabs (6, 7, 8) following the same pattern...
# For brevity, I'll include the complete UI section

# ---------- TAB 6: Team Momentum ----------
def team_momentum(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        momentum_home = []
        momentum_away = []
        
        for team in teams_to_plot:
            team_home = d[d['HOME_TEAM_ID'] == team]['HOME_LAST5_WINRATE'].mean()
            team_away = d[d['VISITOR_TEAM_ID'] == team]['AWAY_LAST5_WINRATE'].mean()
            momentum_home.append(team_home)
            momentum_away.append(team_away)
        
        x = np.arange(len(teams_to_plot))
        width = 0.35
        
        bars1 = ax1.bar(x - width/2, momentum_home, width, label='Home Momentum', 
                       color='#FF3333', edgecolor='white', linewidth=2)
        bars2 = ax1.bar(x + width/2, momentum_away, width, label='Away Momentum', 
                       color='#4ECDC4', edgecolor='white', linewidth=2)
        
        for bar in bars1:
            height = bar.get_height()
            if height > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., height,
                        f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        for bar in bars2:
            height = bar.get_height()
            if height > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., height,
                        f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        
        ax1.set_xticks(x)
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('โšก Team Momentum Comparison (Last-5 Win Rate)', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.legend(fontsize=12, framealpha=0.9)
    else:
        winrate_data = d[['HOME_LAST5_WINRATE', 'AWAY_LAST5_WINRATE']].mean()
        bars = ax1.bar(['Home Win Rate', 'Away Win Rate'], winrate_data.values,
                      color=['#FF3333', '#4ECDC4'], edgecolor='white', linewidth=2, width=0.6)
        
        for bar in bars:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.3f}', ha='center', va='bottom', fontsize=13, fontweight='bold', color='white')
        
        ax1.set_title('โšก Average Last-5 Games Win Rate', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax1.set_ylabel('Win Rate', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
                home_momentum = team_data[team_data['HOME_TEAM_ID'] == team].groupby('SEASON')['HOME_LAST5_WINRATE'].mean()
                away_momentum = team_data[team_data['VISITOR_TEAM_ID'] == team].groupby('SEASON')['AWAY_LAST5_WINRATE'].mean()
                combined_momentum = pd.concat([home_momentum, away_momentum]).groupby(level=0).mean()
                
                ax2.plot(combined_momentum.index, combined_momentum.values, marker='o', linewidth=3,
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            
            ax2.set_title('๐Ÿ“ˆ Momentum Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Avg Win Rate', fontsize=14, fontweight='bold', color='white')
            ax2.legend(loc='best', fontsize=12, framealpha=0.9)
            ax2.tick_params(colors='white', labelsize=11)
        else:
            home_trend = d.groupby('SEASON')['HOME_LAST5_WINRATE'].mean()
            away_trend = d.groupby('SEASON')['AWAY_LAST5_WINRATE'].mean()
            
            ax2.plot(home_trend.index, home_trend.values, marker='o', linewidth=3,
                    label='Home Momentum', color='#FF3333', markersize=10)
            ax2.plot(away_trend.index, away_trend.values, marker='s', linewidth=3,
                    label='Away Momentum', color='#4ECDC4', markersize=10)
            
            ax2.set_title('๐Ÿ“ˆ League Momentum Trend', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Avg Win Rate', fontsize=14, fontweight='bold', color='white')
            ax2.legend(loc='best', fontsize=12, framealpha=0.9)
            ax2.tick_params(colors='white', labelsize=11)
    else:
        momentum = pd.concat([
            d[['HOME_TEAM_ID', 'HOME_LAST5_WINRATE']].rename(columns={'HOME_TEAM_ID': 'TEAM', 'HOME_LAST5_WINRATE': 'WINRATE'}),
            d[['VISITOR_TEAM_ID', 'AWAY_LAST5_WINRATE']].rename(columns={'VISITOR_TEAM_ID': 'TEAM', 'AWAY_LAST5_WINRATE': 'WINRATE'})
        ])
        
        top_momentum = momentum.groupby('TEAM')['WINRATE'].mean().sort_values(ascending=False).head(10)
        bars = ax2.barh(range(len(top_momentum)), top_momentum.values,
                       color=[COLORS[i % len(COLORS)] for i in range(len(top_momentum))],
                       edgecolor='white', linewidth=2)
        
        ax2.set_yticks(range(len(top_momentum)))
        ax2.set_yticklabels([f'Team {int(t)}' for t in top_momentum.index], fontsize=11, color='white')
        
        for i, bar in enumerate(bars):
            width = bar.get_width()
            ax2.text(width, bar.get_y() + bar.get_height()/2.,
                    f' {width:.3f}', ha='left', va='center', fontsize=11, fontweight='bold', color='white')
        
        ax2.set_title('๐Ÿ† Top 10 Teams by Recent Momentum', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_xlabel('Avg Last-5 Win Rate', fontsize=14, fontweight='bold', color='white')
        ax2.tick_params(colors='white', labelsize=11)
    
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# ---------- TAB 7: Time Analysis ----------
def time_analysis(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    month_counts = d['GAME_MONTH'].value_counts().sort_index()
    bars = ax1.bar(month_counts.index, month_counts.values, 
                   color=[COLORS[i % len(COLORS)] for i in range(len(month_counts))],
                   edgecolor='white', linewidth=2)
    
    for bar in bars:
        height = bar.get_height()
        ax1.text(bar.get_x() + bar.get_width()/2., height,
                f'{int(height)}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
    
    ax1.set_title('๐Ÿ“… Games Played per Month', fontsize=18, fontweight='bold', pad=20, color='white')
    ax1.set_xlabel('Month', fontsize=14, fontweight='bold', color='white')
    ax1.set_ylabel('Number of Games', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    weekday_pace = d.groupby('GAME_WEEKDAY')['GAME_PACE_SCORE'].mean().sort_index()
    bars = ax2.bar(weekday_pace.index, weekday_pace.values, 
                   color=['#FF3333', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE'],
                   edgecolor='white', linewidth=2, width=0.7)
    
    for bar in bars:
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                f'{height:.2f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
    
    ax2.set_title('๐Ÿ“Š Game Pace by Day of Week', fontsize=18, fontweight='bold', pad=20, color='white')
    ax2.set_xlabel('Day of Week', fontsize=14, fontweight='bold', color='white')
    ax2.set_ylabel('Avg Pace Score', fontsize=14, fontweight='bold', color='white')
    ax2.tick_params(colors='white', labelsize=11)
    ax2.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    return fig1, fig2

# ---------- TAB 8: Margin Analysis ----------
def margin_analysis(sel_seasons, sel_teams):
    d = filter_df(sel_seasons, sel_teams)
    
    fig1, ax1 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax1.set_facecolor(DARK_BG)
    
    if sel_teams and len(sel_teams) > 0:
        teams_to_plot = sel_teams[:5]
        margin_vals = []
        
        for team in teams_to_plot:
            team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
            margin_vals.append(team_data['POINT_DIFF'].mean())
        
        bars = ax1.bar(range(len(teams_to_plot)), margin_vals,
                      color=[COLORS[i % len(COLORS)] for i in range(len(teams_to_plot))],
                      edgecolor='white', linewidth=2, width=0.7)
        
        for i, bar in enumerate(bars):
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.1f}', ha='center', va='bottom' if height > 0 else 'top', 
                    fontsize=12, fontweight='bold', color='white')
        
        ax1.set_xticks(range(len(teams_to_plot)))
        ax1.set_xticklabels([f'Team {t}' for t in teams_to_plot], fontsize=12, color='white')
        ax1.set_title('๐Ÿ“Š Average Winning Margin - Team Comparison', fontsize=18, fontweight='bold', pad=20, color='white')
        ax1.axhline(y=0, color='white', linestyle='-', linewidth=1, alpha=0.5)
    else:
        margin_by_season = d.groupby('SEASON')['POINT_DIFF'].mean()
        bars = ax1.bar(margin_by_season.index, margin_by_season.values, 
                       color='#FF3333', edgecolor='white', linewidth=2)
        
        for bar in bars:
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.1f}', ha='center', va='bottom', fontsize=11, fontweight='bold', color='white')
        
        ax1.set_title('๐Ÿ“Š Average Winning Margin by Season', fontsize=18, fontweight='bold', pad=20, color='white')
    
    ax1.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white')
    ax1.tick_params(colors='white', labelsize=11)
    ax1.grid(axis='y', alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    
    fig2, ax2 = plt.subplots(figsize=(12, 7), facecolor=DARK_BG)
    ax2.set_facecolor(DARK_BG)
    
    if sel_seasons and len(sel_seasons) > 1:
        if sel_teams and len(sel_teams) > 0:
            for idx, team in enumerate(sel_teams[:5]):
                team_data = d[(d['HOME_TEAM_ID'] == team) | (d['VISITOR_TEAM_ID'] == team)]
                margin_trend = team_data.groupby('SEASON')['POINT_DIFF'].mean()
                ax2.plot(margin_trend.index, margin_trend.values, marker='o', linewidth=3,
                        label=f'Team {team}', color=COLORS[idx % len(COLORS)], markersize=10)
            ax2.set_title('๐Ÿ“ˆ Margin Trends - By Team', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white')
            ax2.legend(loc='best', fontsize=12, framealpha=0.9)
            ax2.tick_params(colors='white', labelsize=11)
        else:
            margin_trend = d.groupby('SEASON')['POINT_DIFF'].mean()
            ax2.plot(margin_trend.index, margin_trend.values, marker='o', linewidth=4,
                    color='#FF3333', markersize=12, markerfacecolor='#4ECDC4',
                    markeredgecolor='white', markeredgewidth=2)
            ax2.set_title('๐Ÿ“ˆ Winning Margin Evolution', fontsize=18, fontweight='bold', pad=20, color='white')
            ax2.set_xlabel('Season', fontsize=14, fontweight='bold', color='white')
            ax2.set_ylabel('Avg Point Difference', fontsize=14, fontweight='bold', color='white')
            ax2.tick_params(colors='white', labelsize=11)
    else:
        ax2.hist(d['POINT_DIFF'], bins=40, color='#4ECDC4', edgecolor='white', linewidth=2, alpha=0.8)
        ax2.axvline(d['POINT_DIFF'].mean(), color='#FF3333', linestyle='--', linewidth=3, 
                   label=f"Mean: {d['POINT_DIFF'].mean():.2f}")
        ax2.axvline(d['POINT_DIFF'].median(), color='#FFA07A', linestyle='--', linewidth=3, 
                   label=f"Median: {d['POINT_DIFF'].median():.2f}")
        
        ax2.set_title('๐Ÿ“Š Point Difference Distribution', fontsize=18, fontweight='bold', pad=20, color='white')
        ax2.set_xlabel('Point Difference', fontsize=14, fontweight='bold', color='white')
        ax2.set_ylabel('Frequency', fontsize=14, fontweight='bold', color='white')
        ax2.legend(fontsize=12, framealpha=0.9)
        ax2.tick_params(colors='white', labelsize=11)
    
    ax2.grid(alpha=0.3, linestyle='--', color='gray')
    plt.tight_layout()
    return fig1, fig2

# UI
custom_css = """

@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&display=swap');



* {

    font-family: 'JetBrains Mono', monospace !important;

}



body, .gradio-container {

    background: #000000 !important;

    color: #FFFFFF !important;

}



.wrap {

    background: #000000 !important;

}



button {

    background: #FF3333 !important;

    color: white !important;

    font-weight: bold !important;

    border: 2px solid white !important;

    font-family: 'JetBrains Mono', monospace !important;

}



button:hover {

    background: #CC0000 !important;

    transform: scale(1.02);

}



.tabs button {

    background: #1a1a1a !important;

    border: 1px solid #FF3333 !important;

}



.tabs button.selected {

    background: #FF3333 !important;

}



label {

    color: #FFFFFF !important;

    font-weight: bold !important;

    font-size: 14px !important;

}



.dropdown {

    background: #1a1a1a !important;

    color: white !important;

    border: 2px solid #FF3333 !important;

}



h1, h2, h3, h4 {

    color: #FFFFFF !important;

}



.gr-box {

    border: 1px solid #333 !important;

    background: #0a0a0a !important;

}

"""

with gr.Blocks(theme=gr.themes.Base(primary_hue="red", secondary_hue="slate"), css=custom_css) as app:
    gr.Markdown("""

    # ๐Ÿ€ NBA INTERACTIVE ANALYTICS DASHBOARD

    ## Comprehensive Analysis of NBA Game Statistics

    """)
    
    gr.Markdown("""

    ### ๐Ÿ“‹ Instructions:

    - **For Team Comparison**: Select multiple teams (max 5) + one or any season

    - **For Season Analysis**: Select multiple seasons + one or any team

    """)

    with gr.Row():
        team_dd = gr.Dropdown(
            choices=teams, 
            multiselect=True, 
            label="๐Ÿ† SELECT TEAMS (Max 5)", 
            info="Choose 1-5 teams for comparison",
            max_choices=5
        )
        season_dd = gr.Dropdown(
            choices=seasons, 
            multiselect=True, 
            label="๐Ÿ—“๏ธ SELECT SEASONS", 
            info="Choose one or more seasons"
        )

    with gr.Tab("๐Ÿ  MATCH OUTCOMES"):
        gr.Markdown("### Home vs Away Performance & Game Types")
        b1 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Overall Comparison")
                p1 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Season Trends/Distribution")
                p2 = gr.Plot()
        b1.click(match_outcomes, [season_dd, team_dd], [p1, p2])

    with gr.Tab("๐ŸŽฏ SCORING & SHOOTING"):
        gr.Markdown("### Scoring Trends & Shooting Efficiency")
        b2 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Overall Scoring")
                p3 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Season Trends/Shooting Stats")
                p4 = gr.Plot()
        b2.click(scoring_shooting, [season_dd, team_dd], [p3, p4])

    with gr.Tab("๐Ÿ‹ POSSESSION CONTROL"):
        gr.Markdown("### Assists & Rebounds Analysis")
        b3 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Overall Possession")
                p5 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Season Trends/Top Teams")
                p6 = gr.Plot()
        b3.click(possession_control, [season_dd, team_dd], [p5, p6])

    with gr.Tab("โšก GAME INTENSITY"):
        gr.Markdown("### Game Pace & Intensity Patterns")
        b4 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Overall Pace")
                p7 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Season Evolution")
                p8 = gr.Plot()
        b4.click(game_intensity, [season_dd, team_dd], [p7, p8])

    with gr.Tab("๐Ÿ  HOME ADVANTAGE"):
        gr.Markdown("### Home Court Advantage Metrics")
        b5 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Top Teams")
                p9 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Season Trends/Shooting Edge")
                p10 = gr.Plot()
        b5.click(home_advantage, [season_dd, team_dd], [p9, p10])

    with gr.Tab("โšก TEAM MOMENTUM"):
        gr.Markdown("### Team Performance Momentum")
        b6 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Momentum Comparison (Last-5 Win Rate)")
                p11 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Momentum Trends - By Team")
                p12 = gr.Plot()
        b6.click(team_momentum, [season_dd, team_dd], [p11, p12])

    with gr.Tab("๐Ÿ“… TIME ANALYSIS"):
        gr.Markdown("### Temporal Patterns in Games")
        b7 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Monthly Distribution")
                p13 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Weekday Pace Analysis")
                p14 = gr.Plot()
        b7.click(time_analysis, [season_dd, team_dd], [p13, p14])

    with gr.Tab("๐Ÿ“Š MARGIN ANALYSIS"):
        gr.Markdown("### Winning Margins & Point Differences")
        b8 = gr.Button("๐Ÿ” ANALYZE", variant="primary", size="lg")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“Š Team/Season Margins")
                p15 = gr.Plot()
            with gr.Column(scale=1):
                gr.Markdown("#### ๐Ÿ“ˆ Margin Trends/Distribution")
                p16 = gr.Plot()
        b8.click(margin_analysis, [season_dd, team_dd], [p15, p16])

    with gr.Tab("๐Ÿ”ฎ FORECASTING"):
        gr.Markdown("### NBA Scoring Trend Analysis")
        gr.Markdown("**Select multiple teams to compare their scoring trends across seasons**")
        b9 = gr.Button("๐Ÿ” ANALYZE TRENDS", variant="primary", size="lg")
        gr.Markdown("#### ๐Ÿ“ˆ Team-wise Scoring Trends by Season")
        p17 = gr.Plot()
        b9.click(forecasting_analysis, [season_dd, team_dd], [p17])

    gr.Markdown("""

    ---

    ### ๐Ÿ’ก DASHBOARD FEATURES:

    - **Team Comparison Mode**: Select 2-5 teams to compare their performance

    - **Season Analysis Mode**: Select multiple seasons to see trends over time

    - **Full-Screen Visualizations**: All graphs optimized for laptop screens

    - **Dark Theme**: Eye-friendly black background with high-contrast elements

    """)

app.launch(share=True)