# All files / src/components/bets BetSlip.tsx

40.49% Statements 296/731
53.52% Branches 38/71
20% Functions 3/15
40.49% Lines 296/731

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    9291x
    1x
    1x
    1x
    1x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x
    7x

    7x

    7x
    15x

    15x
    8x
    4x
    4x

    4x
    1x
    1x
    15x

    15x
    7x

    15x

    15x
    15x

    15x

    15x
    8x
    8x
    8x
    8x
    8x
    8x
    8x

    8x
    8x
    8x
    8x
    8x
    15x

    15x

    15x
    1x
    1x

    1x

    15x

    15x

    15x

    3x
    3x
    3x
    3x
    3x
    3x

    3x
    3x
    3x
    3x
    3x
    3x

    3x
    3x

    3x
    3x

    3x

    12x
    12x

    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x

    12x
    12x
    12x
    12x

    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x

    12x
    12x
    12x

    12x

    12x

    15x

    15x

    15x
    15x
    15x
    15x
    15x

    15x
    12x

    15x
    15x

    15x

    15x
    15x
    15x
    15x
    15x

    15x

    12x
    15x
    15x

    15x

    15x
    15x
    15x
    15x
    15x

    15x

    12x
    15x
    15x

    15x

    15x
    15x

    15x

    15x

    15x

    15x

    15x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x

    15x

    15x

    15x
    15x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x
    15x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    15x

    15x
    15x
    15x
    15x

    15x
    15x
    72x
    72x
    72x
    72x
    72x
    72x
    72x
    15x
    15x
    15x

    15x
    15x
    15x
    15x
    15x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x
    15x
    15x

    15x

    15x
    15x
    15x
    15x

    15x
    15x
    15x
    15x

    15x
    15x

    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x
    15x
    15x
    15x

    15x

    12x
    15x

    15x

    12x

    15x

    15x
    12x

    12x

    15x
    4x

    4x

    15x
    15x

    15x
     import React, { useState } from 'react';
    import { useBetSlip } from '../../hooks/useBetSlip';
    import BetLegItem from './BetLegItem';
    import TeaserControl from './TeaserControl';
    import { formatOdds, formatCurrency, americanToDecimal, decimalToAmerican } from '../../utils/format';

    interface BetSlipProps {
      useDecimalOdds?: boolean;
      onClear?: () => void;
      onRemoveLeg?: (index: number) => void;
    }

    export default function BetSlip({ useDecimalOdds = false, onClear, onRemoveLeg }: BetSlipProps) {
      const {
        legs,
        futureLegs,
        betType,
        stake,
        teaserPoints,
        combinedOdds,
        potentialPayout,
        potentialProfit,
        isValid,
        isSubmitting,
        submitError,
        removeLeg,
        removeFutureLeg,
        updateLeg,
        updateFutureLeg,
        setBetType,
        setStake,
        setTeaserPoints,
        clearSlip,
        submitBet
      } = useBetSlip();

      const [betName, setBetName] = useState('');
      const [showSuccess, setShowSuccess] = useState(false);
      const [isMinimized, setIsMinimized] = useState(false);
      const [stakeInput, setStakeInput] = useState('');
      const [editingFutureId, setEditingFutureId] = useState<string | null>(null);
      const [editFutureOdds, setEditFutureOdds] = useState('');
      const [editFutureOddsDecimal, setEditFutureOddsDecimal] = useState('');
      const [previousLegsCount, setPreviousLegsCount] = useState(0);
      const [oddsBoostPercentage, setOddsBoostPercentage] = useState(0);

      // Auto-expand bet slip when legs are added (but allow manual minimize)
      React.useEffect(() => {
        const totalLegs = legs.length + (futureLegs?.length || 0);
        // Only auto-expand when legs are actually added, not when user manually minimizes
        if (totalLegs > previousLegsCount && isMinimized) {
          setIsMinimized(false);
        }
        setPreviousLegsCount(totalLegs);
      }, [legs.length, futureLegs?.length]);

      // Sync stakeInput with stake changes from quick buttons
      React.useEffect(() => {
        if (stake > 0) {
          setStakeInput(stake.toString());
        } else if (stake === 0 && stakeInput === '') {
          // Keep empty when both are empty
        } else if (stake === 0) {
          setStakeInput('');
        }
      }, [stake]);

      // Detect SGP (Same Game Parlay) - multiple legs on same game
      const sgpInfo = React.useMemo(() => {
        if (betType !== 'parlay' || legs.length < 2) return null;

        const gameGroups = new Map<string, Array<{ leg: typeof legs[0]; index: number }>>();
        legs.forEach((leg, index) => {
          if (!gameGroups.has(leg.gameId)) {
            gameGroups.set(leg.gameId, []);
          }
          gameGroups.get(leg.gameId)!.push({ leg, index });
        });

        const sgpGames = new Map<string, Array<{ leg: typeof legs[0]; index: number }>>();
        const regularLegs: Array<{ leg: typeof legs[0]; index: number }> = [];

        gameGroups.forEach((legsWithIndex, gameId) => {
          if (legsWithIndex.length > 1) {
            // SGP group
            sgpGames.set(gameId, legsWithIndex);
          } else {
            // Regular single leg
            regularLegs.push(legsWithIndex[0]);
          }
        });

        if (sgpGames.size === 0) return null;

        return { sgpGames, regularLegs };
      }, [legs, betType]);

      // State for editing SGP odds
      const [editingSGPGame, setEditingSGPGame] = React.useState<string | null>(null);
      const [sgpOddsEdits, setSgpOddsEdits] = React.useState<Map<string, string>>(new Map());

      // Quick stake buttons
      const quickStakes = [10, 25, 50, 100, 250, 500];

      // Calculate boosted payout and odds
      // Boost applies to PROFIT, not odds multiplier
      const { boostedCombinedOdds, boostedPotentialPayout, boostedPotentialProfit } = React.useMemo(() => {
        if (oddsBoostPercentage === 0) {
          return {
            boostedCombinedOdds: combinedOdds,
            boostedPotentialPayout: potentialPayout,
            boostedPotentialProfit: potentialPayout - stake
          };
        }

        // Calculate original profit
        const originalProfit = potentialPayout - stake;

        // Boost the profit by percentage
        const boostedProfit = originalProfit * (1 + oddsBoostPercentage / 100);
        const boostedPayout = stake + boostedProfit;

        // Back-calculate odds needed for boosted payout
        const boostedDecimal = boostedPayout / stake;
        const boostedAmerican = boostedDecimal >= 2.0
          ? Math.round((boostedDecimal - 1) * 100)
          : Math.round(-100 / (boostedDecimal - 1));

        return {
          boostedCombinedOdds: boostedAmerican,
          boostedPotentialPayout: boostedPayout,
          boostedPotentialProfit: boostedProfit
        };
      }, [combinedOdds, potentialPayout, stake, oddsBoostPercentage]);

      // Handle clear with callback
      const handleClearSlip = () => {
        clearSlip();
        if (onClear) {
          onClear();
        }
      };

      // Handle remove leg with callback
      const handleRemoveLeg = (index: number) => {
        removeLeg(index);
        if (onRemoveLeg) {
          onRemoveLeg(index);
        }
      };

      // Handle submit
      const handleSubmit = async () => {
        if (!isValid || !betName.trim()) return;

        // For parlay boost, DON'T boost individual legs - only the combined odds
        // Pass boostedCombinedOdds to backend which will apply it to the entire parlay
        const oddsToSubmit = oddsBoostPercentage > 0 ? boostedCombinedOdds : undefined;

        if (oddsBoostPercentage > 0 && import.meta.env.DEV) {
          // Dev-only: keep visibility into the boost math without shipping
          // these logs to production users.
          console.log(
            `Parlay boost +${oddsBoostPercentage}%: ` +
            `${combinedOdds} → ${oddsToSubmit}, ` +
            `$${potentialPayout.toFixed(2)} → $${boostedPotentialPayout.toFixed(2)}`
          );
        }

        // Submit with boosted combined odds (bypasses Redux state entirely)
        const success = await submitBet({
          name: betName.trim(),
          boostedCombinedOdds: oddsToSubmit
        });

        if (success) {
          setBetName('');
          setOddsBoostPercentage(0); // Reset boost slider
          setShowSuccess(true);
          setTimeout(() => setShowSuccess(false), 3000);

          // Clear selections in parent component
          if (onClear) {
            onClear();
          }
        }
      };

      // Minimized state - show pixel art bet slip icon
      if (isMinimized) {
        const totalLegs = legs.length + (futureLegs?.length || 0);
        return (
          <button
            onClick={() => setIsMinimized(false)}
            className="fixed bottom-4 right-4 shadow-2xl hover:scale-110 transition-all z-50 block"
            title={`Bet Slip (${totalLegs} ${totalLegs === 1 ? 'selection' : 'selections'})`}
          >
            <div className="relative">
              <img
                src="/betslip.png"
                alt="Bet Slip"
                className="w-20 h-20 block"
              />
              {totalLegs > 0 && (
                <span className="absolute -top-2 -right-2 bg-red-600 text-white rounded-full w-7 h-7 flex items-center justify-center text-sm font-bold border-2 border-white dark:border-gray-800 shadow-lg">
                  {totalLegs}
                </span>
              )}
            </div>
          </button>
        );
      }

      // Empty state - show empty message
      if ((legs.length === 0 && (!futureLegs || futureLegs.length === 0))) {

        return (
          <div className="fixed bottom-4 right-4 w-96 bg-white dark:bg-gray-800 rounded-xl shadow-2xl p-6 text-center z-50 border-2 border-blue-600 dark:border-blue-500">
            <button
              onClick={() => setIsMinimized(true)}
              className="absolute top-3 right-3 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              title="Minimize"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
              </svg>
            </button>
            <div className="text-4xl mb-3">🎟️</div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              Bet Slip Empty
            </h3>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              Click on any odds to add them to your bet slip
            </p>
          </div>
        );
      }

      return (
        <div className="fixed bottom-4 right-4 w-96 bg-white dark:bg-gray-800 rounded-xl shadow-2xl overflow-hidden flex flex-col max-h-[80vh] z-50 border-2 border-brand-600">
          {/* Header */}
          <div className="bg-brand-600 px-4 py-3 flex items-center justify-between text-white">
            <div className="flex items-center gap-2">
              <h3 className="font-display font-bold text-lg tracking-wide">BET SLIP</h3>
              <span className="bg-white/20 px-2 py-0.5 rounded-full text-xs font-semibold">
                {legs.length}
              </span>
            </div>
            <div className="flex items-center gap-3">
              {/* Minimize button */}
              <button
                onClick={() => setIsMinimized(true)}
                className="text-white/80 hover:text-white transition-colors p-1"
                title="Minimize"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
                </svg>
              </button>
              <button
                onClick={handleClearSlip}
                className="text-white/80 hover:text-white transition-colors text-sm font-medium"
              >
                Clear All
              </button>
            </div>
          </div>

          <div className="flex-1 overflow-y-auto">
            {/* Success Message */}
            {showSuccess && (
              <div className="m-4 bg-green-50 border border-green-200 rounded-lg p-3">
                <p className="text-sm text-green-800 font-medium">
                  ✅ Bet placed successfully!
                </p>
              </div>
            )}

            {/* Error Message */}
            {submitError && (
              <div className="m-4 bg-red-50 border border-red-200 rounded-lg p-3">
                <p className="text-sm text-red-800">{submitError}</p>
              </div>
            )}

            <div className="p-4 space-y-4">
              {/* Bet Type Tabs */}
              <div className="flex gap-2">
                <button
                  onClick={() => setBetType('single')}
                  disabled={legs.length > 1}
                  className={`
                    flex-1 px-3 py-2 rounded-lg font-medium text-sm transition-all
                    ${
                      betType === 'single'
                        ? 'bg-brand-600 text-white shadow-md'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }
                    ${legs.length > 1 ? 'opacity-50 cursor-not-allowed' : ''}
                  `}
                >
                  Single
                </button>
                <button
                  onClick={() => setBetType('parlay')}
                  disabled={legs.length < 2}
                  className={`
                    flex-1 px-3 py-2 rounded-lg font-medium text-sm transition-all
                    ${
                      betType === 'parlay'
                        ? 'bg-brand-600 text-white shadow-md'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }
                    ${legs.length < 2 ? 'opacity-50 cursor-not-allowed' : ''}
                  `}
                >
                  Parlay
                </button>
                <button
                  onClick={() => setBetType('teaser')}
                  disabled={legs.length < 2}
                  className={`
                    flex-1 px-3 py-2 rounded-lg font-medium text-sm transition-all
                    ${
                      betType === 'teaser'
                        ? 'bg-brand-600 text-white shadow-md'
                        : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }
                    ${legs.length < 2 ? 'opacity-50 cursor-not-allowed' : ''}
                  `}
                >
                  Teaser
                </button>
              </div>

              {/* Teaser Control */}
              {betType === 'teaser' && (
                <TeaserControl
                  legs={legs}
                  selectedPoints={teaserPoints}
                  onChange={setTeaserPoints}
                />
              )}

              {/* Legs */}
              <div className="space-y-3">
                {/* SGP Groups */}
                {sgpInfo?.sgpGames && Array.from(sgpInfo.sgpGames.entries()).map(([gameId, legsWithIndex]) => {
                  const firstLeg = legsWithIndex[0].leg;
                  const gameName = firstLeg.game
                    ? `${firstLeg.game.awayTeamName} vs ${firstLeg.game.homeTeamName}`
                    : 'Same Game';

                  // Calculate combined SGP odds with smart logic
                  // Check if any leg has userAdjustedOdds - if so, use those for display
                  const hasUserAdjustedOdds = legsWithIndex.some(({ leg }) => leg.userAdjustedOdds !== undefined);

                  let combinedSgpOdds: number;
                  let americanSgpOdds: number;

                  if (hasUserAdjustedOdds) {
                    // At least one leg has adjusted odds - recalculate from userAdjustedOdds or original odds
                    combinedSgpOdds = legsWithIndex.reduce((total, { leg }) => {
                      const oddsToUse = leg.userAdjustedOdds ?? leg.odds;
                      const decimalOdds = oddsToUse > 0 ? 1 + oddsToUse / 100 : 1 + 100 / Math.abs(oddsToUse);
                      return total * decimalOdds;
                    }, 1);
                    americanSgpOdds = combinedSgpOdds >= 2
                      ? Math.round((combinedSgpOdds - 1) * 100)
                      : Math.round(-100 / (combinedSgpOdds - 1));
                  } else {
                    // No adjustments - apply smart SGP logic
                    const mlLeg = legsWithIndex.find(({ leg }) => leg.selectionType === 'moneyline');
                    const spreadLeg = legsWithIndex.find(({ leg }) => leg.selectionType === 'spread');
                    const totalLegs = legsWithIndex.filter(({ leg }) => leg.selectionType === 'total');

                    // Determine which legs to multiply
                    const legsToMultiply: typeof legsWithIndex = [];

                    // If both ML and Spread exist for same team, use only the higher odds
                    if (mlLeg && spreadLeg && mlLeg.leg.selection === spreadLeg.leg.selection) {
                      const mlDecimal = mlLeg.leg.odds > 0 ? 1 + mlLeg.leg.odds / 100 : 1 + 100 / Math.abs(mlLeg.leg.odds);
                      const spreadDecimal = spreadLeg.leg.odds > 0 ? 1 + spreadLeg.leg.odds / 100 : 1 + 100 / Math.abs(spreadLeg.leg.odds);

                      // Use higher odds leg
                      if (mlDecimal >= spreadDecimal) {
                        legsToMultiply.push(mlLeg);
                      } else {
                        legsToMultiply.push(spreadLeg);
                      }

                      // Add totals separately
                      legsToMultiply.push(...totalLegs);
                    } else {
                      // Standard: multiply all legs
                      legsToMultiply.push(...legsWithIndex);
                    }

                    // Calculate combined odds from selected legs
                    combinedSgpOdds = legsToMultiply.reduce((total, { leg }) => {
                      const decimalOdds = leg.odds > 0 ? 1 + leg.odds / 100 : 1 + 100 / Math.abs(leg.odds);
                      return total * decimalOdds;
                    }, 1);
                    americanSgpOdds = combinedSgpOdds >= 2
                      ? Math.round((combinedSgpOdds - 1) * 100)
                      : Math.round(-100 / (combinedSgpOdds - 1));
                  }

                  const isEditingThisSGP = editingSGPGame === gameId;
                  const defaultEditValue = useDecimalOdds
                    ? ((combinedSgpOdds).toFixed(2))
                    : americanSgpOdds.toString();
                  const editValue = sgpOddsEdits.get(gameId) || defaultEditValue;

                  return (
                    <div key={`sgp-${gameId}`} className="border-2 border-purple-500 dark:border-purple-600 rounded-lg bg-gradient-to-br from-purple-100 via-purple-50 to-pink-50 dark:from-purple-900/40 dark:via-purple-900/30 dark:to-pink-900/30 p-4 shadow-md">
                      {/* SGP Header with Combined Odds */}
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1.5">
                            <span className="text-purple-700 dark:text-purple-300 font-bold text-base">⚡</span>
                            <span className="text-sm font-bold text-purple-900 dark:text-purple-100 uppercase tracking-wide">
                              Same Game Parlay
                            </span>
                            <span className="text-xs font-semibold text-purple-700 dark:text-purple-300 bg-purple-200/50 dark:bg-purple-800/50 px-2 py-0.5 rounded-full">
                              {legsWithIndex.length} legs
                            </span>
                          </div>
                          <div className="text-xs font-medium text-gray-700 dark:text-gray-300 truncate">{gameName}</div>
                        </div>

                        {/* Editable Combined Odds */}
                        <div className="flex items-center gap-2 ml-3">
                          {isEditingThisSGP ? (
                            <>
                              <input
                                type="text"
                                inputMode="numeric"
                                value={editValue}
                                onChange={(e) => {
                                  const newMap = new Map(sgpOddsEdits);
                                  newMap.set(gameId, e.target.value);
                                  setSgpOddsEdits(newMap);
                                }}
                                className="w-20 px-2 py-1.5 text-sm font-bold border-2 border-purple-500 dark:border-purple-400 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white text-center shadow-sm [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                                placeholder={useDecimalOdds ? "2.00" : "-110"}
                              />
                              <button
                                onClick={() => {
                                  let americanOdds: number;
                                  if (useDecimalOdds) {
                                    const decimalValue = parseFloat(editValue);
                                    if (!isNaN(decimalValue) && decimalValue >= 1) {
                                      // Convert decimal to American
                                      americanOdds = decimalValue >= 2.0
                                        ? Math.round((decimalValue - 1) * 100)
                                        : Math.round(-100 / (decimalValue - 1));
                                    } else {
                                      return; // Invalid value
                                    }
                                  } else {
                                    americanOdds = parseInt(editValue);
                                    if (isNaN(americanOdds)) {
                                      return; // Invalid value
                                    }
                                  }
                                  legsWithIndex.forEach(({ index }) => {
                                    updateLeg(index, { userAdjustedOdds: americanOdds });
                                  });
                                  setEditingSGPGame(null);
                                }}
                                className="text-green-700 dark:text-green-400 hover:text-green-800 dark:hover:text-green-300 p-1 bg-green-100 dark:bg-green-900/30 rounded transition-colors"
                                title="Apply"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                </svg>
                              </button>
                              <button
                                onClick={() => setEditingSGPGame(null)}
                                className="text-red-700 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 p-1 bg-red-100 dark:bg-red-900/30 rounded transition-colors"
                                title="Cancel"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                              </button>
                            </>
                          ) : (
                            <>
                              <span className="text-base font-bold text-purple-900 dark:text-purple-100 bg-purple-200/60 dark:bg-purple-800/60 px-3 py-1 rounded-lg">
                                {formatOdds(americanSgpOdds, useDecimalOdds)}
                              </span>
                              <button
                                onClick={() => {
                                  setEditingSGPGame(gameId);
                                  const newMap = new Map(sgpOddsEdits);
                                  const initialValue = useDecimalOdds
                                    ? (combinedSgpOdds).toFixed(2)
                                    : americanSgpOdds.toString();
                                  newMap.set(gameId, initialValue);
                                  setSgpOddsEdits(newMap);
                                }}
                                className="text-purple-700 dark:text-purple-300 hover:text-purple-900 dark:hover:text-purple-100 p-1.5 bg-purple-200/60 dark:bg-purple-800/60 rounded-lg hover:bg-purple-300/60 dark:hover:bg-purple-700/60 transition-colors"
                                title="Edit combined odds"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                </svg>
                              </button>
                            </>
                          )}
                        </div>
                      </div>

                      {/* SGP Legs (nested) - now editable */}
                      <div className="space-y-2">
                        {legsWithIndex.map(({ leg, index }) => (
                          <BetLegItem
                            key={index}
                            leg={leg}
                            index={index}
                            onRemove={handleRemoveLeg}
                            onUpdate={updateLeg}
                            showTeaser={false}
                            teaserPoints={0}
                            useDecimalOdds={useDecimalOdds}
                          />
                        ))}
                      </div>
                    </div>
                  );
                })}

                {/* Regular Legs */}
                {sgpInfo ? sgpInfo.regularLegs.map(({ leg, index }) => (
                  <BetLegItem
                    key={index}
                    leg={leg}
                    index={index}
                    onRemove={handleRemoveLeg}
                    onUpdate={updateLeg}
                    showTeaser={betType === 'teaser'}
                    teaserPoints={teaserPoints}
                    useDecimalOdds={useDecimalOdds}
                  />
                )) : legs.map((leg, index) => (
                  <BetLegItem
                    key={index}
                    leg={leg}
                    index={index}
                    onRemove={handleRemoveLeg}
                    onUpdate={updateLeg}
                    showTeaser={betType === 'teaser'}
                    teaserPoints={teaserPoints}
                    useDecimalOdds={useDecimalOdds}
                  />
                ))}

                {/* Futures Legs */}
                {futureLegs && futureLegs.length > 0 && (
                  <div className="border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
                    <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 flex items-center">
                      <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                      </svg>
                      Futures Bets
                    </h3>
                    {futureLegs.map((futureLeg) => {
                      const isEditing = editingFutureId === futureLeg.futureId;
                      const currentOdds = futureLeg.userAdjustedOdds ?? futureLeg.odds;

                      const startEditingFuture = () => {
                        setEditingFutureId(futureLeg.futureId);
                        setEditFutureOdds(currentOdds.toString());
                        if (useDecimalOdds) {
                          setEditFutureOddsDecimal(americanToDecimal(currentOdds).toFixed(2));
                        }
                      };

                      const cancelEditingFuture = () => {
                        setEditingFutureId(null);
                        setEditFutureOdds('');
                        setEditFutureOddsDecimal('');
                      };

                      const applyFutureOdds = () => {
                        let newOdds: number;
                        if (useDecimalOdds) {
                          const decimal = parseFloat(editFutureOddsDecimal);
                          newOdds = !isNaN(decimal) && decimal >= 1.01 ? decimalToAmerican(decimal) : currentOdds;
                        } else {
                          newOdds = parseInt(editFutureOdds);
                          if (isNaN(newOdds)) {
                            newOdds = currentOdds;
                          }
                        }
                        updateFutureLeg(futureLeg.futureId, { userAdjustedOdds: newOdds });
                        setEditingFutureId(null);
                        setEditFutureOdds('');
                        setEditFutureOddsDecimal('');
                      };

                      const adjustFutureOdds = (delta: number) => {
                        if (useDecimalOdds) {
                          const current = parseFloat(editFutureOddsDecimal) || 2.00;
                          const newDecimal = Math.max(1.01, +(current + (delta * 0.05)).toFixed(2));
                          setEditFutureOddsDecimal(newDecimal.toFixed(2));
                          setEditFutureOdds(decimalToAmerican(newDecimal).toString());
                        } else {
                          const currentEditOdds = parseInt(editFutureOdds) || 0;
                          let newOdds = currentEditOdds + (delta * 5);

                          if (currentEditOdds < -100 && newOdds > -100) {
                            newOdds = 100;
                          } else if (currentEditOdds > 100 && newOdds < 100) {
                            newOdds = -100;
                          } else if (newOdds > -100 && newOdds < 100) {
                            newOdds = delta > 0 ? 100 : -100;
                          }

                          setEditFutureOdds(newOdds.toString());
                        }
                      };

                      return (
                        <div
                          key={futureLeg.futureId}
                          className="bg-purple-50 dark:bg-purple-900/20 rounded-lg p-3 mb-2 border border-purple-200 dark:border-purple-700"
                        >
                          <div className="flex justify-between items-start mb-2">
                            <div className="flex-1">
                              <div className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">
                                {futureLeg.sportKey?.replace(/_/g, ' ')}
                              </div>
                              <div className="font-semibold text-gray-900 dark:text-white mb-1">
                                {futureLeg.futureTitle}
                              </div>
                              <div className="text-sm text-gray-700 dark:text-gray-300">
                                {futureLeg.outcome}
                              </div>
                            </div>
                            <div className="flex items-center gap-1 ml-2">
                              <button
                                onClick={isEditing ? cancelEditingFuture : startEditingFuture}
                                className="text-gray-400 dark:text-gray-500 hover:text-blue-600 dark:hover:text-blue-400 transition-colors p-1"
                                title={isEditing ? "Cancel" : "Edit"}
                              >
                                {isEditing ? (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                  </svg>
                                ) : (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                  </svg>
                                )}
                              </button>
                              <button
                                onClick={() => removeFutureLeg(futureLeg.futureId)}
                                className="text-red-500 hover:text-red-700 dark:hover:text-red-400 transition-colors p-1"
                                title="Remove future"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                              </button>
                            </div>
                          </div>

                          {!isEditing ? (
                            <div className="flex items-center justify-between">
                              <div className="text-lg font-bold text-purple-600 dark:text-purple-400">
                                {formatOdds(currentOdds, useDecimalOdds)}
                                {futureLeg.userAdjustedOdds && futureLeg.userAdjustedOdds !== futureLeg.odds && (
                                  <span className="text-xs text-blue-600 dark:text-blue-400 ml-2 font-normal">(adjusted)</span>
                                )}
                              </div>
                              {futureLeg.userAdjustedOdds && futureLeg.userAdjustedOdds !== futureLeg.odds && (
                                <button
                                  onClick={() => updateFutureLeg(futureLeg.futureId, { userAdjustedOdds: undefined })}
                                  className="text-xs text-blue-600 dark:text-blue-400 hover:underline"
                                >
                                  Reset Odds
                                </button>
                              )}
                            </div>
                          ) : (
                            <div className="space-y-2 mt-2">
                              <div>
                                <label className="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
                                  Odds ({useDecimalOdds ? 'Decimal' : 'American'})
                                </label>
                                <div className="flex gap-1">
                                  <button
                                    onClick={() => adjustFutureOdds(-1)}
                                    className="px-3 py-1.5 bg-purple-200 dark:bg-purple-700 hover:bg-purple-300 dark:hover:bg-purple-600 text-purple-700 dark:text-white font-bold rounded transition-colors"
                                    title={useDecimalOdds ? "Decrease by 0.05" : "Decrease by 5"}
                                  >
                                    -
                                  </button>
                                  <input
                                    type="text"
                                    inputMode="decimal"
                                    aria-label="Future bet odds"
                                    value={useDecimalOdds ? editFutureOddsDecimal : editFutureOdds}
                                    onChange={(e) => {
                                      const value = e.target.value;
                                      if (useDecimalOdds) {
                                        // Allow typing decimal values
                                        setEditFutureOddsDecimal(value);
                                        const decimal = parseFloat(value);
                                        if (!isNaN(decimal) && decimal >= 1.01) {
                                          setEditFutureOdds(decimalToAmerican(decimal).toString());
                                        }
                                      } else {
                                        setEditFutureOdds(value);
                                      }
                                    }}
                                    className="flex-1 px-3 py-1.5 text-sm border border-purple-300 dark:border-purple-600 rounded focus:outline-none focus:ring-2 focus:ring-purple-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                                  />
                                  <button
                                    onClick={() => adjustFutureOdds(1)}
                                    className="px-3 py-1.5 bg-purple-200 dark:bg-purple-700 hover:bg-purple-300 dark:hover:bg-purple-600 text-purple-700 dark:text-white font-bold rounded transition-colors"
                                    title={useDecimalOdds ? "Increase by 0.05" : "Increase by 5"}
                                  >
                                    +
                                  </button>
                                </div>
                              </div>
                              <button
                                onClick={applyFutureOdds}
                                className="w-full px-3 py-1.5 bg-purple-600 text-white text-sm font-medium rounded hover:bg-purple-700 transition-colors"
                              >
                                Apply Changes
                              </button>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              {/* Bet Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Bet Name *
                </label>
                <input
                  type="text"
                  value={betName}
                  onChange={(e) => setBetName(e.target.value)}
                  placeholder="e.g., Sunday Parlay"
                  maxLength={100}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
              </div>

              {/* Stake */}
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Stake Amount
                </label>
                <div className="relative">
                  <span className="absolute left-3 top-2.5 text-gray-500 dark:text-gray-400">$</span>
                  <input
                    type="text"
                    inputMode="decimal"
                    value={stakeInput}
                    onChange={(e) => {
                      const value = e.target.value;
                      // Allow empty, digits, and decimal point
                      if (value === '' || /^\d*\.?\d*$/.test(value)) {
                        setStakeInput(value);
                        const numValue = parseFloat(value);
                        setStake(isNaN(numValue) || value === '' ? 0 : numValue);
                      }
                    }}
                    onBlur={() => {
                      // Format on blur if there's a value
                      if (stakeInput && stake > 0) {
                        setStakeInput(stake.toString());
                      }
                    }}
                    className="w-full pl-7 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white dark:bg-gray-700 text-gray-900 dark:text-white [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
                    placeholder="0.00"
                  />
                </div>

                {/* Quick Stakes */}
                <div className="grid grid-cols-3 gap-2 mt-2">
                  {quickStakes.map((amount) => (
                    <button
                      key={amount}
                      onClick={() => setStake(amount)}
                      className="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-medium rounded transition-colors"
                    >
                      ${amount}
                    </button>
                  ))}
                </div>
              </div>

              {/* Odds Boost Slider */}
              <div className="border-2 border-amber-400 dark:border-amber-500 rounded-lg p-4 bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <span className="text-lg">⚡</span>
                    <label className="text-sm font-bold text-amber-900 dark:text-amber-100">
                      Odds Boost
                    </label>
                  </div>
                  <span className="text-lg font-bold text-amber-600 dark:text-amber-400">
                    +{oddsBoostPercentage}%
                  </span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={oddsBoostPercentage}
                  onChange={(e) => setOddsBoostPercentage(parseInt(e.target.value))}
                  className="w-full h-2 bg-gray-300 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-amber-500"
                  aria-label="Odds boost percentage"
                  style={{
                    background: `linear-gradient(to right, rgb(245 158 11) 0%, rgb(245 158 11) ${oddsBoostPercentage}%, rgb(209 213 219) ${oddsBoostPercentage}%, rgb(209 213 219) 100%)`
                  }}
                />
                <div className="flex justify-between text-xs text-amber-800 dark:text-amber-300 mt-1">
                  <span>0%</span>
                  <span>50%</span>
                  <span>100%</span>
                </div>
                {oddsBoostPercentage > 0 && (
                  <div className="mt-3 p-2 bg-amber-100 dark:bg-amber-900/40 rounded text-xs text-amber-900 dark:text-amber-200">
                    <div className="flex justify-between mb-1">
                      <span>Original odds:</span>
                      <span className="font-bold">{formatOdds(combinedOdds, useDecimalOdds)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Boosted odds:</span>
                      <span className="font-bold text-green-700 dark:text-green-400">{formatOdds(boostedCombinedOdds, useDecimalOdds)}</span>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Footer - Odds & Submit */}
          <div className="border-t border-gray-200 dark:border-gray-700 p-4 space-y-3 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-900">
            {/* Combined Odds */}
            <div className="flex items-center justify-between p-3 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
              <span className="text-sm font-semibold text-gray-700 dark:text-gray-300">Combined Odds:</span>
              <div className="flex items-center gap-2">
                {oddsBoostPercentage > 0 && (
                  <span className="text-sm text-gray-500 dark:text-gray-400 line-through">
                    {formatOdds(combinedOdds, useDecimalOdds)}
                  </span>
                )}
                <span className={`text-lg font-bold ${oddsBoostPercentage > 0 ? 'text-amber-600 dark:text-amber-400' : 'text-blue-600 dark:text-blue-400'}`}>
                  {combinedOdds ? formatOdds(oddsBoostPercentage > 0 ? boostedCombinedOdds : combinedOdds, useDecimalOdds) : '—'}
                </span>
                {oddsBoostPercentage > 0 && (
                  <span className="text-xs bg-amber-500 text-white px-1.5 py-0.5 rounded font-bold">+{oddsBoostPercentage}%</span>
                )}
              </div>
            </div>

            {/* Potential Payout */}
            <div className="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-900/30 dark:to-emerald-900/30 rounded-lg p-4 border-2 border-green-200 dark:border-green-700 shadow-sm">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-semibold text-green-800 dark:text-green-300">Potential Payout:</span>
                <span className="text-2xl font-bold text-green-700 dark:text-green-400">
                  {stake > 0 ? formatCurrency(oddsBoostPercentage > 0 ? boostedPotentialPayout : potentialPayout) : '$0.00'}
                </span>
              </div>
              <div className="flex items-center justify-between text-sm pt-2 border-t border-green-200 dark:border-green-700/50">
                <span className="text-green-700 dark:text-green-400 font-medium">Profit:</span>
                <span className="font-bold text-green-800 dark:text-green-300">
                  {stake > 0 ? formatCurrency(oddsBoostPercentage > 0 ? boostedPotentialProfit : potentialProfit) : '$0.00'}
                </span>
              </div>
            </div>

            {/* Submit Button */}
            <button
              onClick={handleSubmit}
              disabled={!isValid || !betName.trim() || isSubmitting}
              className={`
                w-full py-3.5 rounded-lg font-bold text-white text-base transition-all shadow-md
                ${
                  isValid && betName.trim() && !isSubmitting
                    ? 'bg-brand-600 hover:bg-brand-700 hover:shadow-lg transform hover:scale-[1.02] active:scale-[0.98]'
                    : 'bg-gray-400 dark:bg-gray-600 cursor-not-allowed opacity-60'
                }
              `}
            >
              {isSubmitting ? (
                <span className="flex items-center justify-center gap-2">
                  <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Placing Bet...
                </span>
              ) : (
                'Place Bet'
              )}
            </button>

            {/* Validation Messages */}
            {!betName.trim() && legs.length > 0 && (
              <p className="text-xs text-red-600 text-center">
                Bet name is required
              </p>
            )}
            {stake <= 0 && legs.length > 0 && (
              <p className="text-xs text-red-600 text-center">
                Enter stake amount
              </p>
            )}
          </div>
        </div>
      );
    }