<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Bốc Thẻ Trứng Bí Ẩn - 20 Thẻ Giảm Giá | Steal an Egg</title>
<!-- Tải Tailwind CSS và thư viện âm thanh Tone.js -->
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
<!-- Phông chữ tiếng Việt rõ nét -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@500;600;700;800;900&display=swap" rel="stylesheet">
<style>
/* Thiết lập chung và nền tối tương phản cao cho mini-game */
* {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
html, body {
margin: 0;
padding: 0;
min-height: 100%;
font-family: 'Be Vietnam Pro', system-ui, -apple-system, sans-serif;
background-color: #0b0920;
background-image: radial-gradient(circle at 50% 12%, #311068 0%, #101630 52%, #050814 100%);
color: #f8fafc;
overflow-x: hidden;
}
/* Họa tiết chấm lưới nhẹ ở nền */
.bg-grid {
background-image:
radial-gradient(circle at 50% 12%, #311068 0%, #101630 52%, #050814 100%),
radial-gradient(rgba(255, 255, 255, 0.06) 1px, transparent 1px);
background-size: 100% 100%, 26px 26px;
}
/* Không gian 3D sân khấu thẻ */
.stage-3d {
perspective: 1400px;
}
/* Khung thẻ nhỏ gọn, giữ nguyên tỷ lệ 1:1 (không phóng to scale > 1) để chữ & hình sắc nét tuyệt đối trên điện thoại */
.game-card {
position: absolute;
top: 50%;
left: 50%;
width: 152px;
height: 216px;
margin-left: -76px;
margin-top: -108px;
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
transition: transform 0.6s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.35s ease;
cursor: pointer;
user-select: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: geometricPrecision;
}
@media (min-width: 640px) {
.game-card {
width: 172px;
height: 244px;
margin-left: -86px;
margin-top: -122px;
}
}
/* Hai mặt trước và sau của lá thẻ - viền gọn sắc nét, không đổ bóng nhòe chồng lớp */
.card-face {
position: absolute;
inset: 0;
border-radius: 16px;
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
overflow: hidden;
box-shadow: 0 2px 0 #070a19, 0 4px 10px rgba(0, 0, 0, 0.45);
}
/* Mặt sau (úp) nền đặc tương phản cao, viền sáng tách bạch từng lá */
.card-back {
transform: rotateY(0deg);
background-color: #1c1347;
background-image: linear-gradient(160deg, #3b1778 0%, #1c1347 55%, #0d102b 100%);
border: 2px solid #c4b5fd;
}
/* Lá trên cùng của chồng bài có viền vàng nổi bật */
.game-card.top-card .card-back {
border-color: #fde047;
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.65);
}
/* Họa tiết caro mảnh phía sau thẻ */
.card-back-pattern {
background-image:
repeating-linear-gradient(45deg, rgba(216, 180, 254, 0.08) 0px, rgba(216, 180, 254, 0.08) 1px, transparent 1px, transparent 11px),
repeating-linear-gradient(-45deg, rgba(250, 204, 21, 0.06) 0px, rgba(250, 204, 21, 0.06) 1px, transparent 1px, transparent 11px);
}
/* Mặt trước (ngửa) chỉ kích hoạt khi thẻ được rút ra để không lem màu vào chồng bài */
.card-front {
display: none;
transform: rotateY(180deg);
border: 2.5px solid #ffffff;
}
.game-card.is-drawn .card-front {
display: flex;
}
/* Tia sáng lướt nhẹ chỉ chạy trên thẻ đã rút */
.game-card.is-drawn .holo-sheen::after {
content: '';
position: absolute;
top: -50%;
left: -80%;
width: 38%;
height: 200%;
background: linear-gradient(
to right,
rgba(255, 255, 255, 0) 0%,
rgba(255, 255, 255, 0.2) 50%,
rgba(255, 255, 255, 0) 100%
);
transform: rotate(24deg);
animation: sheenMove 3.8s infinite ease-in-out;
pointer-events: none;
}
@keyframes sheenMove {
0%, 20% { left: -80%; }
58%, 100% { left: 155%; }
}
/* Hiệu ứng viền vàng phát sáng cho thẻ đang chờ lật */
@keyframes pulseGlow {
0%, 100% {
box-shadow: 0 0 18px rgba(250, 204, 21, 0.55), 0 12px 26px rgba(0, 0, 0, 0.75);
}
50% {
box-shadow: 0 0 32px rgba(250, 204, 21, 0.9), 0 12px 30px rgba(168, 85, 247, 0.55);
}
}
.drawn-waiting .card-back {
animation: pulseGlow 1.5s infinite ease-in-out;
border-color: #fde047;
}
/* Vòng hào quang phía sau thẻ đã rút */
.spotlight-aura {
position: absolute;
top: 50%;
left: 50%;
width: 240px;
height: 240px;
margin-left: -120px;
margin-top: -120px;
border-radius: 9999px;
background: radial-gradient(circle, rgba(250, 204, 21, 0.24) 0%, rgba(168, 85, 247, 0.12) 48%, transparent 72%);
pointer-events: none;
opacity: 0;
transform: scale(0.75);
transition: opacity 0.45s ease, transform 0.45s ease;
}
.spotlight-aura.active {
opacity: 1;
transform: scale(1.1);
}
/* Nút game nổi khối bấm êm tay */
.btn-game {
transition: transform 0.15s ease, filter 0.15s ease, opacity 0.2s ease;
}
.btn-game:active:not(:disabled) {
transform: translateY(3px) scale(0.98);
}
.btn-game:disabled {
opacity: 0.45;
cursor: not-allowed;
filter: grayscale(0.45);
}
/* Canvas pháo hoa toàn màn hình không chặn thao tác */
#confettiCanvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 60;
}
/* Thanh cuộn tinh gọn cho cửa sổ phụ */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: rgba(15, 23, 42, 0.5);
}
::-webkit-scrollbar-thumb {
background: rgba(139, 92, 246, 0.55);
border-radius: 9999px;
}
</style>
</head>
<body class="bg-grid min-h-screen flex flex-col justify-between selection:bg-purple-500 selection:text-white">
<!-- Canvas pháo hoa chúc mừng khi lật thẻ -->
<canvas id="confettiCanvas"></canvas>
<!-- Khung thông báo nổi (thay thế hoàn toàn alert) -->
<div id="toastContainer" class="fixed top-4 left-1/2 -translate-x-1/2 z-50 flex flex-col gap-2 w-[90%] max-w-sm pointer-events-none"></div>
<!-- Thanh tiêu đề phía trên -->
<header class="w-full max-w-5xl mx-auto px-4 pt-4 pb-2 flex items-center justify-between gap-2 z-20">
<div class="flex items-center gap-2.5 min-w-0">
<div class="w-10 h-10 rounded-xl bg-gradient-to-br from-amber-400 via-orange-500 to-purple-600 flex items-center justify-center shadow-lg shadow-purple-500/30 shrink-0">
<svg class="w-6 h-6 text-white" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2C8.1 2 5 7.4 5 13.5C5 18.2 8.1 22 12 22C15.9 22 19 18.2 19 13.5C19 7.4 15.9 2 12 2ZM10.5 9C10.5 9.8 9.8 10.5 9 10.5C8.2 10.5 7.5 9.8 7.5 9C7.5 8.2 8.2 7.5 9 7.5C9.8 7.5 10.5 8.2 10.5 9ZM14.5 16.5C13.4 16.5 12.5 15.6 12.5 14.5C12.5 13.4 13.4 12.5 14.5 12.5C15.6 12.5 16.5 13.4 16.5 14.5C16.5 15.6 15.6 16.5 14.5 16.5Z"/>
</svg>
</div>
<div class="min-w-0">
<h1 class="text-sm sm:text-xl font-black tracking-tight text-amber-300 leading-tight truncate">
BỐC THẺ TRỨNG BÍ ẨN
</h1>
<p class="text-[11px] sm:text-xs text-slate-300 font-medium truncate">Mini-game Giảm Giá • Steal an Egg</p>
</div>
</div>
<!-- Nút tiện ích: Âm thanh, Lịch sử, Cài đặt Shop -->
<div class="flex items-center gap-1.5 shrink-0">
<button id="btnSound" type="button" title="Bật/Tắt âm thanh" class="p-2.5 rounded-xl bg-slate-800/90 hover:bg-slate-700 border border-slate-600 text-slate-100 transition">
<svg id="iconSoundOn" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z"/>
</svg>
<svg id="iconSoundOff" class="w-5 h-5 hidden text-rose-400" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15zM17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2"/>
</svg>
</button>
<button id="btnHistory" type="button" class="px-3 py-2.5 rounded-xl bg-slate-800/90 hover:bg-slate-700 border border-slate-600 text-xs sm:text-sm font-bold text-slate-100 flex items-center gap-1.5 transition">
<span>Lịch sử</span>
<span id="historyBadge" class="px-1.5 py-0.5 text-[11px] rounded-full bg-purple-600 text-white font-extrabold">0</span>
</button>
<button id="btnSettings" type="button" title="Quản trị & 20 thẻ" class="p-2.5 rounded-xl bg-slate-800/90 hover:bg-slate-700 border border-slate-600 text-slate-100 transition">
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
</svg>
</button>
</div>
</header>
<!-- Thanh trạng thái số thẻ, khóa 1 lần/máy & ô nhập tên -->
<section class="w-full max-w-3xl mx-auto px-4 mt-1 z-20">
<div class="bg-slate-900/90 border border-slate-700 rounded-2xl p-3 flex flex-col sm:flex-row items-center justify-between gap-2.5 shadow-xl">
<div class="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-between sm:justify-start">
<div class="flex items-center gap-2">
<span class="inline-block w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
<span class="text-xs sm:text-sm text-slate-300 font-semibold">Còn:</span>
<span id="remainingCount" class="text-base sm:text-lg font-black text-amber-400">20 / 20</span>
</div>
<div class="flex items-center gap-1.5">
<span id="deviceLimitBadge" class="px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40">
🔒 1 lượt/máy (Còn 1)
</span>
<span id="statusTag" class="px-2.5 py-1 rounded-full text-[11px] font-bold bg-indigo-500/25 text-indigo-200 border border-indigo-400/40">
Sẵn sàng
</span>
</div>
</div>
<div class="relative w-full sm:w-60">
<input
id="playerNameInput"
type="text"
maxlength="28"
placeholder="Nhập tên của bạn trước khi bốc..."
class="w-full bg-slate-800 border border-slate-600 focus:border-amber-400 focus:ring-2 focus:ring-amber-400/25 rounded-xl px-3.5 py-2 text-xs sm:text-sm text-white placeholder-slate-400 outline-none transition"
>
</div>
</div>
</section>
<!-- Sân khấu 3D chứa 20 tấm thẻ chồng lên nhau -->
<main class="relative flex-1 flex flex-col items-center justify-center w-full max-w-4xl mx-auto px-4 py-3 min-h-[300px] sm:min-h-[345px]">
<!-- Dòng hướng dẫn -->
<div id="stageHint" class="mb-2 text-center min-h-[28px] flex items-center justify-center z-20">
<p class="text-xs sm:text-sm text-purple-100 font-semibold bg-purple-950/85 border border-purple-400/45 px-4 py-1.5 rounded-full">
Chạm chồng thẻ hoặc nhấn <strong class="text-amber-300">Bốc Thẻ</strong> để tự động xáo và rút bài!
</p>
</div>
<!-- Vùng 3D xếp 20 tấm thẻ -->
<div id="cardStage" style="min-height: 255px;" class="stage-3d relative w-full h-[255px] sm:h-[290px] flex items-center justify-center">
<div id="spotlightAura" class="spotlight-aura"></div>
<div id="deckContainer" style="min-height: 255px;" class="relative w-full h-full stage-3d"></div>
</div>
<!-- Thanh hành động sau khi lật thẻ -->
<div id="revealActions" class="hidden mt-3 flex flex-col items-center justify-center gap-2 z-30">
<div class="flex flex-wrap items-center justify-center gap-2.5">
<button id="btnCopyResult" type="button" class="btn-game px-4 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 border border-emerald-500/60 text-xs sm:text-sm font-bold text-emerald-300 flex items-center gap-1.5 shadow-lg">
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"/>
</svg>
Sao chép mã
</button>
<button id="btnContinue" type="button" class="btn-game px-5 py-2.5 rounded-xl bg-gradient-to-r from-emerald-400 to-teal-400 hover:brightness-110 text-xs sm:text-sm font-extrabold text-slate-950 shadow-lg">
Cất thẻ & Bốc tiếp ➔
</button>
</div>
<p id="lockedNoticeBadge" class="hidden text-[11px] sm:text-xs font-semibold text-amber-300 bg-amber-950/85 border border-amber-500/50 px-3.5 py-1.5 rounded-full text-center">
🔒 Máy này đã dùng lượt bốc duy nhất (1/1). Hãy sao chép mã gửi shop!
</p>
</div>
</main>
<!-- Khu vực 4 nút điều khiển chính -->
<footer class="w-full max-w-3xl mx-auto px-4 pb-6 pt-2 z-20">
<div class="grid grid-cols-2 sm:flex sm:flex-wrap items-center justify-center gap-2.5 sm:gap-3">
<!-- Nút 1: Xoay Thẻ -->
<button id="btnSpin" type="button" class="btn-game sm:min-w-[148px] px-4 py-3.5 rounded-2xl bg-gradient-to-b from-indigo-500 to-purple-700 hover:brightness-110 text-white font-extrabold text-sm sm:text-base shadow-[0_5px_0_#3b0764,0_10px_22px_rgba(126,34,206,0.45)] flex items-center justify-center gap-2">
<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
</svg>
<span>Xoay Thẻ</span>
</button>
<!-- Nút 2: Xáo & Bốc Thẻ -->
<button id="btnDraw" type="button" class="btn-game sm:min-w-[156px] px-4 py-3.5 rounded-2xl bg-gradient-to-b from-amber-300 via-amber-400 to-orange-500 hover:brightness-105 text-slate-950 font-black text-sm sm:text-base shadow-[0_5px_0_#9a3412,0_10px_22px_rgba(245,158,11,0.45)] flex items-center justify-center gap-2">
<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" stroke-width="2.6" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M7 11.5V14m0-2.5v-6a1.5 1.5 0 113 0m-3 6a1.5 1.5 0 00-3 0v2a7.5 7.5 0 0015 0v-5a1.5 1.5 0 00-3 0m-6-3V11m0-5.5v-1a1.5 1.5 0 013 0v1m0 0V11m0-5.5a1.5 1.5 0 013 0v3m0 0V11"/>
</svg>
<span>Bốc Thẻ</span>
</button>
<!-- Nút 3: Lật Thẻ -->
<button id="btnFlip" type="button" disabled class="btn-game sm:min-w-[148px] px-4 py-3.5 rounded-2xl bg-gradient-to-b from-rose-500 to-pink-600 hover:brightness-110 text-white font-extrabold text-sm sm:text-base shadow-[0_5px_0_#881337,0_10px_22px_rgba(244,63,94,0.4)] flex items-center justify-center gap-2">
<svg class="w-5 h-5 shrink-0" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
<path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
</svg>
<span>Lật Thẻ</span>
</button>
<!-- Nút 4: Làm mới (Yêu cầu mã PIN Chủ Shop khi khóa 1 máy/lần) -->
<button id="btnReset" type="button" class="btn-game sm:min-w-[122px] px-4 py-3.5 rounded-2xl bg-slate-800 hover:bg-slate-700 border border-slate-600 text-slate-100 font-bold text-sm sm:text-base shadow-[0_4px_0_#0f172a] flex items-center justify-center gap-1.5">
<svg class="w-4 h-4 shrink-0" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9"/>
</svg>
<span>Làm mới</span>
</button>
</div>
</footer>
<!-- Modal 1: Lịch sử bốc thẻ -->
<div id="modalHistory" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-sm p-4">
<div class="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-lg max-h-[84vh] flex flex-col shadow-2xl overflow-hidden">
<div class="p-4 border-b border-slate-800 flex items-center justify-between">
<div>
<h2 class="text-base font-extrabold text-white">📜 Lịch Sử Bốc Mã</h2>
<p class="text-xs text-slate-400">Danh sách mã thẻ đã được mở trong lượt này</p>
</div>
<button type="button" class="close-modal p-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300">✕</button>
</div>
<div id="historyList" class="p-4 overflow-y-auto flex-1 space-y-2.5 text-sm"></div>
<div class="p-3.5 border-t border-slate-800 flex items-center gap-2">
<button id="btnCopyAllHistory" type="button" class="flex-1 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs sm:text-sm font-bold transition">
Sao chép toàn bộ gửi nhóm
</button>
</div>
</div>
</div>
<!-- Modal 2: Quản trị Shop, chế độ 1 máy/1 lần & chỉnh sửa 20 mã thẻ -->
<div id="modalSettings" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-sm p-4">
<div class="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-lg max-h-[88vh] flex flex-col shadow-2xl overflow-hidden">
<div class="p-4 border-b border-slate-800 flex items-center justify-between">
<div>
<h2 class="text-base font-extrabold text-white">⚙️ Quản Trị & 20 Mã Thẻ</h2>
<p class="text-xs text-slate-400">Thiết lập khóa 1 lượt/máy & danh sách 20 mã bí mật</p>
</div>
<button type="button" class="close-modal p-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300">✕</button>
</div>
<div id="historyList" class="p-4 overflow-y-auto flex-1 space-y-2.5 text-sm"></div>
<div class="p-3.5 border-t border-slate-800 flex items-center gap-2">
<button id="btnCopyAllHistory" type="button" class="flex-1 py-2.5 rounded-xl bg-purple-600 hover:bg-purple-500 text-white text-xs sm:text-sm font-bold transition">
Sao chép toàn bộ gửi nhóm
</button>
</div>
</div>
</div>
<!-- Modal 2: Quản trị Shop, chế độ 1 máy/1 lần & chỉnh sửa 20 thẻ -->
<div id="modalSettings" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-sm p-4">
<div class="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-lg max-h-[88vh] flex flex-col shadow-2xl overflow-hidden">
<div class="p-4 border-b border-slate-800 flex items-center justify-between">
<div>
<h2 class="text-base font-extrabold text-white">⚙️ Quản Trị & 20 Tấm Thẻ</h2>
<p class="text-xs text-slate-400">Thiết lập khóa 1 lượt/máy & chỉnh sửa giải thưởng</p>
</div>
<button type="button" class="close-modal p-1.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300">✕</button>
</div>
<!-- Cài đặt chế độ 1 máy chỉ bốc 1 lần & Mã PIN Shop -->
<div class="px-4 pt-3 pb-3 bg-slate-950/70 border-b border-slate-800 space-y-2.5">
<label class="flex items-center justify-between gap-3 cursor-pointer p-2.5 rounded-2xl bg-slate-800/90 border border-slate-700">
<div>
<div class="text-xs sm:text-sm font-bold text-amber-300">🔒 Mỗi máy chỉ được bốc 1 lần</div>
<div class="text-[11px] text-slate-400">Khóa ngay khi bốc, tải lại trang vẫn giữ kết quả</div>
</div>
<input id="toggleSingleDraw" type="checkbox" checked class="w-5 h-5 accent-amber-400 cursor-pointer shrink-0">
</label>
<div class="flex flex-wrap items-center gap-2">
<div class="flex items-center gap-2 flex-1 min-w-[160px] bg-slate-800/90 border border-slate-700 rounded-xl px-3 py-2">
<span class="text-[11px] font-bold text-slate-300 whitespace-nowrap">Mã PIN Shop:</span>
<input id="inputAdminPin" type="text" maxlength="10" value="1234" class="w-full bg-transparent text-xs font-extrabold text-amber-300 outline-none" placeholder="1234">
</div>
<button id="btnUnlockThisDevice" type="button" class="px-3 py-2 rounded-xl bg-emerald-600/25 hover:bg-emerald-600/40 border border-emerald-500/40 text-emerald-300 text-xs font-bold transition">
🔓 Mở khóa máy này
</button>
</div>
</div>
<!-- Danh sách 20 thẻ tùy chỉnh -->
<div id="settingsList" class="p-4 overflow-y-auto flex-1 space-y-2.5"></div>
<div class="p-3.5 border-t border-slate-800 flex items-center justify-between gap-2">
<button id="btnDefaultPrizes" type="button" class="px-3.5 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold">
Khôi phục mặc định
</button>
<button id="btnSaveSettings" type="button" class="flex-1 py-2.5 rounded-xl bg-gradient-to-r from-amber-400 to-orange-500 text-slate-950 text-xs sm:text-sm font-extrabold shadow-lg">
Lưu & Xếp Lại 20 Thẻ
</button>
</div>
</div>
</div>
<!-- Modal 3: Nhập Mã PIN Quản Trị (chống khách tự bấm Làm mới để bốc lại) -->
<div id="modalAdminPin" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-sm p-4">
<div class="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-xs p-5 text-center shadow-2xl">
<div class="w-12 h-12 rounded-2xl bg-purple-500/20 text-purple-300 mx-auto flex items-center justify-center text-2xl mb-3">🔐</div>
<h3 class="text-base font-extrabold text-white mb-1">Xác Thực Chủ Shop</h3>
<p class="text-xs text-slate-400 mb-4">Nhập mã PIN quản trị (mặc định: <strong class="text-amber-300">1234</strong>) để mở cài đặt hoặc làm mới.</p>
<input
id="pinVerifyInput"
type="password"
inputmode="numeric"
maxlength="10"
placeholder="Nhập mã PIN..."
class="w-full text-center tracking-[0.25em] font-black text-base bg-slate-800 border border-slate-600 focus:border-amber-400 rounded-xl px-4 py-2.5 text-white outline-none mb-2"
>
<p id="pinErrorMsg" class="hidden text-xs font-bold text-rose-400 mb-3">Mã PIN không đúng, vui lòng thử lại!</p>
<div class="flex gap-2 mt-3">
<button type="button" class="close-modal flex-1 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-sm font-bold">Hủy</button>
<button id="btnVerifyPinConfirm" type="button" class="flex-1 py-2.5 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 text-sm font-extrabold">Xác nhận</button>
</div>
</div>
</div>
<!-- Modal 4: Xác nhận Làm mới 20 thẻ -->
<div id="modalConfirmReset" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/80 backdrop-blur-sm p-4">
<div class="bg-slate-900 border border-slate-700 rounded-3xl w-full max-w-sm p-5 text-center shadow-2xl">
<div class="w-12 h-12 rounded-2xl bg-amber-500/20 text-amber-400 mx-auto flex items-center justify-center text-2xl mb-3">🔄</div>
<h3 class="text-lg font-extrabold text-white mb-1">Xếp lại đủ 20 thẻ?</h3>
<p class="text-xs text-slate-400 mb-5">Mở khóa lượt bốc trên máy này, trộn lại đủ 20 thẻ và xóa lịch sử hiện tại.</p>
<div class="flex gap-2.5">
<button type="button" class="close-modal flex-1 py-2.5 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 text-sm font-bold">Hủy</button>
<button id="btnConfirmResetYes" type="button" class="flex-1 py-2.5 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 text-sm font-extrabold">Đồng ý</button>
</div>
</div>
</div>
<script>
/**
* ============================================================================
* 1. DANH SÁCH 20 MÃ THẺ BÍ MẬT (CHỈ HIỂN THỊ DÃY MÃ TRÊN THẺ)
* ============================================================================
*/
const STORAGE_CONFIG_KEY = 'steal_an_egg_card_config_v3';
const STORAGE_LOCK_KEY = 'steal_an_egg_device_lock_v3';
function getDefault20Codes() {
return [
'SAE-8K4M9',
'SAE-3P7W2',
'SAE-9X2N6',
'SAE-5H8R4',
'SAE-2V6T9',
'SAE-7D3J5',
'SAE-4G9L8',
'SAE-6Q2Z7',
'SAE-9B5C3',
'SAE-3M8F4',
'SAE-7W4Y2',
'SAE-2N9K6',
'SAE-8R3P5',
'SAE-5T7X9',
'SAE-4J6H2',
'SAE-9L2D8',
'SAE-6C8V3',
'SAE-3Z5G7',
'SAE-8F4Q9',
'SAE-2Y7B4'
];
}
/**
* ============================================================================
* 2. BIẾN TRẠNG THÁI & THAM CHIẾU DOM
* ============================================================================
*/
let cardCodePool = getDefault20Codes();
let appConfig = {
singleDrawMode: true,
adminPin: '1234'
};
let deviceLockState = null;
let pendingPinAction = null;
let deck = [];
let activeCard = null;
let appState = 'IDLE'; // 'IDLE' | 'SPINNING' | 'SHUFFLING' | 'DRAWN_UNFLIPPED' | 'REVEALED'
let drawnHistory = [];
let soundEnabled = true;
const deckContainer = document.getElementById('deckContainer');
const spotlightAura = document.getElementById('spotlightAura');
const stageHintEl = document.getElementById('stageHint');
const remainingCountEl = document.getElementById('remainingCount');
const historyBadgeEl = document.getElementById('historyBadge');
const deviceLimitBadgeEl = document.getElementById('deviceLimitBadge');
const statusTagEl = document.getElementById('statusTag');
const playerNameInput = document.getElementById('playerNameInput');
const revealActionsEl = document.getElementById('revealActions');
const btnContinue = document.getElementById('btnContinue');
const lockedNoticeBadgeEl = document.getElementById('lockedNoticeBadge');
const btnSpin = document.getElementById('btnSpin');
const btnDraw = document.getElementById('btnDraw');
const btnFlip = document.getElementById('btnFlip');
const btnReset = document.getElementById('btnReset');
const btnCopyResult = document.getElementById('btnCopyResult');
/**
* ============================================================================
* 3. LƯU TRỮ CẤU HÌNH & KHÓA 1 LƯỢT / MÁY (LOCALSTORAGE)
* ============================================================================
*/
function loadAppStorage() {
try {
const rawCfg = localStorage.getItem(STORAGE_CONFIG_KEY);
if (rawCfg) {
const parsed = JSON.parse(rawCfg);
if (Array.isArray(parsed.codes) && parsed.codes.length === 20) {
cardCodePool = parsed.codes;
}
if (typeof parsed.singleDrawMode === 'boolean') {
appConfig.singleDrawMode = parsed.singleDrawMode;
}
if (typeof parsed.adminPin === 'string' && parsed.adminPin.trim()) {
appConfig.adminPin = parsed.adminPin.trim();
}
}
} catch (e) {
cardCodePool = getDefault20Codes();
}
try {
const rawLock = localStorage.getItem(STORAGE_LOCK_KEY);
if (rawLock) {
const parsedLock = JSON.parse(rawLock);
if (parsedLock && parsedLock.locked && parsedLock.code) {
deviceLockState = parsedLock;
}
}
} catch (e) {
deviceLockState = null;
}
}
function saveConfigStorage() {
try {
localStorage.setItem(STORAGE_CONFIG_KEY, JSON.stringify({
codes: cardCodePool,
singleDrawMode: appConfig.singleDrawMode,
adminPin: appConfig.adminPin
}));
} catch (e) {
// Bỏ qua nếu trình duyệt chặn lưu trữ
}
}
function isDeviceLocked() {
return Boolean(appConfig.singleDrawMode && deviceLockState && deviceLockState.locked);
}
function saveDeviceLock(lockObj) {
deviceLockState = lockObj;
try {
localStorage.setItem(STORAGE_LOCK_KEY, JSON.stringify(lockObj));
} catch (e) {
// Bỏ qua lỗi quota
}
}
function clearDeviceLock() {
deviceLockState = null;
try {
localStorage.removeItem(STORAGE_LOCK_KEY);
} catch (e) {
// Bỏ qua lỗi
}
}
/**
* ============================================================================
* 4. ÂM THANH HIỆU ỨNG TONE.JS (KHÔNG CẦN TỆP NGOÀI)
* ============================================================================
*/
let audioReady = false;
let synth = null;
async function initAudio() {
if (!soundEnabled) return;
try {
if (typeof Tone !== 'undefined') {
if (Tone.context.state !== 'running') {
await Tone.start();
}
if (!synth) {
synth = new Tone.PolySynth(Tone.Synth, {
oscillator: { type: 'triangle' },
envelope: { attack: 0.01, decay: 0.14, sustain: 0.05, release: 0.25 }
}).toDestination();
synth.volume.value = -8;
}
audioReady = true;
}
} catch (err) {
audioReady = false;
}
}
function playSpinSound() {
if (!soundEnabled || !audioReady || !synth) return;
const notes = ['C4', 'E4', 'G4', 'B4', 'D5', 'G5'];
notes.forEach((n, idx) => {
synth.triggerAttackRelease(n, '32n', Tone.now() + idx * 0.075);
});
}
function playShuffleSound(cardCount) {
if (!soundEnabled || !audioReady || !synth) return;
const ticks = Math.min(cardCount, 12);
const scale = ['C4', 'D4', 'E4', 'G4', 'A4', 'C5'];
for (let i = 0; i < ticks; i++) {
const note = scale[i % scale.length];
synth.triggerAttackRelease(note, '64n', Tone.now() + 0.18 + i * 0.026);
}
}
function playDrawSound() {
if (!soundEnabled || !audioReady || !synth) return;
synth.triggerAttackRelease('E4', '16n', Tone.now());
synth.triggerAttackRelease('B4', '16n', Tone.now() + 0.09);
}
function playFlipSound() {
if (!soundEnabled || !audioReady || !synth) return;
const now = Tone.now();
['C5', 'E5', 'G5', 'B5'].forEach((n, i) => {
synth.triggerAttackRelease(n, '16n', now + i * 0.07);
});
}
/**
* ============================================================================
* 5. KHỞI TẠO & XẾP CHỒNG 20 TẤM THẺ (MẶT TRƯỚC CHỈ HIỆN MÃ)
* ============================================================================
*/
function shuffleArray(arr) {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
function buildCardElement(card, stackIndex) {
const el = document.createElement('div');
el.className = 'game-card';
el.dataset.cardId = card.id;
const labelNum = `#${String(stackIndex + 1).padStart(2, '0')}`;
el.innerHTML = `
<!-- Mặt sau (Úp) -->
<div class="card-face card-back card-back-pattern flex flex-col items-center justify-between p-3">
<div class="w-full flex items-center justify-between text-[10px] font-black tracking-wider text-purple-200">
<span class="card-badge-num px-1.5 py-0.5 rounded-md bg-purple-950/90 border border-purple-400/50 text-amber-300">${labelNum}</span>
<span class="text-amber-300">STEAL AN EGG</span>
</div>
<!-- Biểu tượng quả trứng bí ẩn SVG nét căng -->
<div class="my-auto flex flex-col items-center">
<div class="w-16 h-20 sm:w-20 sm:h-24 rounded-2xl bg-purple-950/75 border border-amber-300/40 flex items-center justify-center">
<svg class="w-12 h-14 sm:w-14 sm:h-16" viewBox="0 0 64 80" fill="none" shape-rendering="geometricPrecision">
<path d="M32 6C18 6 8 27 8 49C8 64.5 18.5 74 32 74C45.5 74 56 64.5 56 49C56 27 46 6 32 6Z" fill="#fde047" stroke="#ffffff" stroke-width="2.5"/>
<circle cx="23" cy="31" r="4.5" fill="#7e22ce"/>
<circle cx="41" cy="43" r="5.5" fill="#7e22ce"/>
<circle cx="26" cy="56" r="4" fill="#7e22ce"/>
<text x="32" y="45" text-anchor="middle" fill="#1e1b4b" font-size="18" font-weight="900">?</text>
</svg>
</div>
</div>
<div class="w-full text-center">
<div class="text-[10px] sm:text-[11px] font-extrabold tracking-wide text-amber-200 uppercase">Thẻ Trứng Bí Ẩn</div>
</div>
</div>
<!-- Mặt trước (Ngửa - Chỉ hiển thị duy nhất dãy mã, không có bất kỳ thông tin gì khác) -->
<div class="card-face card-front holo-sheen items-center justify-center p-2.5 text-center" style="background-color: #111827; background-image: linear-gradient(155deg, #1e1b4b 0%, #0f172a 55%, #090d16 100%); border-color: #fde047;">
<div class="w-full py-2.5 px-1.5 rounded-xl bg-black/50 border border-amber-400/50">
<span class="block text-base sm:text-lg font-black tracking-wider text-amber-300 font-mono select-all">
${escapeHTML(card.code)}
</span>
</div>
</div>
`;
el.addEventListener('click', () => handleCardClick(card));
return el;
}
function initDeck() {
deckContainer.innerHTML = '';
activeCard = null;
appState = 'IDLE';
revealActionsEl.classList.add('hidden');
spotlightAura.classList.remove('active');
const shuffledCodes = shuffleArray(cardCodePool);
deck = shuffledCodes.map((codeStr, idx) => {
const card = {
id: idx + 1,
code: codeStr,
jitterX: Math.round((Math.random() - 0.5) * 3),
jitterRot: Number(((Math.random() - 0.5) * 3.6).toFixed(1)),
el: null
};
const el = buildCardElement(card, idx);
card.el = el;
deckContainer.appendChild(el);
return card;
});
renderStackedDeck();
updateUI();
}
/**
* Xếp chồng 20 tấm thẻ lên nhau gọn gàng trên mặt phẳng Z=0 (tách bạch từng mép thẻ, không nhòe màu)
*/
function renderStackedDeck() {
const total = deck.length;
deck.forEach((card, idx) => {
const el = card.el;
if (!el) return;
const yOffset = Math.round((total - 1 - idx) * 1.4 - (total * 0.7));
const xOffset = Math.round(card.jitterX * 0.6 + (total - 1 - idx) * 0.35);
const rotZ = idx === total - 1 ? 0 : Number((card.jitterRot * 0.7).toFixed(1));
el.style.zIndex = 10 + idx;
el.style.opacity = '1';
el.classList.remove('drawn-waiting', 'is-drawn', 'top-card');
if (idx === total - 1) {
el.classList.add('top-card');
}
el.style.transform = `translate3d(${xOffset}px, ${yOffset}px, 0px) rotateZ(${rotZ}deg) rotateY(0deg) scale(1)`;
const backNum = el.querySelector('.card-badge-num');
const labelNum = `#${String(idx + 1).padStart(2, '0')}`;
if (backNum) backNum.textContent = labelNum;
});
}
/**
* Nếu chế độ 1 máy / 1 lần đang bật và máy này đã bốc trước đó, khôi phục đúng mã thẻ đã bốc
*/
function restoreLockedCardIfNeeded() {
if (!isDeviceLocked()) return;
const saved = deviceLockState;
const matchIdx = deck.findIndex(c => c.code === saved.code);
const removed = deck.splice(matchIdx >= 0 ? matchIdx : deck.length - 1, 1)[0];
if (removed && removed.el && removed.el.parentNode) {
removed.el.parentNode.removeChild(removed.el);
}
activeCard = {
id: 999,
code: saved.code,
jitterX: 0,
jitterRot: 0,
el: null
};
const el = buildCardElement(activeCard, 19);
deckContainer.appendChild(el);
activeCard.el = el;
if (saved.player) {
playerNameInput.value = saved.player;
}
const isMobile = window.innerWidth < 640;
const sideShift = isMobile ? -92 : -122;
deck.forEach((card, idx) => {
const yOffset = Math.round((deck.length - 1 - idx) * 1.2 - (deck.length * 0.6));
card.el.style.transition = 'none';
card.el.style.opacity = '0.28';
card.el.style.transform = `translate3d(${sideShift}px, ${yOffset + 8}px, 0px) rotateZ(${card.jitterRot - 6}deg) scale(0.82)`;
});
el.style.zIndex = 100;
el.style.transition = 'none';
el.classList.add('is-drawn');
spotlightAura.classList.add('active');
if (saved.flipped) {
appState = 'REVEALED';
el.style.transform = 'translate3d(0px, -6px, 0px) rotateZ(0deg) rotateY(180deg) scale(1)';
revealActionsEl.classList.remove('hidden');
drawnHistory = [{
player: saved.player || 'Khách #1',
code: saved.code,
time: saved.time || ''
}];
} else {
appState = 'DRAWN_UNFLIPPED';
el.style.transform = 'translate3d(0px, -4px, 0px) rotateZ(0deg) rotateY(0deg) scale(1)';
el.classList.add('drawn-waiting');
}
updateUI();
}
/**
* ============================================================================
* 6. HIỆU ỨNG XOAY THẺ, XÁO THẺ TRƯỚC KHI BỐC, BỐC THẺ & LẬT THẺ
* ============================================================================
*/
async function spinAndShuffleDeck() {
if (appState !== 'IDLE') return;
if (isDeviceLocked()) {
showToast('Máy này đã sử dụng lượt bốc duy nhất (1/1)!', 'error');
return;
}
if (deck.length < 2) {
showToast('Cần ít nhất 2 thẻ để xoay trộn!', 'info');
return;
}
await initAudio();
appState = 'SPINNING';
updateUI();
playSpinSound();
const count = deck.length;
const isMobile = window.innerWidth < 640;
const radiusX = isMobile ? 86 : 134;
const radiusY = isMobile ? 42 : 58;
// Bung vòng tròn 3D
deck.forEach((card, idx) => {
const angle = (idx / count) * Math.PI * 2;
const x = Math.round(Math.cos(angle) * radiusX);
const y = Math.round(Math.sin(angle) * radiusY);
const deg = Math.round((angle * 180) / Math.PI + 90);
card.el.style.transition = 'transform 0.46s cubic-bezier(0.34, 1.56, 0.64, 1)';
card.el.style.zIndex = 20 + idx;
card.el.style.transform = `translate3d(${x}px, ${y}px, 0px) rotateZ(${deg}deg) rotateY(16deg) scale(0.86)`;
});
await wait(440);
// Xoay tròn toàn bộ vòng thẻ
deck.forEach((card, idx) => {
const angle = ((idx / count) * Math.PI * 2) + Math.PI * 1.35;
const x = Math.round(Math.cos(angle) * (radiusX * 0.92));
const y = Math.round(Math.sin(angle) * (radiusY * 0.92));
const deg = Math.round((angle * 180) / Math.PI + 450);
card.el.style.transition = 'transform 0.6s cubic-bezier(0.45, 0, 0.55, 1)';
card.el.style.transform = `translate3d(${x}px, ${y}px, 0px) rotateZ(${deg}deg) rotateY(-16deg) scale(0.9)`;
});
await wait(560);
// Trộn ngẫu nhiên mảng thực và gom lại thành chồng
deck = shuffleArray(deck);
deck.forEach(card => {
card.jitterX = Math.round((Math.random() - 0.5) * 3);
card.jitterRot = Number(((Math.random() - 0.5) * 3.6).toFixed(1));
card.el.style.transition = 'transform 0.52s cubic-bezier(0.22, 1, 0.36, 1)';
});
renderStackedDeck();
await wait(500);
appState = 'IDLE';
updateUI();
showToast(`Đã xoay & trộn ngẫu nhiên ${deck.length} tấm thẻ!`, 'success');
}
/**
* Hiệu ứng xáo thẻ (tách 2 nửa Trái - Phải rồi đan xen) chạy tự động ngay trước khi bốc
*/
async function riffleShuffleBeforeDraw() {
appState = 'SHUFFLING';
updateUI();
playShuffleSound(deck.length);
const total = deck.length;
const mid = Math.ceil(total / 2);
const isMobile = window.innerWidth < 640;
const splitDist = isMobile ? 64 : 84;
// Bước 1: Tách chồng bài làm đôi
deck.forEach((card, idx) => {
const isLeft = idx < mid;
const localIdx = isLeft ? idx : idx - mid;
const x = isLeft ? -splitDist : splitDist;
const y = Math.round((mid - localIdx) * 1.3 - 6);
const rot = isLeft ? -10 : 10;
card.el.style.transitionDelay = '0ms';
card.el.style.transition = 'transform 0.24s cubic-bezier(0.22, 1, 0.36, 1)';
card.el.style.transform = `translate3d(${x}px, ${y}px, 0px) rotateZ(${rot}deg) rotateY(${isLeft ? 8 : -8}deg) scale(1)`;
});
await wait(230);
// Bước 2: Đan xen từng lá từ 2 nửa bay về giữa
const interleaved = [];
for (let i = 0; i < mid; i++) {
if (deck[i]) interleaved.push(deck[i]);
if (mid + i < total && deck[mid + i]) interleaved.push(deck[mid + i]);
}
interleaved.forEach((card, idx) => {
const yOffset = Math.round((total - 1 - idx) * 1.4 - (total * 0.7));
const delay = idx * 17;
card.el.style.zIndex = 20 + idx;
card.el.style.transition = 'transform 0.23s cubic-bezier(0.34, 1.35, 0.64, 1)';
card.el.style.transitionDelay = `${delay}ms`;
card.el.style.transform = `translate3d(${Math.round((Math.random() - 0.5) * 4)}px, ${yOffset - 3}px, 0px) rotateZ(${Number(((Math.random() - 0.5) * 3.5).toFixed(1))}deg) rotateY(0deg) scale(1)`;
});
await wait(220 + total * 17);
// Bước 3: Xáo trộn thực trong mảng & xếp ngay ngắn
deck = shuffleArray(deck);
deck.forEach(card => {
card.jitterX = Math.round((Math.random() - 0.5) * 3);
card.jitterRot = Number(((Math.random() - 0.5) * 3.6).toFixed(1));
card.el.style.transitionDelay = '0ms';
card.el.style.transition = 'transform 0.16s ease-out';
});
renderStackedDeck();
await wait(160);
}
async function drawTopCard() {
if (appState !== 'IDLE') return;
if (isDeviceLocked()) {
showToast('Mỗi máy chỉ được phép bốc 1 lần duy nhất!', 'error');
return;
}
if (deck.length === 0) {
showToast('Đã bốc hết 20 thẻ! Hãy bấm "Làm mới" để bắt đầu lượt mới.', 'info');
return;
}
await initAudio();
// Tự động xáo thẻ trước khi bốc
if (deck.length >= 2) {
await riffleShuffleBeforeDraw();
}
playDrawSound();
activeCard = deck.pop();
appState = 'DRAWN_UNFLIPPED';
// Khóa lượt ngay lập tức nếu chế độ 1 máy 1 lần đang bật (chống tải lại trang bốc lại)
const playerName = playerNameInput.value.trim();
const nowStr = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
if (appConfig.singleDrawMode) {
saveDeviceLock({
locked: true,
flipped: false,
player: playerName || 'Khách #1',
time: nowStr,
code: activeCard.code
});
}
const isMobile = window.innerWidth < 640;
const sideShift = isMobile ? -92 : -122;
// Đẩy chồng thẻ nền lùi sang trái
deck.forEach((card, idx) => {
const yOffset = Math.round((deck.length - 1 - idx) * 1.2 - (deck.length * 0.6));
card.el.style.transition = 'transform 0.48s ease, opacity 0.38s ease';
card.el.style.opacity = '0.28';
card.el.style.transform = `translate3d(${sideShift}px, ${yOffset + 8}px, 0px) rotateZ(${card.jitterRot - 6}deg) scale(0.82)`;
});
// Đưa thẻ vừa bốc ra chính giữa tại Z=0, scale=1 -> sắc nét 100%
const el = activeCard.el;
el.style.zIndex = 100;
el.style.transition = 'transform 0.56s cubic-bezier(0.175, 0.885, 0.32, 1.2)';
el.style.transform = 'translate3d(0px, -4px, 0px) rotateZ(0deg) rotateY(0deg) scale(1)';
el.classList.add('drawn-waiting', 'is-drawn');
spotlightAura.classList.add('active');
updateUI();
}
async function flipActiveCard() {
if (appState !== 'DRAWN_UNFLIPPED' || !activeCard) return;
await initAudio();
appState = 'REVEALED';
const el = activeCard.el;
el.classList.remove('drawn-waiting');
el.style.transition = 'transform 0.7s cubic-bezier(0.22, 1, 0.36, 1)';
el.style.transform = 'translate3d(0px, -6px, 0px) rotateZ(0deg) rotateY(180deg) scale(1)';
playFlipSound();
launchConfetti(85);
const playerName = playerNameInput.value.trim() || `Khách #${drawnHistory.length + 1}`;
const nowStr = new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
drawnHistory.unshift({
player: playerName,
code: activeCard.code,
time: nowStr
});
if (appConfig.singleDrawMode) {
saveDeviceLock({
locked: true,
flipped: true,
player: playerName,
time: nowStr,
code: activeCard.code
});
}
revealActionsEl.classList.remove('hidden');
updateUI();
}
async function dismissRevealedCard() {
if (appState !== 'REVEALED' || !activeCard) return;
const el = activeCard.el;
el.style.transition = 'transform 0.42s ease-in, opacity 0.36s ease';
el.style.transform = 'translate3d(220px, -70px, 0px) rotateZ(22deg) rotateY(180deg) scale(0.55)';
el.style.opacity = '0';
revealActionsEl.classList.add('hidden');
spotlightAura.classList.remove('active');
await wait(360);
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
activeCard = null;
appState = 'IDLE';
playerNameInput.value = '';
deck.forEach(card => {
card.el.style.transition = 'transform 0.48s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.35s ease';
});
renderStackedDeck();
updateUI();
}
function handleCardClick(card) {
if (appState === 'IDLE') {
if (isDeviceLocked()) {
showToast('Mỗi máy chỉ được phép bốc 1 lần duy nhất!', 'error');
return;
}
drawTopCard();
} else if (appState === 'DRAWN_UNFLIPPED' && activeCard && activeCard.id === card.id) {
flipActiveCard();
} else if (appState === 'REVEALED' && activeCard && activeCard.id === card.id) {
copyToClipboard(activeCard.code);
}
}
/**
* ============================================================================
* 7. CẬP NHẬT GIAO DIỆN & TRẠNG THÁI NÚT (CHỈ HIỂN THỊ MÃ)
* ============================================================================
*/
function updateUI() {
const locked = isDeviceLocked();
remainingCountEl.textContent = `${deck.length} / ${cardCodePool.length}`;
historyBadgeEl.textContent = drawnHistory.length;
if (!appConfig.singleDrawMode) {
deviceLimitBadgeEl.textContent = '♾️ Bốc nhiều lần';
deviceLimitBadgeEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-sky-500/20 text-sky-300 border border-sky-500/40';
} else if (locked) {
deviceLimitBadgeEl.textContent = '🔒 Đã dùng (0/1 lượt)';
deviceLimitBadgeEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40';
} else {
deviceLimitBadgeEl.textContent = '🔒 1 lượt/máy (Còn 1)';
deviceLimitBadgeEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40';
}
playerNameInput.disabled = locked && appState === 'REVEALED';
btnSpin.disabled = appState !== 'IDLE' || deck.length < 2 || locked;
btnDraw.disabled = appState !== 'IDLE' || deck.length === 0 || locked;
btnFlip.disabled = appState !== 'DRAWN_UNFLIPPED';
btnReset.disabled = appState === 'SPINNING' || appState === 'SHUFFLING';
if (appState === 'REVEALED') {
if (appConfig.singleDrawMode) {
btnContinue.classList.add('hidden');
lockedNoticeBadgeEl.classList.remove('hidden');
} else {
btnContinue.classList.remove('hidden');
lockedNoticeBadgeEl.classList.add('hidden');
}
} else {
lockedNoticeBadgeEl.classList.add('hidden');
}
if (appState === 'SPINNING') {
statusTagEl.textContent = 'Đang xoay trộn...';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-purple-500/25 text-purple-200 border border-purple-400/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-amber-300 font-bold animate-pulse">✨ Đang xoay vòng & xáo trộn ${deck.length} tấm thẻ...</p>`;
} else if (appState === 'SHUFFLING') {
statusTagEl.textContent = 'Đang xáo thẻ...';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-sky-500/25 text-sky-200 border border-sky-400/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-sky-300 font-bold animate-pulse">🃏 Đang xáo đều ${deck.length} tấm thẻ trước khi bốc...</p>`;
} else if (appState === 'DRAWN_UNFLIPPED') {
statusTagEl.textContent = 'Chờ lật thẻ';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-amber-500/25 text-amber-300 border border-amber-400/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-amber-200 font-bold bg-amber-950/85 border border-amber-400/50 px-4 py-1.5 rounded-full animate-bounce">👆 Chạm trực tiếp vào thẻ hoặc nhấn "Lật Thẻ" để mở mã!</p>`;
} else if (appState === 'REVEALED') {
statusTagEl.textContent = 'Đã mở mã';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-500/25 text-emerald-300 border border-emerald-400/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-emerald-300 font-extrabold">🎉 Mã của bạn: <span class="font-mono text-amber-300">${escapeHTML(activeCard.code)}</span></p>`;
} else {
if (deck.length === 0) {
statusTagEl.textContent = 'Hết thẻ';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-rose-500/20 text-rose-300 border border-rose-500/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-rose-200 font-bold bg-rose-950/70 border border-rose-500/40 px-4 py-1.5 rounded-full">Đã bốc hết 20 thẻ! Nhấn "Làm mới" để xếp lại bộ thẻ mới.</p>`;
} else {
statusTagEl.textContent = 'Sẵn sàng';
statusTagEl.className = 'px-2.5 py-1 rounded-full text-[11px] font-bold bg-indigo-500/25 text-indigo-200 border border-indigo-400/40';
stageHintEl.innerHTML = `<p class="text-xs sm:text-sm text-purple-100 font-semibold bg-purple-950/85 border border-purple-400/45 px-4 py-1.5 rounded-full">Chạm chồng thẻ hoặc nhấn <strong class="text-amber-300">Bốc Thẻ</strong> để tự động xáo và rút bài!</p>`;
}
}
}
/**
* ============================================================================
* 8. PHÁO HOA CANVAS ĐÁP ỨNG MỌI KÍCH THƯỚC MÀN HÌNH
* ============================================================================
*/
const confettiCanvas = document.getElementById('confettiCanvas');
const ctx = confettiCanvas.getContext('2d');
let particles = [];
let confettiRunning = false;
function resizeConfettiCanvas() {
confettiCanvas.width = window.innerWidth;
confettiCanvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeConfettiCanvas);
resizeConfettiCanvas();
function launchConfetti(amount) {
const colors = ['#fde047', '#f59e0b', '#ffffff', '#c084fc', '#38bdf8'];
const cx = confettiCanvas.width / 2;
const cy = confettiCanvas.height / 2;
for (let i = 0; i < amount; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = 4 + Math.random() * 11;
particles.push({
x: cx,
y: cy,
vx: Math.cos(angle) * speed,
vy: Math.sin(angle) * speed - 4,
size: 5 + Math.random() * 6,
color: colors[Math.floor(Math.random() * colors.length)],
rot: Math.random() * 360,
vRot: (Math.random() - 0.5) * 14,
alpha: 1,
decay: 0.012 + Math.random() * 0.012
});
}
if (!confettiRunning) {
confettiRunning = true;
requestAnimationFrame(animateConfetti);
}
}
function animateConfetti() {
ctx.clearRect(0, 0, confettiCanvas.width, confettiCanvas.height);
particles = particles.filter(p => p.alpha > 0.02);
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
p.vy += 0.24;
p.vx *= 0.985;
p.rot += p.vRot;
p.alpha -= p.decay;
ctx.save();
ctx.globalAlpha = Math.max(0, p.alpha);
ctx.translate(p.x, p.y);
ctx.rotate((p.rot * Math.PI) / 180);
ctx.fillStyle = p.color;
ctx.fillRect(-p.size / 2, -p.size / 4, p.size, p.size / 2);
ctx.restore();
});
if (particles.length > 0) {
requestAnimationFrame(animateConfetti);
} else {
confettiRunning = false;
}
}
/**
* ============================================================================
* 9. TIỆN ÍCH CHUNG: CLIPBOARD, TOAST, ESCAPE HTML & MODAL
* ============================================================================
*/
function copyToClipboard(text) {
try {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
showToast('Đã sao chép kết quả! Bạn có thể dán gửi vào nhóm ngay.', 'success');
} catch (err) {
showToast('Không thể tự sao chép, vui lòng chụp màn hình nhé.', 'error');
}
}
function showToast(message, type = 'info') {
const container = document.getElementById('toastContainer');
const toast = document.createElement('div');
const bgMap = {
success: 'bg-emerald-950/95 border-emerald-500/60 text-emerald-200',
error: 'bg-rose-950/95 border-rose-500/60 text-rose-200',
info: 'bg-slate-900/95 border-purple-500/60 text-purple-100'
};
toast.className = `px-4 py-2.5 rounded-2xl border backdrop-blur-md text-xs sm:text-sm font-semibold shadow-2xl text-center transition-all duration-300 transform -translate-y-2 opacity-0 ${bgMap[type] || bgMap.info}`;
toast.textContent = message;
container.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.remove('-translate-y-2', 'opacity-0');
});
setTimeout(() => {
toast.classList.add('opacity-0', '-translate-y-2');
setTimeout(() => toast.remove(), 300);
}, 2600);
}
function escapeHTML(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Quản lý các cửa sổ Modal
const modalHistory = document.getElementById('modalHistory');
const modalSettings = document.getElementById('modalSettings');
const modalConfirmReset = document.getElementById('modalConfirmReset');
const modalAdminPin = document.getElementById('modalAdminPin');
const pinVerifyInput = document.getElementById('pinVerifyInput');
const pinErrorMsg = document.getElementById('pinErrorMsg');
function openModal(modal) {
modal.classList.remove('hidden');
modal.classList.add('flex');
}
function closeAllModals() {
[modalHistory, modalSettings, modalConfirmReset, modalAdminPin].forEach(m => {
m.classList.add('hidden');
m.classList.remove('flex');
});
pendingPinAction = null;
}
function requireAdminPin(onVerified) {
if (!appConfig.singleDrawMode) {
onVerified();
return;
}
pendingPinAction = onVerified;
pinVerifyInput.value = '';
pinErrorMsg.classList.add('hidden');
openModal(modalAdminPin);
setTimeout(() => pinVerifyInput.focus(), 100);
}
function handleVerifyPin() {
const entered = pinVerifyInput.value.trim();
if (entered === appConfig.adminPin) {
const action = pendingPinAction;
closeAllModals();
if (typeof action === 'function') action();
} else {
pinErrorMsg.classList.remove('hidden');
pinVerifyInput.select();
}
}
document.getElementById('btnVerifyPinConfirm').addEventListener('click', handleVerifyPin);
pinVerifyInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') handleVerifyPin();
});
document.querySelectorAll('.close-modal').forEach(btn => {
btn.addEventListener('click', closeAllModals);
});
[modalHistory, modalSettings, modalConfirmReset, modalAdminPin].forEach(modal => {
modal.addEventListener('click', (e) => {
if (e.target === modal) closeAllModals();
});
});
// Modal Lịch sử (chỉ hiển thị tên người bốc & mã)
document.getElementById('btnHistory').addEventListener('click', () => {
const listEl = document.getElementById('historyList');
if (drawnHistory.length === 0) {
listEl.innerHTML = `<p class="text-center text-slate-400 py-8">Chưa có thẻ nào được bốc.</p>`;
} else {
listEl.innerHTML = drawnHistory.map((item, idx) => `
<div class="p-3 rounded-2xl bg-slate-800/85 border border-slate-700 flex items-center justify-between gap-2">
<div class="min-w-0">
<div class="flex items-center gap-1.5">
<span class="text-xs font-bold text-slate-400">#${drawnHistory.length - idx}</span>
<span class="font-bold text-white truncate">${escapeHTML(item.player)}</span>
</div>
<div class="text-[11px] text-slate-400 mt-0.5">${item.time}</div>
</div>
<span class="px-3 py-1 rounded-xl bg-slate-950 border border-amber-400/50 text-xs sm:text-sm font-black font-mono text-amber-300 shrink-0">
${escapeHTML(item.code)}
</span>
</div>
`).join('');
}
openModal(modalHistory);
});
document.getElementById('btnCopyAllHistory').addEventListener('click', () => {
if (drawnHistory.length === 0) {
showToast('Chưa có lịch sử để sao chép!', 'info');
return;
}
const lines = drawnHistory.slice().reverse().map((item, i) => {
return `${i + 1}. ${item.player}: ${item.code}`;
});
const text = `🥚 DANH SÁCH MÃ BỐC THẺ STEAL AN EGG 🥚\n` + lines.join('\n');
copyToClipboard(text);
});
// Modal Cài đặt 20 mã thẻ & chế độ 1 lượt/máy
function renderSettingsEditor() {
document.getElementById('toggleSingleDraw').checked = appConfig.singleDrawMode;
document.getElementById('inputAdminPin').value = appConfig.adminPin;
const container = document.getElementById('settingsList');
container.innerHTML = cardCodePool.map((codeStr, i) => `
<div class="p-2.5 rounded-2xl bg-slate-800/80 border border-slate-700 flex items-center gap-2.5">
<span class="text-xs font-extrabold text-purple-300 w-9 shrink-0 text-center">#${i + 1}</span>
<input type="text" data-idx="${i}" value="${escapeHTML(codeStr)}" placeholder="Nhập mã thẻ..." class="setting-code-input w-full bg-slate-900 border border-slate-600 focus:border-amber-400 rounded-xl px-3 py-2 text-xs sm:text-sm font-black font-mono text-amber-300 outline-none">
</div>
`).join('');
}
document.getElementById('btnSettings').addEventListener('click', () => {
requireAdminPin(() => {
renderSettingsEditor();
openModal(modalSettings);
});
});
document.getElementById('btnUnlockThisDevice').addEventListener('click', () => {
clearDeviceLock();
drawnHistory = [];
initDeck();
closeAllModals();
showToast('Đã mở khóa lượt bốc trên máy này!', 'success');
});
document.getElementById('btnDefaultPrizes').addEventListener('click', () => {
cardCodePool = getDefault20Codes();
renderSettingsEditor();
showToast('Đã khôi phục 20 mã mặc định!', 'info');
});
document.getElementById('btnSaveSettings').addEventListener('click', () => {
const inputs = document.querySelectorAll('.setting-code-input');
const updated = [...cardCodePool];
inputs.forEach(inp => {
const idx = Number(inp.dataset.idx);
updated[idx] = inp.value.trim() || `SAE-CODE${idx + 1}`;
});
cardCodePool = updated;
const newPin = document.getElementById('inputAdminPin').value.trim();
appConfig.singleDrawMode = document.getElementById('toggleSingleDraw').checked;
appConfig.adminPin = newPin || '1234';
saveConfigStorage();
clearDeviceLock();
drawnHistory = [];
initDeck();
closeAllModals();
showToast('Đã lưu 20 mã & xếp lại bộ thẻ!', 'success');
});
/**
* ============================================================================
* 10. GÁN SỰ KIỆN CHO CÁC NÚT ĐIỀU KHIỂN CHÍNH & KHỞI CHẠY NGAY
* ============================================================================
*/
btnSpin.addEventListener('click', spinAndShuffleDeck);
btnDraw.addEventListener('click', drawTopCard);
btnFlip.addEventListener('click', flipActiveCard);
btnContinue.addEventListener('click', dismissRevealedCard);
btnCopyResult.addEventListener('click', () => {
if (!activeCard) return;
const player = playerNameInput.value.trim();
const msg = player ? `${player} - Mã thẻ: ${activeCard.code}` : activeCard.code;
copyToClipboard(msg);
});
btnReset.addEventListener('click', () => {
requireAdminPin(() => {
openModal(modalConfirmReset);
});
});
document.getElementById('btnConfirmResetYes').addEventListener('click', () => {
clearDeviceLock();
drawnHistory = [];
initDeck();
closeAllModals();
showToast('Đã mở khóa & xếp lại đủ 20 tấm thẻ mới!', 'success');
});
document.getElementById('btnSound').addEventListener('click', async () => {
soundEnabled = !soundEnabled;
document.getElementById('iconSoundOn').classList.toggle('hidden', !soundEnabled);
document.getElementById('iconSoundOff').classList.toggle('hidden', soundEnabled);
if (soundEnabled) {
await initAudio();
showToast('Đã bật âm thanh hiệu ứng', 'info');
} else {
showToast('Đã tắt âm thanh', 'info');
}
});
// Khởi chạy ứng dụng an toàn ngay khi tải xong DOM
function bootApp() {
resizeConfettiCanvas();
loadAppStorage();
initDeck();
restoreLockedCardIfNeeded();
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', bootApp);
} else {
bootApp();
}
</script>
</body>
</html>