<style>
/* ================= TryGames — Dashboard content v5 (violet/teal palette) ================= */
:root{
  --bg:#0A0D1A;
  --surface:#131A2E;
  --surface-2:#1B2440;
  --surface-3:#232E52;
  --teal-500:#00E6D8;
  --teal-600:#00C2A8;
  --violet-500:#8B5CF6;
  --violet-600:#7C3AED;
  --gold:#FFC23C;
  --danger:#FF5A5A;
  --grad-primary: linear-gradient(135deg, var(--violet-500), var(--violet-600));
  --grad-gold: linear-gradient(135deg, var(--gold) 0%, #FF7A3C 100%);
  --mint:#00E6D8;
  --text:#F3F5FC;
  --text-dim:#8891AC;
  --line: rgba(255,255,255,.08);
  --radius-lg:26px;
  --radius-md:18px;
  --radius-sm:12px;
  --font-display:'Bebas Neue', sans-serif;
  --font-body:'Inter', system-ui, sans-serif;
  --font-mono:'JetBrains Mono', monospace;

  --sp-page: clamp(14px, 3vw, 28px);
  --sp-section: clamp(22px, 4vw, 38px);
  --fs-h2: clamp(18px, 2.2vw, 23px);

  /* ---- Loot-rarity tiers, driven by each item's own reward value ---- */
  --rare-common:#8891AC;
  --rare-common-glow: rgba(136,145,172,.35);
  --rare-rare:#3CA0FF;
  --rare-rare-glow: rgba(60,160,255,.45);
  --rare-epic:#B266FF;
  --rare-epic-glow: rgba(178,102,255,.5);
  --rare-legendary:#FFC23C;
  --rare-legendary-glow: rgba(255,194,60,.55);
}

*{box-sizing:border-box;}
.eg-wrap{
  position:relative;
  max-width:1320px;width:100%;margin:0 auto;color:var(--text);
  font-family:var(--font-body);padding:var(--sp-page) var(--sp-page) 0;
}
.eg-wrap img{max-width:100%;display:block;}
.eg-wrap a{-webkit-tap-highlight-color:transparent;}
.eg-wrap :focus-visible{outline:2px solid var(--mint);outline-offset:2px;border-radius:8px;}
@media (prefers-reduced-motion: reduce){
  .eg-wrap *{animation-duration:.001ms !important;animation-iteration-count:1 !important;transition-duration:.001ms !important;}
}

/* ---------- Ambient floating coin/orb particles (decorative, non-interactive) ---------- */
.eg-particles{position:absolute;inset:0;top:0;height:640px;overflow:hidden;pointer-events:none;z-index:0;opacity:.55;}
.eg-particle{
  position:absolute;border-radius:50%;
  background:radial-gradient(circle at 35% 30%, rgba(255,255,255,.9), rgba(255,194,60,.15) 60%, transparent 72%);
  filter:blur(.2px);
  animation:eg-particle-float linear infinite;
}
.eg-particle.teal{background:radial-gradient(circle at 35% 30%, rgba(255,255,255,.85), rgba(0,230,216,.18) 60%, transparent 72%);}
.eg-particle.violet{background:radial-gradient(circle at 35% 30%, rgba(255,255,255,.85), rgba(139,92,246,.2) 60%, transparent 72%);}
@keyframes eg-particle-float{
  0%{transform:translateY(0) translateX(0) rotate(0deg);opacity:0;}
  8%{opacity:1;}
  92%{opacity:1;}
  100%{transform:translateY(-560px) translateX(var(--drift,24px)) rotate(180deg);opacity:0;}
}
@media (max-width:767px){.eg-particles{display:none;}}
@media (prefers-reduced-motion: reduce){.eg-particles{display:none;}}

/* ---------- Live ticker (top strip) ---------- */
.eg-ticker{
  position:relative;overflow:hidden;border-radius:16px;border:1px solid var(--line);
  background:rgba(19,26,46,.55);backdrop-filter:blur(10px);
  margin-bottom:var(--sp-section);
  -webkit-mask-image:linear-gradient(90deg, transparent 0, #000 28px, #000 calc(100% - 28px), transparent 100%);
  mask-image:linear-gradient(90deg, transparent 0, #000 28px, #000 calc(100% - 28px), transparent 100%);
}
.eg-ticker-track{
  display:flex;gap:10px;padding:9px;width:max-content;
  animation:eg-ticker-scroll 42s linear infinite;
}
.eg-ticker:hover .eg-ticker-track{animation-play-state:paused;}
@keyframes eg-ticker-scroll{
  from{transform:translateX(0);}
  to{transform:translateX(-50%);}
}
.eg-ticker-card{
  flex:0 0 auto;display:flex;align-items:center;gap:9px;
  background:var(--surface);border:1px solid var(--line);border-radius:12px;
  padding:7px 12px 7px 7px;min-width:222px;
}
.eg-ticker-avatar{
  width:32px;height:32px;border-radius:9px;object-fit:cover;flex-shrink:0;background:var(--surface-2);
}
.eg-ticker-body{min-width:0;flex:1;}
.eg-ticker-name{font-size:12px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-ticker-sub{font-size:10.5px;color:var(--text-dim);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-ticker-amt{
  flex-shrink:0;font-family:var(--font-mono);font-weight:800;font-size:12.5px;color:var(--mint);
  display:flex;align-items:center;gap:5px;
}
.eg-ticker-amt::before{
  content:"";width:6px;height:6px;border-radius:50%;background:var(--mint);
  box-shadow:0 0 0 0 rgba(0,230,216,.6);
  animation:eg-live-dot 1.8s ease-in-out infinite;
}
@keyframes eg-live-dot{
  0%{box-shadow:0 0 0 0 rgba(0,230,216,.5);}
  70%{box-shadow:0 0 0 6px rgba(0,230,216,0);}
  100%{box-shadow:0 0 0 0 rgba(0,230,216,0);}
}

/* ---------- Section titles ---------- */
.eg-section-head{
  display:flex;align-items:flex-end;justify-content:space-between;gap:12px;margin-bottom:14px;
}
.eg-section-title{
  font-family:var(--font-display);font-size:var(--fs-h2);letter-spacing:.03em;
  margin:0 0 4px;display:flex;align-items:center;gap:8px;
}
.eg-section-title .bolt{color:var(--mint);}
.eg-section-sub{font-size:12.5px;color:var(--text-dim);margin:0;}
.eg-section-view-all{
  flex-shrink:0;font-size:12.5px;font-weight:700;color:var(--violet-500);text-decoration:none;white-space:nowrap;
  padding-bottom:2px;
}
.eg-section-view-all:hover{color:var(--text);text-decoration:underline;}

/* =========================================================
   HUD STATS STRIP — level / streak / today's earnings / rank
   at a glance, right under the ticker. Pure visual + a couple
   of data hooks (js-hud-*) other scripts can update.
   ========================================================= */
.eg-hud{
  display:grid;grid-template-columns:repeat(4,1fr);gap:12px;
  margin-bottom:var(--sp-section);
}
.eg-hud-card{
  position:relative;overflow:hidden;
  background:var(--surface);border:1px solid var(--line);border-radius:18px;
  padding:13px 14px;display:flex;align-items:center;gap:11px;
}
.eg-hud-card::before{
  content:"";position:absolute;inset:0;opacity:.5;pointer-events:none;
  background:radial-gradient(120px 60px at 0% 0%, var(--hud-tint, rgba(139,92,246,.18)), transparent 70%);
}
.eg-hud-icon{
  position:relative;z-index:1;flex-shrink:0;width:38px;height:38px;border-radius:12px;
  display:flex;align-items:center;justify-content:center;font-size:16px;color:#fff;
  background:var(--hud-grad, var(--grad-primary));box-shadow:0 8px 18px -8px var(--hud-glow, rgba(139,92,246,.55));
}
.eg-hud-body{position:relative;z-index:1;min-width:0;}
.eg-hud-label{font-size:10.5px;color:var(--text-dim);font-weight:700;letter-spacing:.03em;text-transform:uppercase;margin-bottom:2px;}
.eg-hud-value{font-family:var(--font-mono);font-weight:800;font-size:16px;line-height:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-hud-card.streak{--hud-grad:var(--grad-gold);--hud-glow:rgba(255,138,60,.5);--hud-tint:rgba(255,194,60,.16);}
.eg-hud-card.today{--hud-grad:linear-gradient(135deg,#22E3A5,#12986B);--hud-glow:rgba(34,227,165,.5);--hud-tint:rgba(34,227,165,.14);}
.eg-hud-card.rank{--hud-grad:linear-gradient(135deg,#3CA0FF,#2361C4);--hud-glow:rgba(60,160,255,.5);--hud-tint:rgba(60,160,255,.14);}

@media (max-width:767px){
  .eg-hud{grid-template-columns:repeat(2,1fr);}
}

/* =========================================================
   DAILY QUESTS
   ========================================================= */
.eg-quests{
  display:grid;grid-template-columns:repeat(3,1fr);gap:14px;
  margin-bottom:var(--sp-section);
}
.eg-quest-card{
  position:relative;overflow:hidden;
  background:linear-gradient(155deg, var(--surface-2) 0%, var(--surface) 55%);
  border:1px solid var(--line);border-radius:18px 18px 18px 6px;
  padding:15px 15px 13px 17px;display:flex;flex-direction:column;gap:12px;
  transition:border-color .25s ease, transform .25s ease, box-shadow .25s ease;
}
.eg-quest-card::before{
  content:"";position:absolute;left:0;top:0;bottom:0;width:4px;background:var(--quest-accent, var(--violet-500));
  box-shadow:0 0 12px var(--quest-accent-glow, rgba(139,92,246,.6));
}
.eg-quest-card[data-difficulty="easy"]{--quest-accent:var(--teal-500);--quest-accent-glow:rgba(0,230,216,.55);}
.eg-quest-card[data-difficulty="medium"]{--quest-accent:var(--violet-500);--quest-accent-glow:rgba(139,92,246,.55);}
.eg-quest-card[data-difficulty="hard"]{--quest-accent:var(--gold);--quest-accent-glow:rgba(255,194,60,.55);}
.eg-quest-card:hover{transform:translateY(-2px);border-color:rgba(255,255,255,.16);}
.eg-quest-card.is-done{
  border-color:rgba(34,227,165,.4);
  box-shadow:0 14px 30px -16px rgba(34,227,165,.45);
}
.eg-quest-diff-tag{
  position:absolute;top:12px;right:13px;z-index:1;
  font-family:var(--font-mono);font-size:8.5px;font-weight:800;letter-spacing:.07em;text-transform:uppercase;
  color:var(--quest-accent, var(--text-dim));opacity:.85;
}
.eg-quest-top{display:flex;align-items:center;gap:12px;}
.eg-quest-ring{
  position:relative;flex-shrink:0;width:46px;height:46px;border-radius:50%;
  background:conic-gradient(var(--quest-accent, var(--violet-500)) calc(var(--pct,0) * 1%), rgba(255,255,255,.08) 0);
  display:flex;align-items:center;justify-content:center;
  transition:background 1s ease;
}
.eg-quest-ring::before{
  content:"";position:absolute;inset:3px;border-radius:50%;background:var(--surface);
}
.eg-quest-icon{
  position:relative;z-index:1;width:100%;height:100%;display:flex;align-items:center;justify-content:center;
  color:var(--quest-accent, var(--mint));font-size:15px;
}
.eg-quest-card.is-done .eg-quest-ring{background:conic-gradient(#22E3A5 100%, rgba(255,255,255,.08) 0);}
.eg-quest-card.is-done .eg-quest-icon{color:#22E3A5;}
.eg-quest-title{font-size:13px;font-weight:700;margin-bottom:2px;line-height:1.25;}
.eg-quest-reward{
  display:inline-flex;align-items:center;gap:4px;
  font-family:var(--font-mono);font-size:10.5px;color:#2B1600;font-weight:800;
  background:var(--grad-gold);padding:2px 8px 2px 6px;border-radius:999px;
  box-shadow:0 4px 10px -4px rgba(255,138,60,.5);
}
.eg-quest-reward i{font-size:9px;}
.eg-quest-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;}
.eg-quest-pct{font-family:var(--font-mono);font-size:11px;color:var(--text-dim);font-weight:700;}
.eg-quest-claim{
  border:none;cursor:pointer;font-family:var(--font-mono);font-weight:800;font-size:10.5px;letter-spacing:.03em;
  padding:7px 14px;border-radius:10px;color:#0A0D1A;background:var(--grad-gold);
  box-shadow:0 6px 14px -5px rgba(255,138,60,.55);transition:transform .15s ease, opacity .15s ease, box-shadow .15s ease;
}
.eg-quest-claim:hover{transform:translateY(-1px);box-shadow:0 9px 18px -6px rgba(255,138,60,.65);}
.eg-quest-claim:disabled{opacity:.4;cursor:not-allowed;box-shadow:none;background:var(--surface-3);color:var(--text-dim);}
.eg-quest-card.is-done .eg-quest-claim{background:linear-gradient(135deg,#22E3A5,#12986B);color:#fff;box-shadow:0 6px 14px -5px rgba(34,227,165,.5);}
@media (max-width:767px){
  .eg-quests-wrap{display:none;}
}

/* =========================================================
   FEATURED TASKS (Top Games)
   ========================================================= */
.eg-task-grid{
  display:grid;grid-template-columns:repeat(auto-fill, minmax(148px,1fr));gap:14px;
  margin-bottom:var(--sp-section);
}
.eg-task-card{
  position:relative;display:block;text-decoration:none;color:var(--text);
  background:var(--surface);border:1px solid var(--line);border-radius:20px;
  padding:12px;transition:border-color .32s ease, box-shadow .32s ease, transform .32s ease;
  overflow:hidden;cursor:pointer;
}
.eg-task-card:hover, .eg-task-card:focus-visible{
  border-color:rgba(139,92,246,.5);
  box-shadow:0 10px 26px -8px rgba(139,92,246,.6);
  transform:translateY(-3px);
}
.eg-task-card::after{
  content:"";position:absolute;inset:0;z-index:1;pointer-events:none;
  background:linear-gradient(115deg, transparent 40%, rgba(255,255,255,.16) 50%, transparent 60%);
  background-size:220% 220%;background-position:120% 0;
  transition:background-position .55s ease;
}
.eg-task-card:hover::after{background-position:-20% 0;}
.eg-task-card[data-rarity]{border-top:2px solid var(--rare-tier, var(--line));}
.eg-task-card[data-rarity="common"]{--rare-tier:var(--rare-common);}
.eg-task-card[data-rarity="rare"]{--rare-tier:var(--rare-rare);}
.eg-task-card[data-rarity="epic"]{--rare-tier:var(--rare-epic);}
.eg-task-card[data-rarity="legendary"]{
  --rare-tier:var(--rare-legendary);
  box-shadow:0 0 0 1px rgba(255,194,60,.22), 0 12px 28px -10px var(--rare-legendary-glow);
  animation:eg-legendary-breathe 3.6s ease-in-out infinite;
}
@keyframes eg-legendary-breathe{
  0%,100%{box-shadow:0 0 0 1px rgba(255,194,60,.18), 0 12px 24px -10px rgba(255,194,60,.35);}
  50%{box-shadow:0 0 0 1px rgba(255,194,60,.4), 0 16px 34px -8px rgba(255,194,60,.65);}
}
.eg-rarity-tag{
  position:absolute;bottom:7px;right:7px;z-index:2;
  font-family:var(--font-mono);font-size:8.5px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;
  padding:2px 6px;border-radius:6px;color:#0A0D1A;background:var(--rare-tier, var(--text-dim));
  opacity:.92;
}
.eg-task-icon-wrap{position:relative;border-radius:14px;overflow:hidden;aspect-ratio:1/1;margin-bottom:10px;background:var(--surface-2);}
.eg-task-icon-wrap img{width:100%;height:100%;object-fit:cover;transition:transform .4s ease;}
.eg-task-card:hover .eg-task-icon-wrap img{transform:scale(1.06);}
.eg-task-badge{
  position:absolute;top:7px;left:7px;z-index:2;
  font-family:var(--font-mono);font-weight:800;font-size:10px;letter-spacing:.02em;
  padding:3px 7px;border-radius:7px;color:#fff;
  background:linear-gradient(135deg,#22E3A5,#12986B);box-shadow:0 5px 12px -3px rgba(34,227,165,.5);
}
.eg-task-store{
  position:absolute;top:7px;right:7px;z-index:2;width:22px;height:22px;border-radius:50%;
  background:rgba(10,13,26,.65);display:flex;align-items:center;justify-content:center;
  color:#fff;font-size:11px;border:1px solid rgba(255,255,255,.14);
}
.eg-task-name{font-size:13px;font-weight:700;margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-task-sub{font-size:11px;color:var(--text-dim);margin-bottom:9px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-task-price-row{display:flex;align-items:baseline;gap:7px;}
.eg-task-price{font-family:var(--font-mono);font-weight:800;font-size:14px;color:var(--mint);}
.eg-task-price-old{font-family:var(--font-mono);font-weight:600;font-size:11.5px;color:var(--text-dim);text-decoration:line-through;}

/* =========================================================
   OFFER WALLS
   ========================================================= */
.eg-wall-grid{
  display:grid;grid-template-columns:repeat(auto-fill, minmax(148px,1fr));
  grid-auto-rows:1fr;gap:14px;
  margin-bottom:var(--sp-section);
}
.eg-wall-card{
  position:relative;display:flex;flex-direction:column;text-decoration:none;color:var(--text);
  background:var(--surface);border:1px solid var(--line);
  border-radius:20px 20px 20px 20px;
  clip-path:polygon(0 0, calc(100% - 22px) 0, 100% 22px, 100% 100%, 0 100%);
  overflow:hidden;height:100%;
  transition:border-color .3s ease, box-shadow .3s ease, transform .3s ease;
}
.eg-wall-card::after{
  content:"";position:absolute;top:0;right:0;width:0;height:0;
  border-style:solid;border-width:0 22px 22px 0;border-color:transparent var(--wall-tier, var(--surface-3)) transparent transparent;
  opacity:.9;z-index:2;pointer-events:none;
}
.eg-wall-card:hover, .eg-wall-card:focus-visible{
  border-color:rgba(139,92,246,.55);
  box-shadow:0 12px 28px -8px rgba(139,92,246,.55);
  transform:translateY(-3px);
}
.eg-wall-card[data-tier="bronze"]{--wall-tier:#B08D57;}
.eg-wall-card[data-tier="silver"]{--wall-tier:#B9C2D0;}
.eg-wall-card[data-tier="gold"]{--wall-tier:var(--gold);}
.eg-wall-card[data-tier="diamond"]{--wall-tier:var(--mint);}
.eg-wall-tier-tag{
  position:absolute;top:6px;left:8px;z-index:3;
  font-family:var(--font-mono);font-size:8px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;
  padding:2px 6px;border-radius:6px;color:#0A0D1A;background:var(--wall-tier, var(--text-dim));opacity:.95;
}
.eg-wall-card.is-hot{
  border-color:rgba(255,194,60,.4);
  animation:eg-wall-hot-breathe 3.4s ease-in-out infinite;
}
@keyframes eg-wall-hot-breathe{
  0%,100%{box-shadow:0 0 0 1px rgba(255,194,60,.16), 0 10px 22px -10px rgba(255,194,60,.32);}
  50%{box-shadow:0 0 0 1px rgba(255,194,60,.38), 0 16px 32px -8px rgba(255,194,60,.6);}
}
.eg-wall-card.is-hot:hover{border-color:rgba(255,194,60,.8);}
.eg-wall-logo-area{
  position:relative;flex:1;overflow:hidden;min-height:104px;
  background:
    radial-gradient(90px 70px at 30% 20%, rgba(255,255,255,.06), transparent 70%),
    linear-gradient(160deg, rgba(27,36,64,.5) 0%, rgba(19,26,46,.6) 100%), url('/img/offfaaaback.png');
  background-size:cover;background-position:center;
  display:flex;align-items:center;justify-content:center;padding:18px;
}
.eg-wall-logo-area img{
  position:relative;z-index:2;
  max-width:100%;max-height:100%;object-fit:contain;
  filter:drop-shadow(0 1px 3px rgba(0,0,0,.6));
  transition:transform .35s ease;
}
.eg-wall-card:hover .eg-wall-logo-area img{transform:scale(1.08);}
.eg-wall-bonus{
  position:absolute;bottom:8px;right:8px;z-index:2;
  font-family:var(--font-mono);font-weight:800;font-size:10px;letter-spacing:.02em;
  padding:4px 9px;border-radius:999px;color:#2b1600;
  background:var(--grad-gold);box-shadow:0 5px 12px -3px rgba(255,138,60,.45);
  display:flex;align-items:center;gap:3px;
}
.eg-wall-bonus .flame{font-size:9px;}
.eg-wall-footer{
  padding:9px 10px;border-top:1px solid var(--line);flex-shrink:0;
  background:linear-gradient(180deg, #192B5C 0%, #101A38 100%) !important;
  display:flex;align-items:center;justify-content:center;gap:6px;
}
.eg-wall-name{
  display:block;text-align:center;font-size:12.5px;font-weight:700;letter-spacing:.01em;
  color:var(--text) !important;
  white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
}
.eg-wall-footer .eg-wall-go{
  flex-shrink:0;width:16px;height:16px;border-radius:50%;background:var(--surface-3);
  display:flex;align-items:center;justify-content:center;color:var(--text-dim);font-size:8px;
  transition:background .2s ease, color .2s ease, transform .2s ease;
}
.eg-wall-card:hover .eg-wall-go{background:var(--grad-primary);color:#fff;transform:translateX(2px);}
@media (max-width:380px){
  .eg-wall-grid{grid-template-columns:repeat(auto-fill, minmax(130px,1fr));}
}
@media (max-width:767px){
  .eg-task-grid{
    display:flex;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden;
    gap:12px;margin:0 calc(var(--sp-page) * -1) var(--sp-section);
    padding:2px var(--sp-page) 10px;
    scroll-snap-type:x proximity;-webkit-overflow-scrolling:touch;
    scrollbar-width:none;
  }
  .eg-task-grid::-webkit-scrollbar{display:none;}
  .eg-task-card{flex:0 0 auto;width:148px;scroll-snap-align:start;}
}
@media (max-width:420px){
  .eg-section-head{flex-wrap:wrap;}
}

/* =========================================================
   GAME DETAIL MODAL — v5: gallery, steps, tags, rating,
   countdown, share, related games, focus trap, drag-to-close.
   ========================================================= */
.eg-modal-overlay{
  position:fixed;inset:0;z-index:2147483100;   /* was 999 */
  background:rgba(6,8,16,.72);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);
  display:flex;align-items:center;justify-content:center;
  padding:20px;
  opacity:0;visibility:hidden;pointer-events:none;
  transition:opacity .25s ease, visibility 0s linear .25s;
}
.eg-modal-overlay.is-open{opacity:1;visibility:visible;pointer-events:auto;transition:opacity .25s ease;}

.eg-modal{
  position:relative;width:100%;max-width:500px;max-height:90vh;overflow-y:auto;
  background:linear-gradient(165deg, var(--surface-2) 0%, var(--surface) 60%);
  border:1px solid var(--line);border-radius:24px;
  box-shadow:0 30px 80px -20px rgba(0,0,0,.6), 0 0 0 1px var(--modal-tier-glow, rgba(139,92,246,.25));
  transform:scale(.9) translateY(16px);opacity:0;
  transition:transform .32s cubic-bezier(.2,.9,.3,1.2), opacity .28s ease;
}
.eg-modal-overlay.is-open .eg-modal{transform:scale(1) translateY(0);opacity:1;}
.eg-modal[data-rarity="common"]{--modal-tier-glow:var(--rare-common-glow);--modal-tier:var(--rare-common);}
.eg-modal[data-rarity="rare"]{--modal-tier-glow:var(--rare-rare-glow);--modal-tier:var(--rare-rare);}
.eg-modal[data-rarity="epic"]{--modal-tier-glow:var(--rare-epic-glow);--modal-tier:var(--rare-epic);}
.eg-modal[data-rarity="legendary"]{--modal-tier-glow:var(--rare-legendary-glow);--modal-tier:var(--rare-legendary);}

.eg-modal-drag{display:none;}
@media (max-width:640px){
  .eg-modal-drag{display:flex;justify-content:center;padding:9px 0 2px;touch-action:none;cursor:grab;}
  .eg-modal-drag span{width:36px;height:4px;border-radius:999px;background:rgba(255,255,255,.25);}
}

.eg-modal-close{
  position:absolute;top:12px;right:12px;z-index:5;
  width:32px;height:32px;border-radius:50%;border:1px solid rgba(255,255,255,.14);
  background:rgba(10,13,26,.55);color:var(--text);display:flex;align-items:center;justify-content:center;
  cursor:pointer;font-size:13px;transition:background .2s ease,transform .2s ease;
}
.eg-modal-close:hover{background:rgba(255,255,255,.14);transform:rotate(90deg);}

.eg-modal-hero{position:relative;aspect-ratio:16/10;overflow:hidden;border-radius:24px 24px 0 0;background:var(--surface-2);}
.eg-modal-hero img{width:100%;height:100%;object-fit:cover;opacity:1;transition:opacity .25s ease;}
.eg-modal-hero.is-loading img{opacity:0;}
.eg-modal-hero.is-loading::before{
  content:"";position:absolute;inset:0;
  background:linear-gradient(100deg, var(--surface-2) 30%, var(--surface-3) 50%, var(--surface-2) 70%);
  background-size:200% 100%;animation:eg-shimmer 1.1s ease-in-out infinite;
}
@keyframes eg-shimmer{0%{background-position:120% 0;}100%{background-position:-20% 0;}}
.eg-modal-hero::after{
  content:"";position:absolute;inset:0;background:linear-gradient(180deg, transparent 40%, rgba(10,13,26,.92) 100%);
}
.eg-modal-hero-badges{position:absolute;top:12px;left:12px;z-index:2;display:flex;gap:6px;flex-wrap:wrap;}
.eg-modal-hero-badge{
  font-family:var(--font-mono);font-weight:800;font-size:10px;letter-spacing:.02em;
  padding:4px 9px;border-radius:8px;color:#fff;
  background:linear-gradient(135deg,#22E3A5,#12986B);box-shadow:0 5px 12px -3px rgba(34,227,165,.5);
}

.eg-modal-sparkles{position:absolute;inset:0;pointer-events:none;overflow:hidden;z-index:3;}
.eg-modal-sparkle{
  position:absolute;width:5px;height:5px;border-radius:50%;
  background:var(--modal-tier, var(--gold));opacity:0;
  animation:eg-sparkle-burst .9s ease-out forwards;
}
@keyframes eg-sparkle-burst{
  0%{opacity:1;transform:translate(0,0) scale(1);}
  100%{opacity:0;transform:translate(var(--sx,0),var(--sy,-40px)) scale(.2);}
}

/* ---- thumbnail gallery, sits right under the hero ---- */
.eg-modal-thumbs{display:flex;gap:8px;padding:10px 20px 0;overflow-x:auto;scrollbar-width:none;}
.eg-modal-thumbs::-webkit-scrollbar{display:none;}
.eg-modal-thumb{
  flex-shrink:0;width:54px;height:54px;border-radius:10px;overflow:hidden;
  border:2px solid transparent;cursor:pointer;padding:0;background:none;opacity:.6;
  transition:opacity .2s ease, border-color .2s ease;
}
.eg-modal-thumb img{width:100%;height:100%;object-fit:cover;}
.eg-modal-thumb.active{opacity:1;border-color:var(--modal-tier, var(--violet-500));}
.eg-modal-thumb:hover{opacity:1;}

.eg-modal-body{padding:16px 20px 22px;position:relative;}

.eg-modal-top-row{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;flex-wrap:wrap;}
.eg-modal-rarity{
  display:inline-flex;align-items:center;gap:5px;
  font-family:var(--font-mono);font-size:10px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;
  color:#0A0D1A;background:var(--modal-tier, var(--text-dim));padding:3px 9px;border-radius:999px;
}
.eg-modal-rating{display:inline-flex;align-items:center;gap:4px;font-family:var(--font-mono);font-size:11.5px;font-weight:800;color:var(--gold);}
.eg-modal-rating i{font-size:11px;}

.eg-modal-countdown{
  display:inline-flex;gap:6px;align-items:center;font-family:var(--font-mono);font-size:11px;font-weight:800;
  color:#fff;background:rgba(255,90,90,.16);border:1px solid rgba(255,90,90,.4);
  padding:4px 10px;border-radius:999px;margin-bottom:10px;
}
.eg-modal-countdown i{color:var(--danger);}

.eg-modal-title{font-family:var(--font-display);font-size:clamp(20px,5vw,26px);letter-spacing:.02em;margin:0 0 8px;}
.eg-modal-desc{font-size:13.5px;line-height:1.55;color:var(--text-dim);margin:0 0 12px;}

.eg-modal-tags{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 16px;}
.eg-tag-chip{
  font-size:10.5px;font-weight:700;padding:3px 9px;border-radius:999px;
  background:var(--surface-3);color:var(--text-dim);border:1px solid var(--line);
}

.eg-modal-stats{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:18px;}
.eg-modal-stat{flex:1;min-width:100px;background:var(--surface-3);border:1px solid var(--line);border-radius:14px;padding:10px 12px;}
.eg-modal-stat-label{font-size:9.5px;color:var(--text-dim);text-transform:uppercase;letter-spacing:.05em;font-weight:700;margin-bottom:3px;}
.eg-modal-stat-value{font-family:var(--font-mono);font-weight:800;font-size:15px;color:var(--mint);}
.eg-modal-stat-value.old{color:var(--text-dim);text-decoration:line-through;font-size:12px;font-weight:600;}

/* ---- step-by-step "how to earn" checklist ---- */
.eg-modal-steps-title{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.05em;color:var(--text-dim);margin-bottom:10px;}
.eg-modal-steps{list-style:none;margin:0 0 18px;padding:0;display:flex;flex-direction:column;gap:9px;}
.eg-modal-step{display:flex;gap:10px;align-items:flex-start;font-size:12.5px;color:var(--text-dim);line-height:1.4;}
.eg-modal-step-num{
  flex-shrink:0;width:20px;height:20px;margin-top:.5px;border-radius:50%;
  background:var(--modal-tier, var(--violet-500));color:#0A0D1A;
  font-family:var(--font-mono);font-weight:800;font-size:10px;
  display:flex;align-items:center;justify-content:center;
}

.eg-modal-actions{display:flex;gap:10px;}
.eg-modal-cta{
  flex:1;text-align:center;text-decoration:none;border:none;cursor:pointer;
  font-family:var(--font-mono);font-weight:800;font-size:13px;letter-spacing:.02em;
  padding:13px 16px;border-radius:14px;color:#0A0D1A;background:var(--grad-gold);
  box-shadow:0 10px 22px -8px rgba(255,138,60,.55);transition:transform .15s ease, box-shadow .15s ease;
}
.eg-modal-cta:hover{transform:translateY(-2px);box-shadow:0 14px 28px -8px rgba(255,138,60,.65);}
.eg-modal-secondary{
  flex-shrink:0;border:1px solid var(--line);background:transparent;color:var(--text);
  font-family:var(--font-mono);font-weight:700;font-size:12.5px;padding:13px 16px;border-radius:14px;cursor:pointer;
  transition:background .2s ease,border-color .2s ease;
}
.eg-modal-secondary:hover{background:rgba(255,255,255,.06);border-color:rgba(255,255,255,.2);}
.eg-modal-share{
  width:46px;flex-shrink:0;border:1px solid var(--line);background:transparent;color:var(--text);
  border-radius:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;
  transition:background .2s ease,border-color .2s ease,color .2s ease;
}
.eg-modal-share:hover{background:rgba(255,255,255,.06);}
.eg-modal-share.is-copied{color:#22E3A5;border-color:rgba(34,227,165,.5);}

/* ---- related games strip ---- */
.eg-modal-related{margin-top:20px;padding-top:16px;border-top:1px solid var(--line);}
.eg-modal-related-title{font-size:11px;font-weight:800;text-transform:uppercase;letter-spacing:.05em;color:var(--text-dim);margin-bottom:10px;}
.eg-modal-related-grid{display:flex;gap:10px;overflow-x:auto;scrollbar-width:none;}
.eg-modal-related-grid::-webkit-scrollbar{display:none;}
.eg-modal-related-card{
  flex:0 0 auto;width:92px;cursor:pointer;border:none;background:none;text-align:left;padding:0;color:var(--text);
}
.eg-modal-related-card img{width:92px;height:92px;border-radius:12px;object-fit:cover;margin-bottom:6px;}
.eg-modal-related-name{font-size:10.5px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.eg-modal-related-price{font-size:10px;color:var(--mint);font-family:var(--font-mono);font-weight:800;}

body.eg-modal-lock{overflow:hidden;}

@media (max-width:640px){
  .eg-modal-overlay{padding:0;align-items:flex-end;}
  .eg-modal{max-width:100%;max-height:92vh;border-radius:24px 24px 0 0;transform:translateY(100%);}
  .eg-modal-overlay.is-open .eg-modal{transform:translateY(0);}
  .eg-modal-actions{flex-wrap:wrap;}
  .eg-modal-secondary{flex:1;}
}
</style>

<div class="eg-wrap">

    <div class="eg-particles" aria-hidden="true">
        <?php
        $particleSeed = [
            ['left' => '4%',  'size' => 5,  'dur' => '13s', 'delay' => '0s',   'drift' => '18px', 'cls' => ''],
            ['left' => '14%', 'size' => 3,  'dur' => '17s', 'delay' => '2.4s', 'drift' => '-14px', 'cls' => 'teal'],
            ['left' => '27%', 'size' => 6,  'dur' => '15s', 'delay' => '5s',   'drift' => '10px', 'cls' => 'violet'],
            ['left' => '41%', 'size' => 4,  'dur' => '19s', 'delay' => '1s',   'drift' => '-22px', 'cls' => ''],
            ['left' => '58%', 'size' => 5,  'dur' => '14s', 'delay' => '3.6s', 'drift' => '16px', 'cls' => 'teal'],
            ['left' => '69%', 'size' => 3,  'dur' => '18s', 'delay' => '6.2s', 'drift' => '-10px', 'cls' => 'violet'],
            ['left' => '81%', 'size' => 6,  'dur' => '16s', 'delay' => '0.8s', 'drift' => '20px', 'cls' => ''],
            ['left' => '92%', 'size' => 4,  'dur' => '20s', 'delay' => '4.4s', 'drift' => '-16px', 'cls' => 'teal'],
        ];
        foreach ($particleSeed as $p) {
            $style = "left:{$p['left']};width:{$p['size']}px;height:{$p['size']}px;"
                   . "bottom:0;animation-duration:{$p['dur']};animation-delay:{$p['delay']};--drift:{$p['drift']};";
            echo '<span class="eg-particle ' . $p['cls'] . '" style="' . $style . '"></span>';
        }
        ?>
    </div>

    <?php
    // FIX: every key below is now root-relative (leading "/") to match the
    // '/img/logo.png' fallback used everywhere this map is read. Previously
    // 'lootably' and 'TryGames Special offers' were relative paths
    // ("img/..." with no leading slash), which resolve against the current
    // page's URL rather than the site root and 404 on any nested route.
    //
    // FIX: added an 'adcend' key (matching the slug used in the $offers
    // array below) — the old map only had 'TryGames Special offers', which
    // never matched that slug, so Adcendmedia's logo silently fell back to
    // the default placeholder.
    $offerwallLogos = [
        'lootably' => '/img/lootablyapp.png',
        'adcend'   => '/img/logo.png',
        'gemiad'   => 'https://gemiad.s3.eu-central-1.amazonaws.com/logos/Asset_7.png',
        // 'klinck'      => '/img/klogo.svg',
        // 'avixolabs'   => '/img/aviiiadad.png',
        // 'grock'       => '/img/gdLogo.png',
        // 'typlayedd'   => '/img/tp.png',
        // 'adtowallda'  => '/img/adto-removebg-preview.png',
        // 'playtime'    => '/img/logo_wsdasde.png',
        // 'zadfly'      => '/img/OfferwallFrameLogo1.png',
        // 'notik'       => '/img/logo_main.jpg',
        // 'pubscale'    => '/img/pubsaaw.png',
        // 'vortexwall'  => '/img/Screenshot_3.png',
        // 'upwall'      => '/img/upwall.png',
        // 'taskwall'    => '/img/taskwall.png',
        // 'offeryas'    => '/img/logoo.png',
        // 'clickwall'   => '/img/clickwall.png',
        // 'flextoo'     => '/img/flex.jpeg',
    ];
    ?>

    <!-- ===================== LIVE TICKER ===================== -->
    <div class="eg-ticker">
        <?php
        $tickerItems = [];
        $tickerRows  = [];

        if (isset($this->db)) {
            $tickerResult = $this->db
                ->where('status', 2)
                ->order_by('claim_time', 'DESC')
                ->limit(20)
                ->get('offerwall_history');

            if ($tickerResult) {
                $tickerRows = $tickerResult->result();
            }
        }

        foreach ($tickerRows as $row) {
            $wall = strtolower(trim($row->offerwall));
            $name = trim($row->offername) !== '' ? $row->offername : ucfirst($wall);
            $sub  = $wall !== '' ? ucfirst($wall) : 'Offerwall';
            $img  = isset($offerwallLogos[$wall]) ? $offerwallLogos[$wall] : '/img/logo.png';
            $amt  = number_format((float) $row->amount, 2);

            $tickerItems[] = [$name, $sub, $img, $amt];
        }

        if (empty($tickerItems)) {
            $tickerItems = [
                ['Welcome Bonus', 'TryGames', '/img/logo.png', '0.50'],
            ];
        }

        echo '<div class="eg-ticker-track">';
        for ($loop = 0; $loop < 2; $loop++) {
            foreach ($tickerItems as $t) {
                [$name, $sub, $img, $amt] = $t;
                echo '<div class="eg-ticker-card">'
                   . '<img src="' . $img . '" alt="" class="eg-ticker-avatar">'
                   . '<div class="eg-ticker-body">'
                   . '<div class="eg-ticker-name">' . htmlspecialchars($name) . '</div>'
                   . '<div class="eg-ticker-sub">' . htmlspecialchars($sub) . '</div>'
                   . '</div>'
                   . '<div class="eg-ticker-amt">$' . $amt . '</div>'
                   . '</div>';
            }
        }
        echo '</div>';
        ?>
    </div>

    <!-- ===================== HUD STATS STRIP ===================== -->
    <?php
        $hudLevel   = isset($user['level']) ? (int) $user['level'] : 0;
        $hudStreak  = isset($user['streak']) ? (int) $user['streak'] : 0;
        $hudToday   = isset($user['today_earned']) ? number_format((float) $user['today_earned'], 2) : '0.00';
        $hudRankMap = [0 => 'Bronze', 10 => 'Silver', 25 => 'Gold', 50 => 'Platinum', 75 => 'Diamond'];
        $hudRank = 'Bronze';
        foreach ($hudRankMap as $minLvl => $rankName) { if ($hudLevel >= $minLvl) { $hudRank = $rankName; } }
    ?>
    <div class="eg-hud">
        <div class="eg-hud-card level">
            <span class="eg-hud-icon"><i class="fas fa-star"></i></span>
            <div class="eg-hud-body">
                <div class="eg-hud-label">Level</div>
                <div class="eg-hud-value js-hud-level"><?= $hudLevel ?></div>
            </div>
        </div>
        <div class="eg-hud-card streak">
            <span class="eg-hud-icon"><i class="fas fa-fire"></i></span>
            <div class="eg-hud-body">
                <div class="eg-hud-label">Streak</div>
                <div class="eg-hud-value js-hud-streak"><?= $hudStreak ?> day<?= $hudStreak === 1 ? '' : 's' ?></div>
            </div>
        </div>
        <div class="eg-hud-card today">
            <span class="eg-hud-icon"><i class="fas fa-coins"></i></span>
            <div class="eg-hud-body">
                <div class="eg-hud-label">Today</div>
                <div class="eg-hud-value js-hud-today">$<?= $hudToday ?></div>
            </div>
        </div>
        <div class="eg-hud-card rank">
            <span class="eg-hud-icon"><i class="fas fa-shield-alt"></i></span>
            <div class="eg-hud-body">
                <div class="eg-hud-label">Rank</div>
                <div class="eg-hud-value js-hud-rank"><?= $hudRank ?></div>
            </div>
        </div>
    </div>

    <!-- ===================== DAILY QUESTS ===================== -->
    <div class="eg-quests-wrap">
    <div class="eg-section-head">
        <div>
            <div class="eg-section-title"><span class="bolt">🗡️</span> Daily Quests</div>
            <p class="eg-section-sub">Complete quests for bonus coins on top of your normal rewards</p>
        </div>
    </div>
    <div class="eg-quests">
        <?php
        $quests = [
            ['login',    'fa-door-open',   'Log in today for more than 1 hour',            '+$0.50', 100, false,  'easy'],
            ['complete', 'fa-check-double','Complete 3 tasks',        '+$0.50', 66,  false, 'medium'],
            ['spend',    'fa-clock',       'Spend 10 min on an offer','+$0.25', 30,  false, 'hard'],
        ];
        foreach ($quests as $q) {
            [$qid, $icon, $title, $reward, $progress, $done, $difficulty] = $q;
            $cardClass = 'eg-quest-card' . ($done ? ' is-done' : '');
            echo '<div class="' . $cardClass . '" data-quest="' . $qid . '" data-difficulty="' . $difficulty . '">'
               . '<span class="eg-quest-diff-tag">' . ucfirst($difficulty) . '</span>'
               . '<div class="eg-quest-top">'
               . '<span class="eg-quest-ring" style="--pct:' . $progress . ';"><span class="eg-quest-icon"><i class="fas ' . $icon . '"></i></span></span>'
               . '<div><div class="eg-quest-title">' . $title . '</div>'
               . '<span class="eg-quest-reward"><i class="fas fa-coins"></i>' . $reward . '</span></div>'
               . '</div>'
               . '<div class="eg-quest-foot"><span class="eg-quest-pct">' . ($done ? 'Complete' : $progress . '% complete') . '</span>'
               . '<button type="button" class="eg-quest-claim" data-quest-claim="' . $qid . '" data-quest-reward="' . $reward . '"' . ($done ? '' : ' disabled') . '>'
               . ($done ? 'Claim' : 'Locked') . '</button>'
               . '</div>'
               . '</div>';
        }
        ?>
    </div>
    </div>

    <!-- ===================== OFFERWALLS ===================== -->
    <div id="offerWallContainer">
        <div class="eg-section-head">
            <div>
                <div class="eg-section-title"><span class="bolt">🎁</span> Offer Walls</div>
                <p class="eg-section-sub">Each offer wall contains hundreds of offers to complete</p>
            </div>
        </div>

        <div class="eg-wall-grid">
            <?php
            // FIX: slug now 'adcend' to match the $offerwallLogos key above
            // (was previously mismatched, so this card always fell back to
            // the default /img/logo.png).
            $offers = [
                ['Lootably',       '+99%',  'lootably'],
                ['TryGames Special Offers',       '+90%',  'adcend'],
                ['gemiad',       '+60%',  'gemiad'],
                // ['Klink',        '+60%',  'klinck'],
                // ['Avixolabs',    '+60%',  'avixolabs'],
                // ['GeowDeck',     '+60%',  'grock'],
                // ['Adtowall',     '+60%',  'adtowallda'],
                // ['playtime',     '+60%',  'playtime'],
                // ['pubscale',     '+60%',  'pubscale'],
                // ['upwall',       '+60%',  'upwall'],
                // ['offeryas',     '+59%',  'offeryas'],
            ];

            function eg_wall_tier_for_bonus($bonusValue) {
                if ($bonusValue >= 100) return 'diamond';
                if ($bonusValue >= 70)  return 'gold';
                if ($bonusValue >= 60)  return 'silver';
                return 'bronze';
            }

            foreach ($offers as $o) {
                [$name, $bonus, $slug] = $o;
                $url = '/offerwall/' . $slug;
                $img = isset($offerwallLogos[$slug]) ? $offerwallLogos[$slug] : '/img/logo.png';
                $bonusValue = (int) filter_var($bonus, FILTER_SANITIZE_NUMBER_INT);
                $isHot = $bonusValue >= 100;
                $tier = eg_wall_tier_for_bonus($bonusValue);
                $cardClass = 'eg-wall-card' . ($isHot ? ' is-hot' : '');

                echo '<a href="' . $url . '" target="_blank" rel="noopener" class="' . $cardClass . '" data-offerwall="' . $url . '" data-tier="' . $tier . '">'
                   . '<span class="eg-wall-tier-tag">' . ucfirst($tier) . '</span>'
                   . '<div class="eg-wall-logo-area">'
                   . '<div class="eg-wall-bonus">' . ($isHot ? '<span class="flame">🔥</span>' : '') . $bonus . '</div>'
                   . '<img src="' . $img . '" alt="' . $name . '" loading="lazy">'
                   . '</div>'
                   . '<div class="eg-wall-footer"><span class="eg-wall-name">' . $name . '</span><span class="eg-wall-go"><i class="fas fa-arrow-right"></i></span></div>'
                   . '</a>';
            }
            ?>
        </div>
    </div>

    <!-- ===================== TOP GAMES ===================== -->
    <div class="eg-section-head">
        <div>
            <div class="eg-section-title"><span class="bolt">🔥</span> Top Games</div>
            <p class="eg-section-sub">Featured tasks are the best tasks to complete, with the highest rewards</p>
        </div>
        <a href="/tasks" class="eg-section-view-all">View All</a>
    </div>
    <div class="eg-task-grid">
        <?php
        // Each game now carries richer detail used only by the modal:
        // screenshots (gallery), steps (how to earn), tags, rating, time
        // estimate, and an optional countdown (seconds) for hot offers.
        $games = [
            [
                'name' => 'Magnet Miner', 'sub' => 'Dig in the deepest m...',
                'img' => '/img/games/coinmaster.jpg', 'price' => '208.23', 'oldPrice' => null, 'badge' => '+100%',
                'desc' => 'Dig in the deepest mines, build your base and raid your friends. Reach the target level and claim the full reward straight to your balance.',
                'screenshots' => ['/img/games/coinmaster.jpg'],
                'steps' => ['Open the app from the link below', 'Create a free account', 'Reach level 10 within 7 days'],
                'tags' => ['Android', 'iOS', 'Simulation'],
                'rating' => 4.7, 'time' => '~20 min/day', 'ends_in' => 21600,
            ],
            [
                'name' => 'OneShot Pool', 'sub' => 'Welcome to OneSho...',
                'img' => '/img/games/ballpool.jpg', 'price' => '22.42', 'oldPrice' => '11.21', 'badge' => '+100%',
                'desc' => 'Welcome to OneShot Pool — line up your shots and climb the ranked ladder. Complete the listed milestone in-app to unlock the payout.',
                'screenshots' => ['/img/games/ballpool.jpg'],
                'steps' => ['Download and open OneShot Pool', 'Play through the tutorial', 'Reach Rank 5 in ranked mode'],
                'tags' => ['Android', 'Sports'],
                'rating' => 4.4, 'time' => '~15 min', 'ends_in' => 10800,
            ],
            [
                'name' => 'Blast it!', 'sub' => 'Open the app, regist...',
                'img' => '/img/games/toonblast.jpg', 'price' => '12.39', 'oldPrice' => '6.19', 'badge' => null,
                'desc' => 'Open the app, register a new account, and match your way through the early levels. Reward unlocks once you hit the required stage.',
                'screenshots' => ['/img/games/toonblast.jpg'],
                'steps' => ['Open the app, register a new account', 'Complete the tutorial levels', 'Reach level 15'],
                'tags' => ['Android', 'iOS', 'Puzzle'],
                'rating' => 4.5, 'time' => '~25 min', 'ends_in' => null,
            ],
            [
                'name' => 'Clumsy Arrow', 'sub' => 'Meet Clumsy Arrow, ...',
                'img' => '/img/games/freefire.jpg', 'price' => '16.54', 'oldPrice' => '8.27', 'badge' => '+100%',
                'desc' => 'Meet Clumsy Arrow, a fast-paced aiming game. Hit the target score within the trial window to trigger your reward.',
                'screenshots' => ['/img/games/freefire.jpg'],
                'steps' => ['Open the app and allow notifications', 'Play 5 matches', 'Hit the target score of 3,000'],
                'tags' => ['Android', 'Arcade'],
                'rating' => 4.2, 'time' => '~10 min', 'ends_in' => 5400,
            ],
            [
                'name' => 'Swap Rush', 'sub' => 'Dive into the colorfu...',
                'img' => '/img/games/state.webp', 'price' => '18.40', 'oldPrice' => null, 'badge' => null,
                'desc' => 'Dive into the colorful world of Swap Rush and clear the daily board challenges to unlock this task\'s full reward.',
                'screenshots' => ['/img/games/state.webp'],
                'steps' => ['Install Swap Rush', 'Link your account', 'Clear 3 daily board challenges'],
                'tags' => ['iOS', 'Puzzle'],
                'rating' => 4.3, 'time' => '~18 min', 'ends_in' => null,
            ],
            [
                'name' => 'Grab A Toy', 'sub' => 'Open the app, regist...',
                'img' => '/img/games/rise.jpg', 'price' => '203.54', 'oldPrice' => '101.77', 'badge' => '+100%',
                'desc' => 'Open the app, register, and grab your first toy from the claw machine. Reach the target level to claim the full payout.',
                'screenshots' => ['/img/games/rise.jpg'],
                'steps' => ['Open the app, register an account', 'Grab your first toy from the claw machine', 'Reach player level 8'],
                'tags' => ['Android', 'iOS', 'Casual'],
                'rating' => 4.8, 'time' => '~30 min', 'ends_in' => 14400,
            ],
            [
                'name' => 'Ball Sorting Master', 'sub' => 'Open the app, regist...',
                'img' => '/img/games/Royal-Match-Review-King-Robert.webp', 'price' => '5.72', 'oldPrice' => '2.86', 'badge' => '+100%',
                'desc' => 'Open the app, register, and sort the balls into matching tubes across the early puzzle set to unlock this reward.',
                'screenshots' => ['/img/games/Royal-Match-Review-King-Robert.webp'],
                'steps' => ['Open the app, register an account', 'Sort balls across the first 20 puzzles'],
                'tags' => ['Android', 'Puzzle'],
                'rating' => 4.1, 'time' => '~12 min', 'ends_in' => 3600,
            ],
            [
                'name' => 'Block Blitz: Gems', 'sub' => 'Open the app, regist...',
                'img' => '/img/games/tiktok-icon2.png', 'price' => '7.08', 'oldPrice' => '3.54', 'badge' => null,
                'desc' => 'Open the app, register, and clear gem blocks against the clock. Hit the milestone level to trigger your payout.',
                'screenshots' => ['/img/games/tiktok-icon2.png'],
                'steps' => ['Open the app, register an account', 'Clear gem blocks against the clock', 'Reach milestone level 12'],
                'tags' => ['Android', 'iOS', 'Arcade'],
                'rating' => 4.0, 'time' => '~14 min', 'ends_in' => null,
            ],
        ];

        function eg_rarity_for_price($price) {
            $p = (float) $price;
            if ($p >= 100) return ['legendary', 'Legendary'];
            if ($p >= 30)  return ['epic', 'Epic'];
            if ($p >= 10)  return ['rare', 'Rare'];
            return ['common', 'Common'];
        }

        // Build the payload once as a JSON blob the modal script can look
        // up by index — avoids stuffing large arrays/steps into per-card
        // data-* attributes and keeps rendering + click handling in sync.
        $gamesForJs = [];

        foreach ($games as $i => $g) {
            [$rarityKey, $rarityLabel] = eg_rarity_for_price($g['price']);

            echo '<div class="eg-task-card js-game-card" role="button" tabindex="0"'
               . ' data-index="' . $i . '"'
               . ' data-rarity="' . $rarityKey . '">'
               . '<div class="eg-task-icon-wrap">'
               . '<img src="' . $g['img'] . '" alt="' . htmlspecialchars($g['name']) . '" loading="lazy">'
               . ($g['badge'] ? '<div class="eg-task-badge">' . $g['badge'] . '</div>' : '')
               . '<div class="eg-task-store"><i class="fas fa-mobile-alt"></i></div>'
               . '</div>'
               . '<div class="eg-task-name">' . htmlspecialchars($g['name']) . '</div>'
               . '<div class="eg-task-sub">' . htmlspecialchars($g['sub']) . '</div>'
               . '<div class="eg-task-price-row">'
               . '<span class="eg-task-price">$ ' . $g['price'] . '</span>'
               . ($g['oldPrice'] ? '<span class="eg-task-price-old">$ ' . $g['oldPrice'] . '</span>' : '')
               . '</div>'
               . '<span class="eg-rarity-tag">' . $rarityLabel . '</span>'
               . '</div>';

            $gamesForJs[] = [
                'name'        => $g['name'],
                'sub'         => $g['sub'],
                'img'         => $g['img'],
                'price'       => $g['price'],
                'oldPrice'    => $g['oldPrice'],
                'badge'       => $g['badge'],
                'desc'        => $g['desc'],
                'screenshots' => !empty($g['screenshots']) ? $g['screenshots'] : [$g['img']],
                'steps'       => $g['steps'],
                'tags'        => $g['tags'],
                'rating'      => $g['rating'],
                'time'        => $g['time'],
                'endsIn'      => $g['ends_in'], // seconds from page load, or null
                'rarityKey'   => $rarityKey,
                'rarityLabel' => $rarityLabel,
                'href'        => '/offerwall/lootably',
            ];
        }
        ?>
    </div>

</div>

<!-- Full game data set, looked up by index when a card or a "related"
     suggestion is clicked. Keeps the modal in sync with the cards without
     re-parsing a pile of data-* attributes. -->
<script>window.EG_GAMES = <?php echo json_encode($gamesForJs, JSON_UNESCAPED_SLASHES); ?>;</script>

<!-- The modal markup itself is built by JS (see script below) instead of
     being server-rendered here. That way it can never "go missing" —
     it doesn't matter which template includes this file, whether it's
     loaded via AJAX into a tab, or whether some other partial only pulls
     in the .eg-task-grid above: the script always builds and attaches
     the modal to <body> the first time a game card is clicked. -->

<!-- ===================== quest claim + game modal wiring ===================== -->
<script>
    // NOTE: this file is rendered as dashboard content and may be inserted
    // into the page after the initial page load (e.g. an AJAX-loaded tab),
    // which means the document's DOMContentLoaded event has already fired
    // by the time this <script> runs. Waiting on that event here would mean
    // this code never runs at all. Since this script sits after all the
    // markup it needs, it's safe to run immediately instead.
(function () {
    // Only hide offerwalls when the setting is explicitly not 'on'.
    // Missing key → leave section visible (avoids accidental hide).
    var offerWallContainer = document.getElementById('offerWallContainer');
    var shouldHideBlock = <?php
        $twStatus = null;
        if (isset($this->data['settings']['timewall_status'])) {
            $twStatus = $this->data['settings']['timewall_status'];
        } elseif (isset($settings['timewall_status'])) {
            $twStatus = $settings['timewall_status'];
        }
        echo json_encode($twStatus !== null && $twStatus !== 'on');
    ?>;
    if (shouldHideBlock && offerWallContainer) {
        offerWallContainer.style.display = 'none';
    }

    document.addEventListener('click', function (e) {
        var btn = e.target.closest('[data-quest-claim]');
        if (!btn || btn.disabled) return;
        var reward = btn.getAttribute('data-quest-reward') || '';
        var card = btn.closest('.eg-quest-card');
        btn.disabled = true;
        btn.textContent = 'Claimed';
        if (card) card.classList.add('is-done');
        if (window.EG) {
            EG.chime('reward');
            EG.confetti(btn.getBoundingClientRect());
            EG.toast('Quest complete', reward + ' added to your balance', 'success');
            EG.bumpHud('.js-hud-today');
        }
    });

    // ================= Top Games detail modal =================
    // Delegated listeners are bound once per <script> execution (not once
    // per page-lifetime) — this file's own IIFE only runs once per time
    // this partial is inserted, so simply not re-declaring GAMES/functions
    // twice is enough; we don't need a global boot flag that can go stale.
    // Instead we track boot state as a local closure var, and — critically —
    // always re-verify the modal node is actually in the DOM before reusing
    // it, so a removed/replaced modal gets rebuilt automatically.

    var GAMES = Array.isArray(window.EG_GAMES) ? window.EG_GAMES : [];
    if (!GAMES.length && window.console) {
        console.warn('TryGames: window.EG_GAMES is empty or missing — game cards will not open a modal.');
    }

    var EG_MODAL_TEMPLATE =
        '<div class="eg-modal-overlay" id="egGameModal" aria-hidden="true">' +
          '<div class="eg-modal" id="egModalCard" data-rarity="" role="dialog" aria-modal="true" aria-labelledby="egModalTitle">' +
            '<div class="eg-modal-drag" id="egModalDrag"><span></span></div>' +
            '<button type="button" class="eg-modal-close" id="egModalClose" aria-label="Close"><i class="fas fa-times"></i></button>' +
            '<div class="eg-modal-hero is-loading" id="egModalHero">' +
              '<img id="egModalImg" src="" alt="">' +
              '<div class="eg-modal-hero-badges" id="egModalBadges"></div>' +
              '<div class="eg-modal-sparkles" id="egModalSparkles"></div>' +
            '</div>' +
            '<div class="eg-modal-thumbs" id="egModalThumbs"></div>' +
            '<div class="eg-modal-body">' +
              '<div class="eg-modal-top-row">' +
                '<span class="eg-modal-rarity" id="egModalRarity"></span>' +
                '<span class="eg-modal-rating" id="egModalRating"></span>' +
              '</div>' +
              '<div class="eg-modal-countdown" id="egModalCountdown" style="display:none;">' +
                '<i class="fas fa-bolt"></i><span id="egModalCountdownText"></span>' +
              '</div>' +
              '<h3 class="eg-modal-title" id="egModalTitle"></h3>' +
              '<p class="eg-modal-desc" id="egModalDesc"></p>' +
              '<div class="eg-modal-tags" id="egModalTags"></div>' +
              '<div class="eg-modal-stats" id="egModalStats">' +
                '<div class="eg-modal-stat">' +
                  '<div class="eg-modal-stat-label">Reward</div>' +
                  '<div class="eg-modal-stat-value" id="egModalPrice"></div>' +
                '</div>' +
                '<div class="eg-modal-stat" id="egModalOldWrap" style="display:none;">' +
                  '<div class="eg-modal-stat-label">Was</div>' +
                  '<div class="eg-modal-stat-value old" id="egModalOldPrice"></div>' +
                '</div>' +
                '<div class="eg-modal-stat" id="egModalTimeWrap" style="display:none;">' +
                  '<div class="eg-modal-stat-label">Est. Time</div>' +
                  '<div class="eg-modal-stat-value" id="egModalTime"></div>' +
                '</div>' +
              '</div>' +
              '<div id="egModalStepsWrap" style="display:none;">' +
                '<div class="eg-modal-steps-title">How to earn this reward</div>' +
                '<ol class="eg-modal-steps" id="egModalSteps"></ol>' +
              '</div>' +
              '<div class="eg-modal-actions">' +
                '<a href="/offerwall/lootably" target="_blank" rel="noopener" class="eg-modal-cta" id="egModalCta">Start Task</a>' +
                '<button type="button" class="eg-modal-share" id="egModalShare" aria-label="Copy share link"><i class="fas fa-share-alt"></i></button>' +
                '<button type="button" class="eg-modal-secondary" id="egModalCancel">Maybe later</button>' +
              '</div>' +
              '<div class="eg-modal-related" id="egModalRelatedWrap" style="display:none;">' +
                '<div class="eg-modal-related-title">You might also like</div>' +
                '<div class="eg-modal-related-grid" id="egModalRelated"></div>' +
              '</div>' +
            '</div>' +
          '</div>' +
        '</div>';

    // Elements are (re)looked-up every time egBindModalRefs() runs, and we
    // ALWAYS check whether the modal node is still attached to <body> —
    // if a previous instance was removed (e.g. content re-rendered via
    // AJAX), we rebuild it and rebind its internal listeners fresh instead
    // of silently doing nothing.
    var egModal, egModalCard, egModalDrag, egModalClose, egModalCancel,
        egModalHero, egModalImg, egModalThumbs, egModalBadges, egModalSparkles,
        egModalRarity, egModalRating, egModalCountdown, egModalCountdownTx,
        egModalTitle, egModalDesc, egModalTags, egModalPrice, egModalOldWrap,
        egModalOldPrice, egModalTimeWrap, egModalTime, egModalStepsWrap,
        egModalSteps, egModalCta, egModalShare, egModalRelatedWrap, egModalRelated;

    function egModalIsAttached() {
        var el = document.getElementById('egGameModal');
        return !!(el && document.body.contains(el));
    }

    function egEnsureModal() {
        if (egModalIsAttached()) {
            return document.getElementById('egGameModal');
        }
        // Either never built, or the old node got removed from the DOM —
        // clean up any orphan node first, then rebuild fresh.
        var stale = document.getElementById('egGameModal');
        if (stale && stale.parentNode) stale.parentNode.removeChild(stale);

        var wrap = document.createElement('div');
        wrap.innerHTML = EG_MODAL_TEMPLATE;
        var node = wrap.firstElementChild;
        document.body.appendChild(node);
        egListenersBound = false; // force rebind on the fresh node
        return node;
    }

    var egListenersBound = false;

    function egBindModalRefs() {
        egModal          = egEnsureModal();
        egModalCard       = document.getElementById('egModalCard');
        egModalDrag        = document.getElementById('egModalDrag');
        egModalClose       = document.getElementById('egModalClose');
        egModalCancel      = document.getElementById('egModalCancel');
        egModalHero        = document.getElementById('egModalHero');
        egModalImg         = document.getElementById('egModalImg');
        egModalThumbs      = document.getElementById('egModalThumbs');
        egModalBadges      = document.getElementById('egModalBadges');
        egModalSparkles    = document.getElementById('egModalSparkles');
        egModalRarity      = document.getElementById('egModalRarity');
        egModalRating      = document.getElementById('egModalRating');
        egModalCountdown   = document.getElementById('egModalCountdown');
        egModalCountdownTx = document.getElementById('egModalCountdownText');
        egModalTitle       = document.getElementById('egModalTitle');
        egModalDesc        = document.getElementById('egModalDesc');
        egModalTags        = document.getElementById('egModalTags');
        egModalPrice       = document.getElementById('egModalPrice');
        egModalOldWrap     = document.getElementById('egModalOldWrap');
        egModalOldPrice    = document.getElementById('egModalOldPrice');
        egModalTimeWrap    = document.getElementById('egModalTimeWrap');
        egModalTime        = document.getElementById('egModalTime');
        egModalStepsWrap   = document.getElementById('egModalStepsWrap');
        egModalSteps       = document.getElementById('egModalSteps');
        egModalCta         = document.getElementById('egModalCta');
        egModalShare       = document.getElementById('egModalShare');
        egModalRelatedWrap = document.getElementById('egModalRelatedWrap');
        egModalRelated     = document.getElementById('egModalRelated');

        if (!egListenersBound) {
            if (egModalClose)  egModalClose.addEventListener('click', egCloseGameModal);
            if (egModalCancel) egModalCancel.addEventListener('click', egCloseGameModal);
            if (egModalShare)  egModalShare.addEventListener('click', egShareCurrent);
            egModal.addEventListener('click', function (e) {
                if (e.target === egModal) egCloseGameModal();
            });
            egBindDragToClose();
            egListenersBound = true;
        }
    }

    var egLastFocused   = null;
    var egCountdownTimer = null;
    var egCurrentIndex  = -1;

    function egFmt2(n) {
        n = parseFloat(n);
        return isNaN(n) ? '0.00' : n.toFixed(2);
    }

    function egSpawnSparkles() {
        if (!egModalSparkles) return;
        egModalSparkles.innerHTML = '';
        var count = window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 0 : 14;
        for (var i = 0; i < count; i++) {
            var s = document.createElement('span');
            s.className = 'eg-modal-sparkle';
            var angle = Math.random() * Math.PI * 2;
            var dist = 30 + Math.random() * 70;
            s.style.left = (35 + Math.random() * 30) + '%';
            s.style.top = (35 + Math.random() * 30) + '%';
            s.style.setProperty('--sx', (Math.cos(angle) * dist) + 'px');
            s.style.setProperty('--sy', (Math.sin(angle) * dist) + 'px');
            s.style.animationDelay = (Math.random() * 0.15) + 's';
            egModalSparkles.appendChild(s);
        }
    }

    function egSetHeroImage(src, alt) {
        egModalHero.classList.add('is-loading');
        var probe = new Image();
        probe.onload = function () { egModalHero.classList.remove('is-loading'); };
        probe.onerror = function () { egModalHero.classList.remove('is-loading'); };
        probe.src = src;
        egModalImg.src = src;
        egModalImg.alt = alt || '';
    }

    function egRenderThumbs(game) {
        egModalThumbs.innerHTML = '';
        var shots = game.screenshots && game.screenshots.length ? game.screenshots : [game.img];
        if (shots.length < 2) { egModalThumbs.style.display = 'none'; return; }
        egModalThumbs.style.display = '';
        shots.forEach(function (src, i) {
            var b = document.createElement('button');
            b.type = 'button';
            b.className = 'eg-modal-thumb' + (i === 0 ? ' active' : '');
            b.innerHTML = '<img src="' + src + '" alt="">';
            b.addEventListener('click', function () {
                egModalThumbs.querySelectorAll('.eg-modal-thumb').forEach(function (t) { t.classList.remove('active'); });
                b.classList.add('active');
                egSetHeroImage(src, game.name);
            });
            egModalThumbs.appendChild(b);
        });
    }

    function egRenderTags(tags) {
        egModalTags.innerHTML = '';
        (tags || []).forEach(function (t) {
            var chip = document.createElement('span');
            chip.className = 'eg-tag-chip';
            chip.textContent = t;
            egModalTags.appendChild(chip);
        });
    }

    function egRenderSteps(steps) {
        egModalSteps.innerHTML = '';
        if (!steps || !steps.length) { egModalStepsWrap.style.display = 'none'; return; }
        egModalStepsWrap.style.display = '';
        steps.forEach(function (s, i) {
            var li = document.createElement('li');
            li.className = 'eg-modal-step';
            li.innerHTML = '<span class="eg-modal-step-num">' + (i + 1) + '</span><span>' + s + '</span>';
            egModalSteps.appendChild(li);
        });
    }

    function egRenderRelated(currentIndex) {
        egModalRelated.innerHTML = '';
        var pool = GAMES.map(function (g, i) { return i; }).filter(function (i) { return i !== currentIndex; });
        for (var i = pool.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var tmp = pool[i]; pool[i] = pool[j]; pool[j] = tmp;
        }
        var picks = pool.slice(0, 4);
        if (!picks.length) { egModalRelatedWrap.style.display = 'none'; return; }
        egModalRelatedWrap.style.display = '';
        picks.forEach(function (i) {
            var g = GAMES[i];
            var card = document.createElement('button');
            card.type = 'button';
            card.className = 'eg-modal-related-card';
            card.innerHTML = '<img src="' + g.img + '" alt="' + g.name + '">'
                + '<div class="eg-modal-related-name">' + g.name + '</div>'
                + '<div class="eg-modal-related-price">$ ' + g.price + '</div>';
            card.addEventListener('click', function () { egOpenGameModal(i); });
            egModalRelated.appendChild(card);
        });
    }

    function egStartCountdown(seconds) {
        if (egCountdownTimer) { clearInterval(egCountdownTimer); egCountdownTimer = null; }
        if (!seconds || seconds <= 0) { egModalCountdown.style.display = 'none'; return; }
        var deadline = Date.now() + seconds * 1000;
        egModalCountdown.style.display = '';
        function tick() {
            var remaining = Math.max(0, Math.round((deadline - Date.now()) / 1000));
            var h = Math.floor(remaining / 3600);
            var m = Math.floor((remaining % 3600) / 60);
            var s = remaining % 60;
            var pad = function (n) { return (n < 10 ? '0' : '') + n; };
            egModalCountdownTx.textContent = 'Bonus ends in ' + pad(h) + ':' + pad(m) + ':' + pad(s);
            if (remaining <= 0) {
                clearInterval(egCountdownTimer);
                egCountdownTimer = null;
                egModalCountdown.style.display = 'none';
            }
        }
        tick();
        egCountdownTimer = setInterval(tick, 1000);
    }

    function egOpenGameModal(index) {
        // Re-read window.EG_GAMES at call time too — covers the case where
        // it gets (re)populated after this script first ran.
        if (!GAMES.length && Array.isArray(window.EG_GAMES) && window.EG_GAMES.length) {
            GAMES = window.EG_GAMES;
        }
        var game = GAMES[index];
        if (!game) {
            if (window.console) console.warn('TryGames: no game data for index', index, '— check window.EG_GAMES.');
            if (window.EG) EG.toast('Unavailable', 'This task could not be loaded right now.', 'gold');
            return;
        }
        egCurrentIndex = index;

        egBindModalRefs();

        egModalCard.setAttribute('data-rarity', game.rarityKey || 'common');
        egSetHeroImage(game.img, game.name);
        egRenderThumbs(game);

        egModalTitle.textContent = game.name || '';
        egModalDesc.textContent = game.desc || '';
        egModalRarity.textContent = game.rarityLabel || '';
        egModalPrice.textContent = '$ ' + egFmt2(game.price);
        egModalCta.href = game.href || '/offerwall/lootably';

        if (game.rating) {
            egModalRating.innerHTML = '<i class="fas fa-star"></i> ' + Number(game.rating).toFixed(1);
            egModalRating.style.display = '';
        } else {
            egModalRating.style.display = 'none';
        }

        egRenderTags(game.tags);
        egRenderSteps(game.steps);
        egStartCountdown(game.endsIn);

        egModalBadges.innerHTML = '';
        if (game.badge) {
            var b = document.createElement('span');
            b.className = 'eg-modal-hero-badge';
            b.textContent = game.badge;
            egModalBadges.appendChild(b);
        }

        if (game.oldPrice && game.oldPrice !== '' && game.oldPrice !== 'null') {
            egModalOldPrice.textContent = '$ ' + egFmt2(game.oldPrice);
            egModalOldWrap.style.display = '';
        } else {
            egModalOldWrap.style.display = 'none';
        }

        if (game.time) {
            egModalTime.textContent = game.time;
            egModalTimeWrap.style.display = '';
        } else {
            egModalTimeWrap.style.display = 'none';
        }

        egRenderRelated(index);

        egLastFocused = document.activeElement;
        egModal.classList.add('is-open');
        egModal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('eg-modal-lock');
        egSpawnSparkles();
        egModalClose.focus();
    }

    function egCloseGameModal() {
        if (!egModal) return;
        egModal.classList.remove('is-open');
        egModal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('eg-modal-lock');
        if (egCountdownTimer) { clearInterval(egCountdownTimer); egCountdownTimer = null; }
        if (egLastFocused) egLastFocused.focus();
    }

    function egFocusableEls() {
        return Array.prototype.slice.call(
            egModalCard.querySelectorAll('button, a[href], [tabindex]:not([tabindex="-1"])')
        ).filter(function (el) { return el.offsetParent !== null; });
    }

    function egShareCurrent() {
        var game = GAMES[egCurrentIndex];
        if (!game) return;
        var url = window.location.origin + (game.href || '/offerwall/lootably');
        var done = function () {
            egModalShare.classList.add('is-copied');
            egModalShare.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(function () {
                egModalShare.classList.remove('is-copied');
                egModalShare.innerHTML = '<i class="fas fa-share-alt"></i>';
            }, 1600);
        };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(done, done);
        } else {
            var ta = document.createElement('textarea');
            ta.value = url;
            ta.style.position = 'fixed';
            ta.style.opacity = '0';
            document.body.appendChild(ta);
            ta.select();
            try { document.execCommand('copy'); } catch (err) {}
            document.body.removeChild(ta);
            done();
        }
    }

    function egBindDragToClose() {
        if (!egModalDrag) return;
        var dragStartY = 0, dragDeltaY = 0, isDragging = false;
        var onStart = function (clientY) {
            if (!window.matchMedia('(max-width: 640px)').matches) return;
            isDragging = true;
            dragStartY = clientY;
            egModalCard.style.transition = 'none';
        };
        var onMove = function (clientY) {
            if (!isDragging) return;
            dragDeltaY = Math.max(0, clientY - dragStartY);
            egModalCard.style.transform = 'translateY(' + dragDeltaY + 'px)';
        };
        var onEnd = function () {
            if (!isDragging) return;
            isDragging = false;
            egModalCard.style.transition = '';
            egModalCard.style.transform = '';
            if (dragDeltaY > 90) {
                egCloseGameModal();
            }
            dragDeltaY = 0;
        };
        egModalDrag.addEventListener('touchstart', function (e) { onStart(e.touches[0].clientY); }, { passive: true });
        egModalDrag.addEventListener('touchmove', function (e) { onMove(e.touches[0].clientY); }, { passive: true });
        egModalDrag.addEventListener('touchend', onEnd);
        egModalDrag.addEventListener('mousedown', function (e) { onStart(e.clientY); });
        document.addEventListener('mousemove', function (e) { if (isDragging) onMove(e.clientY); });
        document.addEventListener('mouseup', onEnd);
    }

    // Pre-create the modal node immediately so first click is instant and
    // any template/ID issues surface in the console right away.
    try {
        egBindModalRefs();
    } catch (err) {
        if (window.console) console.error('TryGames: failed to init game modal', err);
    }

    // Bind document-level listeners only once for the whole page lifetime
    // (survives AJAX re-injection of this partial).
    if (!window.__EG_GAME_MODAL_BOUND__) {
        window.__EG_GAME_MODAL_BOUND__ = true;

        document.addEventListener('click', function (e) {
            var card = e.target.closest('.js-game-card');
            if (!card) return;
            e.preventDefault();
            e.stopPropagation();
            var idx = parseInt(card.getAttribute('data-index'), 10);
            if (isNaN(idx)) {
                if (window.console) console.warn('TryGames: game card missing data-index');
                return;
            }
            egOpenGameModal(idx);
        }, true); // capture phase so nothing else can swallow the click

        document.addEventListener('keydown', function (e) {
            var card = e.target.closest && e.target.closest('.js-game-card');
            if (card && (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar')) {
                e.preventDefault();
                var idx = parseInt(card.getAttribute('data-index'), 10);
                egOpenGameModal(idx);
                return;
            }
            if (!egModal || !egModal.classList.contains('is-open')) return;
            if (e.key === 'Escape') {
                egCloseGameModal();
                return;
            }
            if (e.key === 'Tab') {
                var focusable = egFocusableEls();
                if (!focusable.length) return;
                var first = focusable[0];
                var last = focusable[focusable.length - 1];
                if (e.shiftKey && document.activeElement === first) {
                    e.preventDefault();
                    last.focus();
                } else if (!e.shiftKey && document.activeElement === last) {
                    e.preventDefault();
                    first.focus();
                }
            }
        });
    }
})();
    function openTabjoyOfferwall() {
        window.location.href = "coinlycash://open-tabjoy-offerwall";
        alert('Download our app to show this offerwall');
    }
    function openPubOfferwall() {
        var userId = '<?php echo isset($userId) ? $userId : (isset($user["id"]) ? $user["id"] : ""); ?>';
        if (userId) {
            window.location.href = "coinlycash://open-pubscale-offerwall?user_id=" + userId;
        } else {
            alert('User ID is not set!');
        }
        setTimeout(function() { window.location.href = "/"; }, 2000);
        alert('Download our app to open this offerwall');
    }
</script>

<script>
    localStorage.setItem('user_id', '<?php echo isset($userId) ? $userId : (isset($user["id"]) ? $user["id"] : ""); ?>');
</script>

<script async src="https://www.googletagmanager.com/gtag/js?id=G-FNW6P9E8E7"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-FNW6P9E8E7');
</script>
<div id="onerow"></div>
<script type="text/javascript" src="https://cdn.cpx-research.com/assets/js/script_tag_v2.0.js"></script>