File size: 38,534 Bytes
27db761
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disc Golf League Tracker</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .highlight {
            background-color: rgba(255, 255, 0, 0.2);
            transition: background-color 0.3s;
        }
        .money-in { color: #10B981; }
        .money-out { color: #EF4444; }
        input[type="number"]::-webkit-inner-spin-button,
        input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        .payment-input {
            width: 60px;
            text-align: center;
        }
        .credits-column {
            background-color: rgba(16, 185, 129, 0.1);
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <header class="mb-8 text-center">
            <h1 class="text-4xl font-bold text-green-800 mb-2">
                <i class="fas fa-golf-ball mr-2"></i> Disc Golf League Tracker
            </h1>
            <p class="text-gray-600">Track weekly scores and finances for your disc golf league</p>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Player Management -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-semibold text-green-700 mb-4 flex items-center">
                    <i class="fas fa-users mr-2"></i> Players
                </h2>
                <div class="mb-4 flex">
                    <input type="text" id="playerName" placeholder="Player name" class="flex-1 px-3 py-2 border rounded-l focus:outline-none focus:ring-2 focus:ring-green-500">
                    <button id="addPlayer" class="bg-green-600 text-white px-4 py-2 rounded-r hover:bg-green-700 transition">
                        <i class="fas fa-plus"></i> Add
                    </button>
                </div>
                <ul id="playerList" class="divide-y">
                    <!-- Players will be added here -->
                </ul>
            </div>

            <!-- Weekly Event -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-semibold text-green-700 mb-4 flex items-center">
                    <i class="fas fa-calendar-week mr-2"></i> Weekly Event
                </h2>
                <div class="mb-4">
                    <label class="block text-gray-700 mb-1">Event Date</label>
                    <input type="date" id="eventDate" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-green-500">
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 mb-1">Course</label>
                    <input type="text" id="courseName" placeholder="Course name" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-green-500">
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 mb-1">Default Entry Fee ($)</label>
                    <input type="number" id="entryFee" value="5" min="0" step="0.5" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-green-500">
                </div>
                <button id="startEvent" class="w-full bg-green-600 text-white py-2 rounded hover:bg-green-700 transition">
                    <i class="fas fa-play mr-1"></i> Start Event
                </button>
            </div>

            <!-- Financial Summary -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-semibold text-green-700 mb-4 flex items-center">
                    <i class="fas fa-money-bill-wave mr-2"></i> Finances
                </h2>
                <div class="bg-gray-50 p-4 rounded mb-4">
                    <div class="flex justify-between mb-2">
                        <span class="font-medium">Total Collected:</span>
                        <span id="totalCollected" class="font-bold money-in">$0.00</span>
                    </div>
                    <div class="flex justify-between mb-2">
                        <span class="font-medium">Total Paid Out:</span>
                        <span id="totalPaidOut" class="font-bold money-out">$0.00</span>
                    </div>
                    <div class="flex justify-between pt-2 border-t">
                        <span class="font-medium">League Balance:</span>
                        <span id="leagueBalance" class="font-bold">$0.00</span>
                    </div>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 mb-1">Add Payout</label>
                    <div class="flex">
                        <select id="payoutPlayer" class="flex-1 px-3 py-2 border rounded-l focus:outline-none focus:ring-2 focus:ring-green-500">
                            <option value="">Select player</option>
                        </select>
                        <input type="number" id="payoutAmount" placeholder="Amount" min="0" step="0.5" class="w-24 px-3 py-2 border-t border-b border-gray-300 focus:outline-none">
                        <button id="addPayout" class="bg-green-600 text-white px-4 py-2 rounded-r hover:bg-green-700 transition">
                            <i class="fas fa-hand-holding-usd"></i>
                        </button>
                    </div>
                </div>
                <div class="max-h-40 overflow-y-auto">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="bg-gray-100">
                                <th class="py-2 text-left pl-2">Player</th>
                                <th class="py-2 text-right pr-2">Amount</th>
                                <th class="py-2 text-right pr-2">Credits</th>
                                <th class="py-2 text-right pr-2"></th>
                            </tr>
                        </thead>
                        <tbody id="payoutList">
                            <!-- Payouts will be added here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Event Scoring Section -->
        <div id="scoringSection" class="bg-white rounded-lg shadow p-6 mt-6 hidden">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-semibold text-green-700">
                    <i class="fas fa-golf-ball mr-2"></i> 
                    <span id="currentEventTitle">Event Scoring</span>
                </h2>
                <button id="endEvent" class="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-700 transition">
                    <i class="fas fa-stop mr-1"></i> End Event
                </button>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="py-2 text-left pl-2">Player</th>
                            <th class="py-2 text-center">Score</th>
                            <th class="py-2 text-center">+/-</th>
                            <th class="py-2 text-center">Payment</th>
                            <th class="py-2 text-center">Paid</th>
                            <th class="py-2 text-right pr-2">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="scoreEntryRows">
                        <!-- Score rows will be added here -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- League History -->
        <div class="bg-white rounded-lg shadow p-6 mt-6">
            <h2 class="text-xl font-semibold text-green-700 mb-4 flex items-center">
                <i class="fas fa-history mr-2"></i> League History
            </h2>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="py-2 text-left pl-2">Date</th>
                            <th class="py-2 text-left">Course</th>
                            <th class="py-2 text-center">Players</th>
                            <th class="py-2 text-center">Winner</th>
                            <th class="py-2 text-right pr-2">Payout</th>
                            <th class="py-2 text-right pr-2">Collected</th>
                        </tr>
                    </thead>
                    <tbody id="eventHistory">
                        <!-- Event history will be added here -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Player Statistics -->
        <div class="bg-white rounded-lg shadow p-6 mt-6">
            <h2 class="text-xl font-semibold text-green-700 mb-4 flex items-center">
                <i class="fas fa-chart-line mr-2"></i> Player Statistics
            </h2>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="py-2 text-left pl-2">Player</th>
                            <th class="py-2 text-center">Events</th>
                            <th class="py-2 text-center">Wins</th>
                            <th class="py-2 text-center">Avg Score</th>
                            <th class="py-2 text-right pr-2">Total Paid</th>
                            <th class="py-2 text-right pr-2">Total Payout</th>
                            <th class="py-2 text-right pr-2 credits-column">Credits</th>
                        </tr>
                    </thead>
                    <tbody id="playerStats">
                        <!-- Player stats will be added here -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Player Payment History Modal -->
        <div id="paymentHistoryModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
            <div class="bg-white rounded-lg shadow-lg w-full max-w-md max-h-[80vh] overflow-y-auto">
                <div class="p-4 border-b">
                    <h3 class="text-lg font-semibold text-green-700" id="paymentHistoryTitle">Payment History</h3>
                    <button id="closePaymentHistory" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="p-4">
                    <table class="w-full text-sm">
                        <thead>
                            <tr class="bg-gray-100">
                                <th class="py-2 text-left pl-2">Date</th>
                                <th class="py-2 text-left">Event</th>
                                <th class="py-2 text-right pr-2">Amount</th>
                            </tr>
                        </thead>
                        <tbody id="paymentHistoryContent">
                            <!-- Payment history will be added here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Data storage
        let players = [];
        let currentEvent = null;
        let events = [];
        let payouts = [];
        let playerPayments = [];

        // DOM elements
        const playerNameInput = document.getElementById('playerName');
        const addPlayerBtn = document.getElementById('addPlayer');
        const playerList = document.getElementById('playerList');
        const eventDateInput = document.getElementById('eventDate');
        const courseNameInput = document.getElementById('courseName');
        const entryFeeInput = document.getElementById('entryFee');
        const startEventBtn = document.getElementById('startEvent');
        const scoringSection = document.getElementById('scoringSection');
        const scoreEntryRows = document.getElementById('scoreEntryRows');
        const endEventBtn = document.getElementById('endEvent');
        const payoutPlayerSelect = document.getElementById('payoutPlayer');
        const payoutAmountInput = document.getElementById('payoutAmount');
        const addPayoutBtn = document.getElementById('addPayout');
        const payoutList = document.getElementById('payoutList');
        const totalCollectedSpan = document.getElementById('totalCollected');
        const totalPaidOutSpan = document.getElementById('totalPaidOut');
        const leagueBalanceSpan = document.getElementById('leagueBalance');
        const eventHistory = document.getElementById('eventHistory');
        const playerStats = document.getElementById('playerStats');
        const currentEventTitle = document.getElementById('currentEventTitle');
        const paymentHistoryModal = document.getElementById('paymentHistoryModal');
        const paymentHistoryTitle = document.getElementById('paymentHistoryTitle');
        const paymentHistoryContent = document.getElementById('paymentHistoryContent');
        const closePaymentHistory = document.getElementById('closePaymentHistory');

        // Set default date to today
        eventDateInput.valueAsDate = new Date();

        // Initialize from localStorage
        function loadData() {
            const savedPlayers = localStorage.getItem('discGolfPlayers');
            const savedEvents = localStorage.getItem('discGolfEvents');
            const savedPayouts = localStorage.getItem('discGolfPayouts');
            const savedPayments = localStorage.getItem('discGolfPlayerPayments');

            if (savedPlayers) players = JSON.parse(savedPlayers);
            if (savedEvents) events = JSON.parse(savedEvents);
            if (savedPayouts) payouts = JSON.parse(savedPayouts);
            if (savedPayments) playerPayments = JSON.parse(savedPayments);

            renderPlayerList();
            updatePayoutPlayerSelect();
            renderEventHistory();
            renderPlayerStats();
            updateFinancialSummary();
            renderPayoutList();
        }

        // Save data to localStorage
        function saveData() {
            localStorage.setItem('discGolfPlayers', JSON.stringify(players));
            localStorage.setItem('discGolfEvents', JSON.stringify(events));
            localStorage.setItem('discGolfPayouts', JSON.stringify(payouts));
            localStorage.setItem('discGolfPlayerPayments', JSON.stringify(playerPayments));
        }

        // Add player
        addPlayerBtn.addEventListener('click', () => {
            const name = playerNameInput.value.trim();
            if (name && !players.some(p => p.name.toLowerCase() === name.toLowerCase())) {
                players.push({
                    id: Date.now().toString(),
                    name: name,
                    eventsPlayed: 0,
                    wins: 0,
                    totalPayout: 0,
                    totalPaid: 0,
                    totalScore: 0,
                    credits: 0
                });
                playerNameInput.value = '';
                renderPlayerList();
                updatePayoutPlayerSelect();
                saveData();
            }
        });

        // Render player list
        function renderPlayerList() {
            playerList.innerHTML = '';
            players.forEach(player => {
                const li = document.createElement('li');
                li.className = 'py-2 px-1 flex justify-between items-center fade-in';
                li.innerHTML = `
                    <span>${player.name}</span>
                    <div>
                        <button class="text-blue-500 hover:text-blue-700 view-payments mr-3" data-id="${player.id}" title="View payment history">
                            <i class="fas fa-money-bill-wave"></i>
                        </button>
                        <button class="text-red-500 hover:text-red-700 delete-player" data-id="${player.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `;
                playerList.appendChild(li);
            });

            // Add delete event listeners
            document.querySelectorAll('.delete-player').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const id = e.currentTarget.getAttribute('data-id');
                    players = players.filter(p => p.id !== id);
                    renderPlayerList();
                    updatePayoutPlayerSelect();
                    saveData();
                });
            });

            // Add payment history event listeners
            document.querySelectorAll('.view-payments').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const playerId = e.currentTarget.getAttribute('data-id');
                    showPaymentHistory(playerId);
                });
            });
        }

        // Show payment history for a player
        function showPaymentHistory(playerId) {
            const player = players.find(p => p.id === playerId);
            if (!player) return;

            paymentHistoryTitle.textContent = `Payment History - ${player.name}`;
            paymentHistoryContent.innerHTML = '';

            const playerPayments = getPlayerPayments(playerId);
            if (playerPayments.length === 0) {
                const tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="3" class="py-4 text-center text-gray-500">No payment history found</td>';
                paymentHistoryContent.appendChild(tr);
            } else {
                playerPayments.forEach(payment => {
                    const tr = document.createElement('tr');
                    tr.className = 'border-b';
                    tr.innerHTML = `
                        <td class="py-2 pl-2">${formatDate(payment.date)}</td>
                        <td class="py-2">${payment.eventName || 'N/A'}</td>
                        <td class="py-2 text-right pr-2 money-in">$${payment.amount.toFixed(2)}</td>
                    `;
                    paymentHistoryContent.appendChild(tr);
                });
            }

            paymentHistoryModal.classList.remove('hidden');
        }

        // Close payment history modal
        closePaymentHistory.addEventListener('click', () => {
            paymentHistoryModal.classList.add('hidden');
        });

        // Get payments for a specific player
        function getPlayerPayments(playerId) {
            return playerPayments.filter(p => p.playerId === playerId);
        }

        // Update payout player select
        function updatePayoutPlayerSelect() {
            payoutPlayerSelect.innerHTML = '<option value="">Select player</option>';
            players.forEach(player => {
                const option = document.createElement('option');
                option.value = player.id;
                option.textContent = player.name;
                payoutPlayerSelect.appendChild(option);
            });
        }

        // Start event
        startEventBtn.addEventListener('click', () => {
            const date = eventDateInput.value;
            const course = courseNameInput.value.trim();
            const entryFee = parseFloat(entryFeeInput.value) || 0;

            if (!date || !course) {
                alert('Please enter a date and course name');
                return;
            }

            if (players.length === 0) {
                alert('Please add at least one player');
                return;
            }

            currentEvent = {
                id: Date.now().toString(),
                date: date,
                course: course,
                entryFee: entryFee,
                participants: players.map(player => ({
                    playerId: player.id,
                    name: player.name,
                    score: 0,
                    relativeToPar: 0,
                    paymentAmount: entryFee,
                    paid: false
                }))
            };

            currentEventTitle.textContent = `${formatDate(date)} @ ${course}`;
            scoringSection.classList.remove('hidden');
            renderScoreEntryRows();
            saveData();
        });

        // Render score entry rows
        function renderScoreEntryRows() {
            if (!currentEvent) return;

            scoreEntryRows.innerHTML = '';
            currentEvent.participants.forEach(participant => {
                const player = players.find(p => p.id === participant.playerId);
                const tr = document.createElement('tr');
                tr.className = 'border-b fade-in';
                tr.innerHTML = `
                    <td class="py-2 pl-2">${participant.name}</td>
                    <td class="py-2 text-center">
                        <input type="number" class="w-16 px-2 py-1 border rounded score-input" 
                               value="${participant.score}" data-player-id="${participant.playerId}">
                    </td>
                    <td class="py-2 text-center relative-to-par">${formatRelativeToPar(participant.relativeToPar)}</td>
                    <td class="py-2 text-center">
                        <input type="number" class="payment-input px-2 py-1 border rounded payment-input" 
                               value="${participant.paymentAmount}" min="0" step="0.5"
                               data-player-id="${participant.playerId}">
                    </td>
                    <td class="py-2 text-center">
                        <input type="checkbox" class="h-5 w-5 paid-checkbox" 
                               ${participant.paid ? 'checked' : ''} data-player-id="${participant.playerId}">
                    </td>
                    <td class="py-2 text-right pr-2">
                        <button class="px-2 py-1 bg-gray-200 rounded mr-1 set-par" data-player-id="${participant.playerId}">
                            <i class="fas fa-bullseye"></i> Set Par
                        </button>
                    </td>
                `;
                scoreEntryRows.appendChild(tr);
            });

            // Add event listeners
            document.querySelectorAll('.score-input').forEach(input => {
                input.addEventListener('change', (e) => {
                    const playerId = e.target.getAttribute('data-player-id');
                    const score = parseInt(e.target.value) || 0;
                    updateParticipantScore(playerId, score);
                });
            });

            document.querySelectorAll('.payment-input').forEach(input => {
                input.addEventListener('change', (e) => {
                    const playerId = e.target.getAttribute('data-player-id');
                    const amount = parseFloat(e.target.value) || 0;
                    updateParticipantPayment(playerId, amount);
                });
            });

            document.querySelectorAll('.paid-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', (e) => {
                    const playerId = e.target.getAttribute('data-player-id');
                    const paid = e.target.checked;
                    updateParticipantPaidStatus(playerId, paid);
                });
            });

            document.querySelectorAll('.set-par').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const playerId = e.currentTarget.getAttribute('data-player-id');
                    const scoreInput = document.querySelector(`.score-input[data-player-id="${playerId}"]`);
                    const score = parseInt(scoreInput.value) || 0;
                    setAsPar(playerId, score);
                });
            });
        }

        // Update participant score
        function updateParticipantScore(playerId, score) {
            if (!currentEvent) return;
            
            const participant = currentEvent.participants.find(p => p.playerId === playerId);
            if (participant) {
                participant.score = score;
                
                // Find the lowest score to calculate relative to par
                const lowestScore = Math.min(...currentEvent.participants.map(p => p.score));
                participant.relativeToPar = participant.score - lowestScore;
                
                // Update the display
                const relativeCell = document.querySelector(`.score-input[data-player-id="${playerId}"]`).closest('tr').querySelector('.relative-to-par');
                relativeCell.textContent = formatRelativeToPar(participant.relativeToPar);
                
                saveData();
            }
        }

        // Update participant payment amount
        function updateParticipantPayment(playerId, amount) {
            if (!currentEvent) return;
            
            const participant = currentEvent.participants.find(p => p.playerId === playerId);
            if (participant) {
                participant.paymentAmount = amount;
                saveData();
            }
        }

        // Update participant paid status
        function updateParticipantPaidStatus(playerId, paid) {
            if (!currentEvent) return;
            
            const participant = currentEvent.participants.find(p => p.playerId === playerId);
            if (participant) {
                participant.paid = paid;
                saveData();
                updateFinancialSummary();
            }
        }

        // Set a score as par (0)
        function setAsPar(playerId, parScore) {
            if (!currentEvent) return;
            
            currentEvent.participants.forEach(participant => {
                const scoreInput = document.querySelector(`.score-input[data-player-id="${participant.playerId}"]`);
                const currentScore = parseInt(scoreInput.value) || 0;
                const newScore = currentScore - parScore;
                scoreInput.value = newScore;
                updateParticipantScore(participant.playerId, newScore);
            });
        }

        // Format relative to par
        function formatRelativeToPar(value) {
            if (value === 0) return 'E';
            return value > 0 ? `+${value}` : value;
        }

        // End event
        endEventBtn.addEventListener('click', () => {
            if (!currentEvent) return;
            
            // Determine winner(s)
            const minScore = Math.min(...currentEvent.participants.map(p => p.score));
            const winners = currentEvent.participants.filter(p => p.score === minScore);
            
            // Calculate total collected for this event
            const eventCollected = currentEvent.participants
                .filter(p => p.paid)
                .reduce((sum, p) => sum + p.paymentAmount, 0);
            
            // Record player payments
            currentEvent.participants.forEach(participant => {
                if (participant.paid) {
                    playerPayments.push({
                        id: Date.now().toString(),
                        playerId: participant.playerId,
                        eventId: currentEvent.id,
                        eventName: `${formatDate(currentEvent.date)} @ ${currentEvent.course}`,
                        date: currentEvent.date,
                        amount: participant.paymentAmount
                    });
                    
                    // Update player's total paid
                    const player = players.find(p => p.id === participant.playerId);
                    if (player) {
                        player.totalPaid += participant.paymentAmount;
                        
                        // Add to player's credits if not paid out yet
                        const playerPayouts = payouts.filter(p => p.playerId === participant.playerId);
                        const totalPayout = playerPayouts.reduce((sum, p) => sum + p.amount, 0);
                        
                        if (player.totalPayout < player.totalPaid) {
                            player.credits = player.totalPaid - player.totalPayout;
                        } else {
                            player.credits = 0;
                        }
                    }
                }
            });
            
            // Update player stats
            currentEvent.participants.forEach(participant => {
                const player = players.find(p => p.id === participant.playerId);
                if (player) {
                    player.eventsPlayed++;
                    player.totalScore += participant.score;
                    
                    if (winners.some(w => w.playerId === participant.playerId)) {
                        player.wins++;
                    }
                }
            });
            
            // Add to event history
            events.push({
                id: currentEvent.id,
                date: currentEvent.date,
                course: currentEvent.course,
                winner: winners.map(w => w.name).join(', '),
                payout: winners.length > 0 ? calculatePayout(currentEvent) : 0,
                collected: eventCollected,
                participantCount: currentEvent.participants.length
            });
            
            // Reset current event
            currentEvent = null;
            scoringSection.classList.add('hidden');
            
            // Update displays
            renderEventHistory();
            renderPlayerStats();
            updateFinancialSummary();
            renderPayoutList();
            saveData();
        });

        // Calculate potential payout for an event
        function calculatePayout(event) {
            const paidParticipants = event.participants.filter(p => p.paid);
            const totalCollected = paidParticipants.reduce((sum, p) => sum + p.paymentAmount, 0);
            return totalCollected;
        }

        // Add payout
        addPayoutBtn.addEventListener('click', () => {
            const playerId = payoutPlayerSelect.value;
            const amount = parseFloat(payoutAmountInput.value) || 0;
            
            if (!playerId || amount <= 0) {
                alert('Please select a player and enter a valid amount');
                return;
            }
            
            const player = players.find(p => p.id === playerId);
            if (!player) return;
            
            payouts.push({
                id: Date.now().toString(),
                playerId: playerId,
                playerName: player.name,
                amount: amount,
                date: new Date().toISOString().split('T')[0]
            });
            
            // Update player's total payout
            player.totalPayout += amount;
            
            // Update player's credits
            if (player.totalPayout < player.totalPaid) {
                player.credits = player.totalPaid - player.totalPayout;
            } else {
                player.credits = 0;
            }
            
            payoutAmountInput.value = '';
            renderPayoutList();
            renderPlayerStats();
            updateFinancialSummary();
            saveData();
        });

        // Render payout list
        function renderPayoutList() {
            payoutList.innerHTML = '';
            players.forEach(player => {
                const playerPayouts = payouts.filter(p => p.playerId === player.id);
                const totalPayout = playerPayouts.reduce((sum, p) => sum + p.amount, 0);
                
                // Calculate credits (total paid - total payout)
                const credits = player.totalPaid - totalPayout;
                
                const tr = document.createElement('tr');
                tr.className = 'fade-in';
                tr.innerHTML = `
                    <td class="py-1 pl-2">${player.name}</td>
                    <td class="py-1 text-right pr-2 money-out">$${totalPayout.toFixed(2)}</td>
                    <td class="py-1 text-right pr-2 money-in">$${Math.max(0, credits).toFixed(2)}</td>
                    <td class="py-1 text-right pr-2">
                        <button class="text-green-600 hover:text-green-800 add-payout" data-id="${player.id}" title="Add payout">
                            <i class="fas fa-plus"></i>
                        </button>
                    </td>
                `;
                payoutList.appendChild(tr);
            });
            
            // Add payout event listeners
            document.querySelectorAll('.add-payout').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const playerId = e.currentTarget.getAttribute('data-id');
                    const player = players.find(p => p.id === playerId);
                    if (player) {
                        payoutPlayerSelect.value = playerId;
                        payoutAmountInput.focus();
                    }
                });
            });
        }

        // Update financial summary
        function updateFinancialSummary() {
            // Total collected from all events
            const totalCollected = events.reduce((sum, event) => {
                return sum + event.collected;
            }, 0);
            
            // Total paid out
            const totalPaidOut = payouts.reduce((sum, payout) => sum + payout.amount, 0);
            
            // League balance
            const balance = totalCollected - totalPaidOut;
            
            // Update in real-time from current event if it exists
            if (currentEvent) {
                const currentCollected = currentEvent.participants
                    .filter(p => p.paid)
                    .reduce((sum, p) => sum + p.paymentAmount, 0);
                
                totalCollectedSpan.textContent = `$${(totalCollected + currentCollected).toFixed(2)}`;
            } else {
                totalCollectedSpan.textContent = `$${totalCollected.toFixed(2)}`;
            }
            
            totalPaidOutSpan.textContent = `$${totalPaidOut.toFixed(2)}`;
            leagueBalanceSpan.textContent = `$${balance.toFixed(2)}`;
            
            // Color balance based on value
            if (balance < 0) {
                leagueBalanceSpan.classList.remove('money-in');
                leagueBalanceSpan.classList.add('money-out');
            } else {
                leagueBalanceSpan.classList.remove('money-out');
                leagueBalanceSpan.classList.add('money-in');
            }
        }

        // Render event history
        function renderEventHistory() {
            eventHistory.innerHTML = '';
            events.slice().reverse().forEach(event => {
                const tr = document.createElement('tr');
                tr.className = 'border-b fade-in hover:bg-gray-50';
                tr.innerHTML = `
                    <td class="py-2 pl-2">${formatDate(event.date)}</td>
                    <td class="py-2">${event.course}</td>
                    <td class="py-2 text-center">${event.participantCount}</td>
                    <td class="py-2 text-center">${event.winner}</td>
                    <td class="py-2 text-right pr-2 money-out">$${event.payout.toFixed(2)}</td>
                    <td class="py-2 text-right pr-2 money-in">$${event.collected.toFixed(2)}</td>
                `;
                eventHistory.appendChild(tr);
            });
        }

        // Render player stats
        function renderPlayerStats() {
            playerStats.innerHTML = '';
            players.forEach(player => {
                const avgScore = player.eventsPlayed > 0 
                    ? (player.totalScore / player.eventsPlayed).toFixed(1)
                    : '-';
                
                const tr = document.createElement('tr');
                tr.className = 'border-b fade-in hover:bg-gray-50';
                tr.innerHTML = `
                    <td class="py-2 pl-2">${player.name}</td>
                    <td class="py-2 text-center">${player.eventsPlayed}</td>
                    <td class="py-2 text-center">${player.wins}</td>
                    <td class="py-2 text-center">${avgScore}</td>
                    <td class="py-2 text-right pr-2 money-in">$${player.totalPaid.toFixed(2)}</td>
                    <td class="py-2 text-right pr-2 money-in">$${player.totalPayout.toFixed(2)}</td>
                    <td class="py-2 text-right pr-2 money-in credits-column">$${Math.max(0, player.credits).toFixed(2)}</td>
                `;
                playerStats.appendChild(tr);
            });
        }

        // Format date as MM/DD/YYYY
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US');
        }

        // Initialize
        loadData();
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Chainrattler/instantcoder" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>