-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
857 lines (736 loc) · 41.2 KB
/
Copy pathindex.html
File metadata and controls
857 lines (736 loc) · 41.2 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Lucky 9 Boxes - Global Config</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800&family=Sarabun:wght@400;600&display=swap" rel="stylesheet">
<!-- Lucide Icons -->
<script src="https://unpkg.com/lucide@latest"></script>
<!-- Confetti Library -->
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
<!-- FingerprintJS -->
<script>
const fpPromise = import('https://openfpcdn.io/fingerprintjs/v4')
.then(FingerprintJS => FingerprintJS.load());
</script>
<style>
body {
font-family: 'Poppins', 'Sarabun', sans-serif;
background: linear-gradient(135deg, #7f1d1d 0%, #b91c1c 50%, #ea580c 100%);
height: 100vh;
overflow: hidden;
touch-action: manipulation;
}
/* Glassmorphism Classes */
.glass-panel {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
}
.glass-box {
background: linear-gradient(135deg, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0.05) 100%);
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.3);
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
overflow: hidden;
}
.glass-box:hover {
transform: translateY(-2px);
border-color: rgba(255,255,255,0.6);
box-shadow: 0 0 15px rgba(255, 255, 255, 0.4);
}
.glass-box:active {
transform: scale(0.95);
}
.glass-box.disabled {
opacity: 0.5;
pointer-events: none;
filter: grayscale(1);
}
.glass-box.winner {
background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
border-color: #FFF;
box-shadow: 0 0 30px #FFD700;
animation: pulse-gold 1.5s infinite;
z-index: 10;
}
.glass-box.loser {
background: rgba(0,0,0,0.3);
border-color: rgba(255,0,0,0.3);
animation: shake 0.5s ease-in-out;
}
.admin-row:nth-child(even) { background-color: rgba(255, 255, 255, 0.05); }
.admin-row:hover { background-color: rgba(255, 255, 255, 0.1); }
.custom-scroll::-webkit-scrollbar { width: 6px; }
.custom-scroll::-webkit-scrollbar-track { background: rgba(0,0,0,0.1); }
.custom-scroll::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.3); border-radius: 3px; }
@keyframes pulse-gold {
0% { box-shadow: 0 0 0 0 rgba(255, 215, 0, 0.7); }
70% { box-shadow: 0 0 0 15px rgba(255, 215, 0, 0); }
100% { box-shadow: 0 0 0 0 rgba(255, 215, 0, 0); }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
20% { transform: translateX(-5px); }
40% { transform: translateX(5px); }
60% { transform: translateX(-5px); }
80% { transform: translateX(5px); }
}
@keyframes popIn {
0% { transform: scale(0.5); opacity: 0; }
100% { transform: scale(1); opacity: 1; }
}
.modal-enter { animation: popIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; }
.shine::after {
content: ''; position: absolute; top: 0; left: -100%; width: 50%; height: 100%;
background: linear-gradient(to right, rgba(255,255,255,0) 0%, rgba(255,255,255,0.3) 50%, rgba(255,255,255,0) 100%);
transform: skewX(-25deg); animation: shine 3s infinite;
}
@keyframes shine { 100% { left: 125%; } }
/* Loading Overlay */
#loadingOverlay {
transition: opacity 0.5s ease;
}
</style>
</head>
<body class="text-white select-none flex flex-col items-center justify-center relative p-4">
<!-- Loading Overlay -->
<div id="loadingOverlay" class="fixed inset-0 z-[100] bg-slate-900 flex flex-col items-center justify-center">
<div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-yellow-500 mb-4"></div>
<p class="text-yellow-500 font-bold animate-pulse">Connecting to Game Server...</p>
<p id="loadingStatus" class="text-slate-500 text-xs mt-2">Fetching global rules</p>
</div>
<!-- Header Section -->
<header class="w-full max-w-md flex justify-between items-center mb-6 z-10">
<div class="flex items-center gap-2 cursor-pointer select-none active:opacity-70 transition-opacity" id="adminTrigger">
<div class="bg-white/20 p-2 rounded-lg backdrop-blur-sm">
<i data-lucide="gift" class="w-6 h-6 text-yellow-300"></i>
</div>
<span class="font-bold text-lg tracking-wide uppercase text-white/90">ร้าน<span class="text-yellow-300">หนานหล่อ</span></span>
</div>
<button id="soundToggle" class="p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors backdrop-blur-sm">
<i id="soundIcon" data-lucide="volume-2" class="w-5 h-5"></i>
</button>
</header>
<!-- Main Game Container -->
<main class="w-full max-w-md flex flex-col items-center z-10">
<div class="text-center mb-8">
<h1 class="text-4xl md:text-5xl font-extrabold mb-2 drop-shadow-lg leading-tight">
หนานหล่อ <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-yellow-300 to-yellow-500">แจกโชคใหญ่</span>
</h1>
<p class="text-white/80 text-sm md:text-base font-light">เปิดกล่องลุ้นรับของรางวัลสุดพิเศษ! จากร้านหนานหล่อ</p>
</div>
<!-- The Grid -->
<div id="gameGrid" class="grid grid-cols-3 gap-3 md:gap-4 w-full aspect-square mb-6 opacity-0 transition-opacity duration-1000 ease-out">
<!-- Items generated by JS -->
</div>
<!-- View Result Button -->
<button id="viewResultBtn" class="hidden w-full max-w-xs mx-auto py-3 rounded-xl bg-white/20 hover:bg-white/30 backdrop-blur-sm border border-white/30 text-white font-semibold transition-all shadow-lg active:scale-95 mb-4 flex items-center justify-center gap-2">
<i data-lucide="eye" class="w-5 h-5"></i>
ดูผลรางวัลของคุณ
</button>
<div class="mt-4 text-center opacity-60 text-xs">
<p>กิจกรรมพิเศษจาก ร้านหนานหล่อ</p>
</div>
</main>
<!-- Result Modal -->
<div id="resultModal" class="fixed inset-0 z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300 bg-black/60 backdrop-blur-sm">
<div id="modalCard" class="glass-panel w-11/12 max-w-sm p-8 rounded-3xl text-center transform scale-90 transition-transform duration-300">
<div id="modalIconContainer" class="mx-auto w-20 h-20 rounded-full flex items-center justify-center mb-4 shadow-xl">
<i id="modalIcon" data-lucide="trophy" class="w-10 h-10 text-white"></i>
</div>
<h2 id="modalTitle" class="text-3xl font-bold mb-2">You Won!</h2>
<p id="modalMessage" class="text-white/80 mb-6">Congratulations!</p>
<div id="rewardSection" class="hidden mb-6 bg-white/10 rounded-xl p-3 border border-dashed border-white/30">
<p class="text-xs text-white/60 uppercase tracking-widest mb-1">รหัสรางวัลของคุณ</p>
<code class="text-xl font-mono text-yellow-300 font-bold select-all">Waiting...</code>
</div>
<button id="playAgainBtn" class="w-full py-4 rounded-xl font-bold text-lg shadow-lg transform active:scale-95 transition-all">
Play Again
</button>
</div>
</div>
<!-- Admin Login Modal -->
<div id="adminLoginModal" class="fixed inset-0 z-[70] flex items-center justify-center hidden bg-black/80 backdrop-blur-sm">
<div class="glass-panel w-11/12 max-w-xs p-6 rounded-2xl text-center shadow-2xl transform transition-all scale-100">
<div class="mx-auto w-12 h-12 bg-white/10 rounded-full flex items-center justify-center mb-4">
<i data-lucide="lock" class="text-white w-6 h-6"></i>
</div>
<h3 class="text-xl font-bold mb-4 text-white">Admin Access</h3>
<input type="password" id="adminPasswordInput" placeholder="Enter Password" class="w-full bg-black/30 border border-white/20 rounded-lg p-3 text-white placeholder-white/40 mb-4 focus:outline-none focus:border-yellow-400 text-center tracking-widest">
<div class="flex gap-2">
<button id="cancelLoginBtn" class="flex-1 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white text-sm font-medium transition-colors">Cancel</button>
<button id="confirmLoginBtn" class="flex-1 py-2 rounded-lg bg-yellow-500 hover:bg-yellow-400 text-black font-bold text-sm shadow-lg transition-colors">Login</button>
</div>
<p id="loginErrorMsg" class="text-red-400 text-xs mt-3 hidden">Incorrect Password</p>
</div>
</div>
<!-- Admin Panel Modal -->
<div id="adminModal" class="fixed inset-0 z-[60] flex items-center justify-center hidden bg-black/80 backdrop-blur-md">
<div class="w-11/12 max-w-4xl h-[80vh] bg-slate-900 border border-slate-700 rounded-2xl flex flex-col shadow-2xl overflow-hidden text-sm relative">
<!-- Admin Header -->
<div class="p-4 bg-slate-800 border-b border-slate-700 flex justify-between items-center flex-shrink-0">
<div class="flex items-center gap-2">
<i data-lucide="cloud" class="text-blue-400"></i>
<h2 class="font-bold text-lg text-white">Global Config & Logs</h2>
</div>
<button onclick="toggleAdminPanel(false)" class="p-1.5 hover:bg-white/10 rounded-full transition-colors">
<i data-lucide="x" class="w-5 h-5 text-slate-400"></i>
</button>
</div>
<div class="flex-1 overflow-auto custom-scroll p-4 space-y-6">
<!-- GLOBAL RULES DISPLAY -->
<div class="bg-blue-900/30 rounded-xl p-4 border border-blue-700/50">
<h3 class="text-blue-300 font-bold mb-2 flex items-center gap-2">
<i data-lucide="globe"></i> Current Global Rules (Read-Only)
</h3>
<p class="text-xs text-slate-400 mb-4">
These settings are loaded from Google Sheets. To change them, edit the "CONFIG" tab in your Google Sheet.
</p>
<div class="grid grid-cols-2 gap-4">
<div class="bg-slate-900/50 p-3 rounded-lg border border-slate-700">
<span class="text-xs text-slate-500 uppercase">Cooldown Mode</span>
<p id="adminConfigMode" class="text-white font-mono font-bold text-lg">Loading...</p>
</div>
<div class="bg-slate-900/50 p-3 rounded-lg border border-slate-700">
<span class="text-xs text-slate-500 uppercase">Value</span>
<p id="adminConfigValue" class="text-white font-mono font-bold text-lg">Loading...</p>
</div>
</div>
</div>
<!-- LOGS SECTION -->
<div>
<div class="flex justify-between items-center mb-2">
<h3 class="text-white font-bold flex items-center gap-2">
<i data-lucide="list"></i> Local Player Logs
</h3>
<div class="flex gap-2">
<button onclick="clearLogs()" class="px-3 py-1.5 bg-red-600 hover:bg-red-500 rounded text-xs font-semibold flex items-center gap-1 transition-colors">
<i data-lucide="trash-2" class="w-3 h-3"></i> Clear Local
</button>
</div>
</div>
<div class="bg-slate-800/50 rounded-xl border border-slate-700 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left border-collapse">
<thead class="bg-slate-900">
<tr class="text-slate-400 text-xs uppercase tracking-wider">
<th class="p-3 font-semibold">Time</th>
<th class="p-3 font-semibold">Visitor ID</th>
<th class="p-3 font-semibold text-center">Result</th>
<th class="p-3 font-semibold text-right">Reward Code</th>
</tr>
</thead>
<tbody id="logTableBody" class="text-slate-300 divide-y divide-slate-800">
<!-- Rows injected here -->
</tbody>
</table>
</div>
<div id="noLogsMsg" class="hidden text-center text-slate-500 p-6">No local logs found.</div>
</div>
</div>
</div>
</div>
</div>
<!-- Background Decoration -->
<div class="fixed top-0 left-0 w-full h-full overflow-hidden -z-10 pointer-events-none">
<div class="absolute top-[-10%] left-[-10%] w-64 h-64 bg-red-600 rounded-full mix-blend-multiply filter blur-3xl opacity-50 animate-blob"></div>
<div class="absolute top-[-10%] right-[-10%] w-64 h-64 bg-yellow-600 rounded-full mix-blend-multiply filter blur-3xl opacity-50 animate-blob animation-delay-2000"></div>
<div class="absolute bottom-[-10%] left-[20%] w-64 h-64 bg-orange-600 rounded-full mix-blend-multiply filter blur-3xl opacity-50 animate-blob animation-delay-4000"></div>
</div>
<script>
// --- Configuration ---
// ใส่ URL ที่ได้จาก Google Apps Script Deployment ที่นี่
const GOOGLE_SCRIPT_URL = 'https://script.google.com/macros/s/AKfycbyr9jFWvN-NkGW2_yow7U1CJCMCc7HcOc6uhFoxelXC3EJG_AE1pzU4zQwpvSZ42OOv/exec';
// --- Global Variables ---
let visitorId = null;
let adminClickCount = 0;
let adminClickTimer = null;
// Global Config Cache
let globalConfig = {
cooldown_mode: 'once', // default fallback
cooldown_value: 0
};
// Storage Keys
const LOG_STORAGE_KEY = 'luckyBox_nhanlor_logs';
const PLAYED_KEY_PREFIX = 'luckyBox_nhanlor_played_'; // Legacy Key
const LAST_PLAYED_KEY_PREFIX = 'luckyBox_nhanlor_last_timestamp_'; // Timestamp Key
const RESULT_DATA_PREFIX = 'luckyBox_nhanlor_data_';
// --- Game State ---
const state = {
isPlaying: false, // Start false until config loads
winningIndex: null,
soundEnabled: true,
totalBoxes: 9,
playStatus: { allowed: false, reason: null, remainingMs: 0 }
};
const losingMessages = [
"กล่องนี้... ว่างเปล่าเหมือนใจเธอ",
"หนานหล่อบอกว่า... ลองใหม่วันหลังนะ",
"ของรางวัลชิ้นนี้ยังไม่ใช่ของคุณ",
"ว้า! อดได้ของขวัญเลย",
"ของรางวัลรออยู่... แต่ไม่ใช่กล่องนี้",
"ผิดกล่อง! แต่ไม่ผิดใจที่มาร้านเรา",
"เกือบได้รางวัลใหญ่แล้วเชียว!"
];
const winningMessages = [
"🎉 ยินดีด้วย! รับของขวัญสุดพิเศษไปเลย!",
"ดวงเฮงสุดๆ! รับรางวัล Limited Edition จากหนานหล่อ",
"สุดยอด! เตรียมรับความเซอร์ไพรส์ได้เลย",
"ช่องนี้แหละ... ที่ซ่อนโชคใหญ่เอาไว้!",
"คุณคือผู้โชคดี ได้รับของรางวัลพรีเมียม!"
];
function generateRewardCode() {
return 'NH-' + Math.random().toString(36).substring(2, 8).toUpperCase();
}
// --- FETCH GLOBAL CONFIG ---
async function loadGlobalConfig() {
const loadingOverlay = document.getElementById('loadingOverlay');
const loadingStatus = document.getElementById('loadingStatus');
if (!GOOGLE_SCRIPT_URL || GOOGLE_SCRIPT_URL.includes('YOUR_GOOGLE_SCRIPT_URL')) {
console.warn("No API URL configured. Using default rules.");
loadingOverlay.style.opacity = '0';
setTimeout(() => loadingOverlay.style.display = 'none', 500);
return;
}
try {
loadingStatus.innerText = "Downloading game rules...";
const response = await fetch(GOOGLE_SCRIPT_URL);
if (!response.ok) throw new Error("Network response was not ok");
const data = await response.json();
// Map API response to our config object
globalConfig = {
cooldown_mode: data.cooldown_mode || 'once',
cooldown_value: parseInt(data.cooldown_value) || 0
};
console.log("Global Config Loaded:", globalConfig);
} catch (error) {
console.error("Failed to load global config:", error);
// Fallback is already set in globalConfig definition (once)
loadingStatus.innerText = "Connection failed. Using default rules.";
} finally {
// Hide loader
loadingOverlay.style.opacity = '0';
setTimeout(() => loadingOverlay.style.display = 'none', 500);
}
}
// --- LOGIC: Check Play Eligibility ---
function checkPlayEligibility(vid) {
const lastPlayedStr = localStorage.getItem(`${LAST_PLAYED_KEY_PREFIX}${vid}`);
const legacyPlayed = localStorage.getItem(`${PLAYED_KEY_PREFIX}${vid}`) === 'true';
// Case 1: New Player
if (!lastPlayedStr && !legacyPlayed) {
return { allowed: true };
}
const lastPlayed = lastPlayedStr ? parseInt(lastPlayedStr) : (legacyPlayed ? Date.now() : 0);
// Use Global Config Logic
if (globalConfig.cooldown_mode === 'once') {
return { allowed: false, reason: 'limit_reached' };
}
// Calculate Cooldown
let cooldownMs = 0;
if (globalConfig.cooldown_mode === 'hour') cooldownMs = globalConfig.cooldown_value * 60 * 60 * 1000;
if (globalConfig.cooldown_mode === 'day') cooldownMs = globalConfig.cooldown_value * 24 * 60 * 60 * 1000;
const now = Date.now();
const diff = now - lastPlayed;
if (diff >= cooldownMs) {
return { allowed: true };
} else {
return { allowed: false, reason: 'cooldown', remainingMs: cooldownMs - diff };
}
}
function msToTime(duration) {
let minutes = Math.floor((duration / (1000 * 60)) % 60);
let hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
let days = Math.floor(duration / (1000 * 60 * 60 * 24));
let parts = [];
if (days > 0) parts.push(days + " days");
if (hours > 0) parts.push(hours + " hr");
parts.push(minutes + " min");
return parts.join(" ");
}
// --- Logging System ---
function logPlay(vid, isWin, code) {
const timestamp = new Date().toLocaleString('th-TH');
const resultStr = isWin ? 'WIN' : 'LOSE';
const codeStr = code || '-';
const userAgent = navigator.userAgent;
// 1. Google Sheet (POST)
if (GOOGLE_SCRIPT_URL && !GOOGLE_SCRIPT_URL.includes('YOUR_GOOGLE_SCRIPT_URL')) {
const params = new URLSearchParams();
params.append('timestamp', timestamp);
params.append('visitorId', vid || 'Unknown');
params.append('result', resultStr);
params.append('rewardCode', codeStr);
params.append('userAgent', userAgent);
fetch(GOOGLE_SCRIPT_URL, {
method: 'POST', body: params, mode: 'no-cors'
}).catch(err => console.error("Sheet Error", err));
}
// 2. Local Cache
try {
const logs = JSON.parse(localStorage.getItem(LOG_STORAGE_KEY) || '[]');
logs.unshift({ timestamp, visitorId: vid, result: resultStr, code: codeStr, userAgent });
if (logs.length > 50) logs.pop();
localStorage.setItem(LOG_STORAGE_KEY, JSON.stringify(logs));
} catch (e) { console.error("Local log error", e); }
}
// --- Admin UI Functions ---
function toggleAdminPanel(show) {
const panel = document.getElementById('adminModal');
if (show) {
renderLogs();
// Update Admin Read-Only Display
document.getElementById('adminConfigMode').innerText = globalConfig.cooldown_mode.toUpperCase();
document.getElementById('adminConfigValue').innerText = globalConfig.cooldown_value;
panel.classList.remove('hidden');
} else {
panel.classList.add('hidden');
}
}
// Login Modal Functions
function toggleLoginModal(show) {
const loginModal = document.getElementById('adminLoginModal');
const passwordInput = document.getElementById('adminPasswordInput');
const errorMsg = document.getElementById('loginErrorMsg');
if (show) {
loginModal.classList.remove('hidden');
passwordInput.value = '';
errorMsg.classList.add('hidden');
setTimeout(() => passwordInput.focus(), 100);
} else {
loginModal.classList.add('hidden');
}
}
function handleLogin() {
const passwordInput = document.getElementById('adminPasswordInput');
const errorMsg = document.getElementById('loginErrorMsg');
if (passwordInput.value === 'admin') {
toggleLoginModal(false);
toggleAdminPanel(true);
} else {
errorMsg.classList.remove('hidden');
passwordInput.classList.add('border-red-500');
setTimeout(() => passwordInput.classList.remove('border-red-500'), 500);
}
}
function renderLogs() {
const tbody = document.getElementById('logTableBody');
const noLogs = document.getElementById('noLogsMsg');
tbody.innerHTML = '';
const logs = JSON.parse(localStorage.getItem(LOG_STORAGE_KEY) || '[]');
if (logs.length === 0) {
noLogs.classList.remove('hidden'); return;
}
noLogs.classList.add('hidden');
logs.forEach(log => {
const tr = document.createElement('tr');
tr.className = 'admin-row border-b border-slate-800/50';
const winClass = log.result === 'WIN' ? 'text-green-400 font-bold' : 'text-red-400';
const codeClass = log.code !== '-' ? 'text-yellow-400 font-mono' : 'text-slate-600';
tr.innerHTML = `
<td class="p-3 whitespace-nowrap text-slate-400">${log.timestamp}</td>
<td class="p-3 font-mono text-xs text-blue-300">${log.visitorId}</td>
<td class="p-3 text-center ${winClass}">${log.result}</td>
<td class="p-3 text-right ${codeClass}">${log.code}</td>
`;
tbody.appendChild(tr);
});
}
function clearLogs() {
if(confirm('Clear LOCAL cache?')) {
localStorage.removeItem(LOG_STORAGE_KEY);
renderLogs();
}
}
// --- Audio Engine ---
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
function playTone(type) {
if (!state.soundEnabled) return;
if (audioCtx.state === 'suspended') audioCtx.resume();
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
const now = audioCtx.currentTime;
if (type === 'click') {
osc.type = 'sine'; osc.frequency.setValueAtTime(800, now); osc.frequency.exponentialRampToValueAtTime(300, now + 0.1);
gainNode.gain.setValueAtTime(0.3, now); gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.1);
osc.start(now); osc.stop(now + 0.1);
} else if (type === 'win') {
osc.type = 'triangle'; osc.frequency.setValueAtTime(523.25, now); osc.frequency.setValueAtTime(659.25, now + 0.1);
osc.frequency.setValueAtTime(783.99, now + 0.2); osc.frequency.setValueAtTime(1046.50, now + 0.3);
gainNode.gain.setValueAtTime(0, now); gainNode.gain.linearRampToValueAtTime(0.5, now + 0.1); gainNode.gain.exponentialRampToValueAtTime(0.01, now + 1.5);
osc.start(now); osc.stop(now + 1.5);
} else if (type === 'lose') {
osc.type = 'sawtooth'; osc.frequency.setValueAtTime(200, now); osc.frequency.linearRampToValueAtTime(150, now + 0.3);
gainNode.gain.setValueAtTime(0.3, now); gainNode.gain.exponentialRampToValueAtTime(0.01, now + 0.5);
osc.start(now); osc.stop(now + 0.5);
}
}
// --- DOM Elements ---
const grid = document.getElementById('gameGrid');
const modal = document.getElementById('resultModal');
const modalCard = document.getElementById('modalCard');
const soundToggle = document.getElementById('soundToggle');
const soundIcon = document.getElementById('soundIcon');
const playAgainBtn = document.getElementById('playAgainBtn');
const viewResultBtn = document.getElementById('viewResultBtn');
const adminTrigger = document.getElementById('adminTrigger');
const cancelLoginBtn = document.getElementById('cancelLoginBtn');
const confirmLoginBtn = document.getElementById('confirmLoginBtn');
const adminPasswordInput = document.getElementById('adminPasswordInput');
// --- Initialization ---
async function initGame() {
// 1. Load Fingerprint
try {
const fp = await fpPromise;
const result = await fp.get();
visitorId = result.visitorId;
} catch (error) {
console.error("Fingerprint error:", error);
visitorId = 'fallback_' + Math.random().toString(36);
}
// 2. Fetch Global Config
await loadGlobalConfig();
// 3. CHECK PLAY ELIGIBILITY
const status = checkPlayEligibility(visitorId);
state.playStatus = status;
// Update UI based on status
if (!status.allowed) {
state.isPlaying = false;
showLockedState(status.reason, status.remainingMs);
// Show last result if available
try {
const savedResult = JSON.parse(localStorage.getItem(`${RESULT_DATA_PREFIX}${visitorId}`));
if (savedResult) {
restoreResultModal(savedResult);
viewResultBtn.classList.remove('hidden');
}
} catch (e) {}
grid.classList.remove('opacity-0');
return;
}
// 4. ALLOW PLAY
state.isPlaying = true;
state.winningIndex = null;
grid.innerHTML = '';
for (let i = 0; i < state.totalBoxes; i++) {
const box = document.createElement('div');
box.className = 'glass-box rounded-2xl flex items-center justify-center cursor-pointer shine';
box.dataset.index = i;
box.innerHTML = `<i data-lucide="gift" class="w-8 h-8 md:w-10 md:h-10 text-white/70 transition-transform duration-300"></i>`;
box.addEventListener('click', () => handleBoxClick(i, box));
grid.appendChild(box);
}
lucide.createIcons();
toggleModal(false);
grid.classList.remove('opacity-0');
}
function showLockedState(reason, remainingMs) {
grid.innerHTML = '';
for (let i = 0; i < state.totalBoxes; i++) {
const box = document.createElement('div');
box.className = 'glass-box rounded-2xl flex items-center justify-center disabled opacity-30';
box.innerHTML = `<i data-lucide="lock" class="w-8 h-8 md:w-10 md:h-10 text-white/50"></i>`;
grid.appendChild(box);
}
lucide.createIcons();
const headerTitle = document.querySelector('h1');
const subTitle = document.querySelector('main p');
if (reason === 'cooldown') {
const timeLeft = msToTime(remainingMs);
if(headerTitle) headerTitle.innerHTML = `<span class="text-gray-300">รอเล่นรอบถัดไป</span>`;
if(subTitle) subTitle.innerText = `อีก ${timeLeft} ถึงจะเล่นได้อีกครั้ง`;
} else {
if(headerTitle) headerTitle.innerHTML = `<span class="text-gray-300">ใช้สิทธิ์ไปแล้ว</span>`;
if(subTitle) subTitle.innerText = "ขอบคุณที่ร่วมสนุกกับร้านหนานหล่อ ไว้เจอกันใหม่นะ!";
}
}
// --- Game Logic ---
function handleBoxClick(index, boxElement) {
if (!state.isPlaying) return;
if (state.winningIndex === null) {
state.winningIndex = Math.floor(Math.random() * state.totalBoxes);
}
state.isPlaying = false;
// SAVE PLAY TIMESTAMP
if (visitorId) {
const now = Date.now();
localStorage.setItem(`${LAST_PLAYED_KEY_PREFIX}${visitorId}`, now.toString());
localStorage.setItem(`${PLAYED_KEY_PREFIX}${visitorId}`, 'true');
}
if (navigator.vibrate) navigator.vibrate(50);
Array.from(grid.children).forEach((child, idx) => {
if (idx !== index) child.classList.add('disabled');
});
if (index === state.winningIndex) {
boxElement.classList.add('winner');
boxElement.innerHTML = `<i data-lucide="crown" class="w-10 h-10 text-white drop-shadow-md"></i>`;
lucide.createIcons();
playTone('win');
triggerConfetti();
const rewardCode = generateRewardCode();
logPlay(visitorId, true, rewardCode);
setTimeout(() => showResult(true, rewardCode), 1000);
} else {
playTone('lose');
boxElement.classList.add('loser');
if (navigator.vibrate) navigator.vibrate([50, 50, 50]);
boxElement.innerHTML = `<i data-lucide="x-circle" class="w-10 h-10 text-white/50"></i>`;
lucide.createIcons();
logPlay(visitorId, false, null);
setTimeout(() => showResult(false, null), 800);
}
}
function showResult(isWin, code) {
const modalIconContainer = document.getElementById('modalIconContainer');
const modalTitle = document.getElementById('modalTitle');
const modalMessage = document.getElementById('modalMessage');
const rewardSection = document.getElementById('rewardSection');
const playAgainBtn = document.getElementById('playAgainBtn');
const codeElement = document.querySelector('#rewardSection code');
playAgainBtn.style.display = 'none';
let resultData = { isWin: isWin, title: "", message: "", code: "" };
if (isWin) {
modalIconContainer.className = "mx-auto w-20 h-20 rounded-full flex items-center justify-center mb-4 shadow-xl bg-gradient-to-br from-yellow-300 to-orange-500";
modalCard.querySelector('#modalIcon').outerHTML = '<i id="modalIcon" data-lucide="party-popper" class="w-10 h-10 text-white"></i>';
resultData.title = "ยินดีด้วย! คุณชนะ!";
resultData.message = winningMessages[Math.floor(Math.random() * winningMessages.length)];
resultData.code = code;
modalTitle.textContent = resultData.title;
modalTitle.className = "text-3xl font-bold mb-2 text-transparent bg-clip-text bg-gradient-to-r from-yellow-200 to-yellow-500";
modalMessage.textContent = resultData.message;
codeElement.innerText = resultData.code;
rewardSection.classList.remove('hidden');
} else {
modalIconContainer.className = "mx-auto w-20 h-20 rounded-full flex items-center justify-center mb-4 shadow-xl bg-gray-600";
modalCard.querySelector('#modalIcon').outerHTML = '<i id="modalIcon" data-lucide="refresh-cw" class="w-10 h-10 text-white/80"></i>';
resultData.title = "ว้า... แย่จัง!";
resultData.message = losingMessages[Math.floor(Math.random() * losingMessages.length)];
modalTitle.textContent = resultData.title;
modalTitle.className = "text-3xl font-bold mb-2 text-white";
modalMessage.textContent = resultData.message;
rewardSection.classList.add('hidden');
}
if (visitorId) {
localStorage.setItem(`${RESULT_DATA_PREFIX}${visitorId}`, JSON.stringify(resultData));
}
viewResultBtn.classList.remove('hidden');
lucide.createIcons();
toggleModal(true);
}
function restoreResultModal(data) {
const modalIconContainer = document.getElementById('modalIconContainer');
const modalTitle = document.getElementById('modalTitle');
const modalMessage = document.getElementById('modalMessage');
const rewardSection = document.getElementById('rewardSection');
const playAgainBtn = document.getElementById('playAgainBtn');
const codeElement = document.querySelector('#rewardSection code');
playAgainBtn.style.display = 'none';
if (data.isWin) {
modalIconContainer.className = "mx-auto w-20 h-20 rounded-full flex items-center justify-center mb-4 shadow-xl bg-gradient-to-br from-yellow-300 to-orange-500";
modalCard.querySelector('#modalIcon').outerHTML = '<i id="modalIcon" data-lucide="party-popper" class="w-10 h-10 text-white"></i>';
modalTitle.className = "text-3xl font-bold mb-2 text-transparent bg-clip-text bg-gradient-to-r from-yellow-200 to-yellow-500";
rewardSection.classList.remove('hidden');
codeElement.innerText = data.code;
} else {
modalIconContainer.className = "mx-auto w-20 h-20 rounded-full flex items-center justify-center mb-4 shadow-xl bg-gray-600";
modalCard.querySelector('#modalIcon').outerHTML = '<i id="modalIcon" data-lucide="refresh-cw" class="w-10 h-10 text-white/80"></i>';
modalTitle.className = "text-3xl font-bold mb-2 text-white";
rewardSection.classList.add('hidden');
}
modalTitle.textContent = data.title;
modalMessage.textContent = data.message;
lucide.createIcons();
}
function toggleModal(show) {
if (show) {
modal.classList.remove('opacity-0', 'pointer-events-none');
modalCard.classList.remove('scale-90');
modalCard.classList.add('modal-enter', 'scale-100');
} else {
modal.classList.add('opacity-0', 'pointer-events-none');
modalCard.classList.remove('modal-enter', 'scale-100');
modalCard.classList.add('scale-90');
}
}
function triggerConfetti() {
var duration = 3 * 1000;
var animationEnd = Date.now() + duration;
var defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 60 };
function randomInRange(min, max) { return Math.random() * (max - min) + min; }
var interval = setInterval(function() {
var timeLeft = animationEnd - Date.now();
if (timeLeft <= 0) return clearInterval(interval);
var particleCount = 50 * (timeLeft / duration);
confetti(Object.assign({}, defaults, { particleCount, origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 } }));
confetti(Object.assign({}, defaults, { particleCount, origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 } }));
}, 250);
}
// --- Event Listeners ---
modal.addEventListener('click', (e) => {
if (e.target === modal) toggleModal(false);
});
viewResultBtn.addEventListener('click', () => toggleModal(true));
soundToggle.addEventListener('click', () => {
state.soundEnabled = !state.soundEnabled;
if (state.soundEnabled) {
soundIcon.setAttribute('data-lucide', 'volume-2');
playTone('click');
} else {
soundIcon.setAttribute('data-lucide', 'volume-x');
}
lucide.createIcons();
});
// Secret Admin Trigger
adminTrigger.addEventListener('click', () => {
adminClickCount++;
clearTimeout(adminClickTimer);
adminClickTimer = setTimeout(() => { adminClickCount = 0; }, 1500);
if (adminClickCount >= 5) {
adminClickCount = 0;
clearTimeout(adminClickTimer);
toggleLoginModal(true);
}
});
cancelLoginBtn.addEventListener('click', () => toggleLoginModal(false));
confirmLoginBtn.addEventListener('click', handleLogin);
adminPasswordInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') handleLogin();
});
document.getElementById('adminLoginModal').addEventListener('click', (e) => {
if (e.target.id === 'adminLoginModal') toggleLoginModal(false);
});
// Start
initGame();
window.addEventListener('load', () => {
setTimeout(() => grid.classList.remove('opacity-0'), 100);
});
tailwind.config = {
theme: {
extend: {
animation: { blob: "blob 7s infinite" },
keyframes: {
blob: {
"0%": { transform: "translate(0px, 0px) scale(1)" },
"33%": { transform: "translate(30px, -50px) scale(1.1)" },
"66%": { transform: "translate(-20px, 20px) scale(0.9)" },
"100%": { transform: "translate(0px, 0px) scale(1)" },
},
},
},
},
}
</script>
</body>
</html>