<!doctype html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Survive | Ver Jogo</title>
    <meta name="theme-color" content="#0a0f2a">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Survive">
    <link rel="manifest" href="/manifest.webmanifest">
    <link rel="apple-touch-icon" href="/icons/icon-192.svg">
    <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=Anton&family=Rajdhani:wght@500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-1: #050714;
            --bg-2: #090f2a;
            --bg-3: #1b0d38;
            --line: #222d60;
            --text: #f7f8ff;
            --muted: #8f98bf;
            --card: #0d1230;
            --card-soft: #0b1029;
            --yellow: #ffc928;
            --green: #2ee46e;
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            min-height: 100vh;
            font-family: 'Rajdhani', sans-serif;
            color: var(--text);
            background:
                radial-gradient(600px 400px at 20% -10%, #4f2dc166 0%, transparent 62%),
                radial-gradient(700px 450px at 100% 120%, #1d7ad03b 0%, transparent 62%),
                linear-gradient(145deg, var(--bg-1), var(--bg-2), var(--bg-3));
            display: grid;
            place-items: center;
            padding: 16px;
        }

        .phone {
            width: min(390px, 100%);
            min-height: 760px;
            border-radius: 32px;
            border: 1px solid #2f3c7a;
            background: linear-gradient(180deg, #060a1b 0%, #080c22 55%, #070919 100%);
            box-shadow: 0 30px 80px #000a;
            padding: 16px 14px 12px;
            display: grid;
            grid-template-rows: auto auto auto auto auto 1fr auto;
            gap: 12px;
            animation: rise 380ms ease-out;
        }

        .top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 2px 2px 0;
        }

        .top form {
            margin: 0;
        }

        .icon-btn {
            width: 34px;
            height: 34px;
            border-radius: 10px;
            border: 1px solid #344183;
            background: #0e1535;
            display: grid;
            place-items: center;
            color: #dbe3ff;
        }

        .icon-btn.logout {
            cursor: pointer;
        }

        .brand {
            border: 0;
            border-radius: 0;
            background: transparent;
            text-align: center;
            padding: 0 4px 0;
            margin-bottom: 0;
        }

        .brand .logo {
            width: 100%;
            max-width: 252px;
            height: auto;
            display: block;
            margin: -29px auto 0;
            object-fit: contain;
            filter: drop-shadow(0 8px 16px #0009);
        }

        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border: 0;
        }

        .round {
            border: 1px solid var(--line);
            border-radius: 16px;
            background: var(--card);
            text-align: center;
            padding: 14px 10px;
        }

        .round .label {
            margin: 0;
            font-size: 1.05rem;
            font-weight: 700;
            color: var(--muted);
            text-transform: uppercase;
            letter-spacing: 0.6px;
        }

        .countdown {
            margin: 4px 0 2px;
            font-size: 3.1rem;
            font-weight: 700;
            line-height: 1;
            letter-spacing: 1px;
        }

        .round .when {
            margin: 0;
            font-size: 1.65rem;
            font-weight: 700;
        }

        .city-pill {
            border: 1px solid #35508e;
            border-radius: 12px;
            background: #0d173d;
            color: #dce5ff;
            padding: 8px 10px;
            text-align: center;
            font-weight: 700;
            font-size: 1.02rem;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }

        .stat {
            border: 1px solid var(--line);
            border-radius: 14px;
            padding: 10px 12px 12px;
            background: var(--card-soft);
        }

        .label {
            text-transform: uppercase;
            font-size: 0.85rem;
            font-weight: 700;
            color: var(--muted);
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .value {
            font-size: clamp(1.7rem, 5vw, 1.95rem);
            font-weight: 700;
            line-height: 1;
        }

        .value.green {
            color: var(--green);
        }

        .value.compact {
            font-size: clamp(1.42rem, 4.2vw, 1.72rem);
            letter-spacing: -0.2px;
        }

        .meta {
            margin-top: 2px;
            color: #aeb8db;
            font-size: 1.05rem;
            font-weight: 600;
        }

        .meta.live-tag {
            position: relative;
            margin-top: 8px;
            width: fit-content;
            padding: 2px 10px 2px 26px;
            border-radius: 999px;
            border: 1px solid #8e1d2f;
            background: linear-gradient(180deg, #4d1020, #300a15);
            color: #ffb5c1;
            font-size: 0.92rem;
            font-weight: 700;
            letter-spacing: 0.45px;
            text-transform: uppercase;
            box-shadow:
                inset 0 1px 0 #ffffff12,
                0 0 0 0 #ff4d7366;
            animation: liveTagPulse 2.2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
        }

        .meta.live-tag::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 50%;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #ff5d7c;
            transform: translateY(-50%);
            box-shadow: 0 0 8px #ff5d7ccc;
            animation: liveDotBlink 1.1s ease-in-out infinite;
        }

        .meta.live-tag::after {
            content: '';
            position: absolute;
            inset: -1px;
            border-radius: 999px;
            border: 1px solid #ff7a9644;
            opacity: 0;
            transform: scale(1);
            animation: liveHalo 2.2s ease-out infinite;
            pointer-events: none;
        }

        @keyframes liveTagPulse {
            0% {
                transform: scale(1);
                box-shadow:
                    inset 0 1px 0 #ffffff12,
                    0 0 0 0 #ff4d7333;
            }

            40% {
                transform: scale(1.03);
                box-shadow:
                    inset 0 1px 0 #ffffff18,
                    0 0 14px 2px #ff4d7355;
            }

            100% {
                transform: scale(1);
                box-shadow:
                    inset 0 1px 0 #ffffff12,
                    0 0 0 0 #ff4d7333;
            }
        }

        @keyframes liveDotBlink {
            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.45;
            }
        }

        @keyframes liveHalo {
            0% {
                opacity: 0;
                transform: scale(1);
            }

            20% {
                opacity: 0.55;
            }

            100% {
                opacity: 0;
                transform: scale(1.14);
            }
        }

        .cta {
            margin-top: 2px;
            border: 0;
            border-radius: 14px;
            background: linear-gradient(180deg, #ffd54a, #ffc928);
            color: #211500;
            font: inherit;
            text-transform: uppercase;
            font-size: clamp(1.44rem, 5vw, 1.82rem);
            font-weight: 700;
            letter-spacing: 0.42px;
            line-height: 1;
            padding: 7px 12px;
            width: 100%;
            max-width: 100%;
            min-height: 50px;
            justify-self: center;
            cursor: pointer;
            border: 1px solid #f4bf12;
            box-shadow: 0 10px 20px #0007;
            animation: ctaPulse 2.6s ease-in-out infinite;
        }

        @keyframes ctaPulse {
            0%,
            100% {
                transform: scale(1);
                box-shadow: 0 10px 20px #0007;
            }

            50% {
                transform: scale(1.015);
                box-shadow: 0 12px 24px #0008;
            }
        }

        .entry-fee {
            margin: 0;
            text-align: center;
            color: #d7defb;
            font-size: 1.2rem;
            font-weight: 600;
        }

        .install {
            border: 1px solid #39467c;
            background: #10183a;
            color: #dce5ff;
            border-radius: 12px;
            padding: 9px 12px;
            font: inherit;
            font-size: 1rem;
            font-weight: 700;
            justify-self: center;
            cursor: pointer;
        }

        .install[hidden] {
            display: none;
        }

        .payment-overlay[hidden] {
            display: none;
        }

        .payment-overlay {
            position: fixed;
            inset: 0;
            z-index: 80;
            background: #030613dd;
            backdrop-filter: blur(5px);
            display: grid;
            place-items: center;
            padding: 14px;
        }

        .payment-sheet {
            width: min(420px, 100%);
            border: 1px solid #3b4f94;
            border-radius: 18px;
            background: linear-gradient(180deg, #0b1231, #091028);
            box-shadow: 0 30px 80px #000a;
            padding: 14px;
            position: relative;
            display: grid;
            gap: 10px;
        }

        .payment-close {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 32px;
            height: 32px;
            border-radius: 9px;
            border: 1px solid #4259a5;
            background: #111c45;
            color: #dce6ff;
            font-size: 1.2rem;
            line-height: 1;
            cursor: pointer;
        }

        .payment-status {
            margin: 0;
            width: fit-content;
            border: 1px solid #8e1d2f;
            border-radius: 999px;
            background: linear-gradient(180deg, #4d1020, #2d0a14);
            color: #ffb5c1;
            padding: 4px 12px;
            text-transform: uppercase;
            font-size: 0.84rem;
            font-weight: 700;
            letter-spacing: 0.55px;
        }

        .payment-status.is-waiting {
            animation: paymentStatusPulse 1.9s ease-in-out infinite;
        }

        .payment-status.is-approved {
            border-color: #1f8a49;
            background: linear-gradient(180deg, #124228, #0e301d);
            color: #a8f5c5;
        }

        .payment-status.is-waiting::after {
            content: '...';
            display: inline-block;
            width: 0;
            overflow: hidden;
            vertical-align: bottom;
            animation: paymentStatusDots 1.2s steps(4, end) infinite;
        }

        @keyframes paymentStatusPulse {
            0%,
            100% {
                transform: scale(1);
                box-shadow: 0 0 0 0 #ff4d7333;
            }

            50% {
                transform: scale(1.02);
                box-shadow: 0 0 12px 1px #ff4d7347;
            }
        }

        @keyframes paymentStatusDots {
            0% {
                width: 0;
            }

            100% {
                width: 1.9ch;
            }
        }

        .payment-title {
            margin: 0;
            font-family: 'Anton', sans-serif;
            letter-spacing: 0.7px;
            font-size: 1.5rem;
        }

        .payment-subtitle {
            margin: -4px 0 0;
            color: #b7c3ed;
            font-size: 1rem;
            font-weight: 600;
        }

        .payment-qr-wrap {
            border: 1px solid #4157a4;
            border-radius: 14px;
            background: #f7f9ff;
            padding: 10px;
            width: fit-content;
            margin: 4px auto 0;
        }

        .payment-qr {
            width: 240px;
            height: 240px;
            display: block;
            border-radius: 8px;
        }

        .payment-label {
            color: #d4ddff;
            font-size: 1rem;
            font-weight: 700;
        }

        .payment-copy {
            width: 100%;
            min-height: 88px;
            border: 1px solid #4157a4;
            border-radius: 10px;
            background: #111b40;
            color: #f3f6ff;
            font: inherit;
            font-size: 0.95rem;
            font-weight: 700;
            line-height: 1.4;
            padding: 10px;
            resize: none;
        }

        .payment-actions {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .payment-copy-btn {
            border: 1px solid #d0a500;
            border-radius: 10px;
            background: linear-gradient(180deg, #ffd54a, #ffc928);
            color: #241800;
            font: inherit;
            font-size: 1rem;
            font-weight: 700;
            padding: 8px 12px;
            cursor: pointer;
        }

        .payment-confirm-btn {
            border: 1px solid #258f4f;
            border-radius: 10px;
            background: linear-gradient(180deg, #2dd26f, #1fb35a);
            color: #032611;
            font: inherit;
            font-size: 1rem;
            font-weight: 700;
            padding: 8px 12px;
            cursor: pointer;
        }

        .payment-copy-btn:disabled,
        .payment-confirm-btn:disabled {
            opacity: 0.6;
            cursor: wait;
        }

        .payment-feedback {
            color: #98f3bb;
            font-size: 0.95rem;
            font-weight: 700;
        }

        .payment-meta {
            margin: 0;
            color: #a7b4e2;
            font-size: 0.95rem;
            font-weight: 600;
        }

        .tab-hidden {
            display: none !important;
        }

        .tab-card {
            border: 1px solid var(--line);
            border-radius: 14px;
            padding: 12px;
            background: var(--card-soft);
            display: grid;
            gap: 8px;
        }

        .tab-card .title {
            margin: 0;
            color: #e5ebff;
            font-size: 1.2rem;
            font-weight: 700;
        }

        .tab-card .text {
            margin: 0;
            color: #b6c2ea;
            font-size: 1rem;
            font-weight: 600;
        }

        .tab-card.highlight {
            animation: roomHighlight 900ms ease;
        }

        @keyframes roomHighlight {
            0% {
                box-shadow: 0 0 0 0 #ffd54a00;
            }

            35% {
                box-shadow: 0 0 0 3px #ffd54a66;
            }

            100% {
                box-shadow: 0 0 0 0 #ffd54a00;
            }
        }

        .avatar-shell {
            border: 1px solid #2f3a74;
            border-radius: 16px;
            background: linear-gradient(180deg, #090e22, #090d1f);
            box-shadow: inset 0 1px 0 #ffffff0d, 0 14px 30px #0007;
            padding: 10px;
            display: grid;
            gap: 10px;
        }

        .avatar-header {
            display: grid;
            grid-template-columns: 26px 1fr 26px;
            align-items: center;
            gap: 6px;
            border-bottom: 1px solid #1f2a5a;
            padding-bottom: 8px;
        }

        .avatar-back-btn {
            width: 24px;
            height: 24px;
            border: 0;
            border-radius: 6px;
            background: transparent;
            color: #cfd8ff;
            cursor: pointer;
            font-size: 1.2rem;
            line-height: 1;
            padding: 0;
        }

        .avatar-header-title {
            margin: 0;
            text-align: center;
            font-family: 'Anton', sans-serif;
            font-size: 1.1rem;
            letter-spacing: 0.6px;
            text-transform: uppercase;
            color: #edf1ff;
        }

        .avatar-stage {
            border: 1px solid #2c2556;
            border-radius: 14px;
            background:
                radial-gradient(120% 90% at 50% 0%, #4d1fbf66 0%, #1a153f 42%, #0f1432 100%);
            min-height: 300px;
            display: grid;
            align-content: end;
            justify-items: center;
            gap: 4px;
            padding: 14px 10px 12px;
            position: relative;
            overflow: hidden;
        }

        .avatar-stage::before {
            content: '';
            position: absolute;
            width: 210px;
            height: 210px;
            border-radius: 50%;
            bottom: -120px;
            left: 50%;
            transform: translateX(-50%);
            background: radial-gradient(circle, #8e5bff88 0%, #8e5bff11 65%, transparent 80%);
            pointer-events: none;
        }

        .avatar-preview {
            display: grid;
            gap: 6px;
            justify-items: center;
            position: relative;
            z-index: 1;
        }

        .avatar-preview-face {
            width: 230px;
            height: 230px;
            border-radius: 0;
            border: 0;
            display: flex;
            align-items: flex-end;
            justify-content: center;
            background: transparent;
            box-shadow: none;
            overflow: visible;
            position: relative;
            isolation: isolate;
            transform-origin: 50% 100%;
        }

        .avatar-preview-face.is-picked {
            animation: avatarPick 360ms ease;
        }

        .avatar-preview-photo {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: block;
            filter: drop-shadow(0 10px 14px #0007) saturate(1.08) brightness(1.12) contrast(1.04);
            mix-blend-mode: normal;
            transition: opacity 180ms ease, transform 220ms ease;
        }

        .avatar-preview-face.is-switching .avatar-preview-photo {
            opacity: 0.1;
            transform: translateY(8px) scale(0.95);
        }

        .avatar-preview-fallback {
            font-size: 3.3rem;
            line-height: 1;
            filter: drop-shadow(0 10px 14px #0009);
        }

        .avatar-preview-fallback[hidden] {
            display: none !important;
        }

        .avatar-preview-text {
            margin: 0;
            color: #ced9ff;
            font-size: 0.85rem;
            font-weight: 700;
            text-align: center;
        }

        .avatar-filters {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 5px;
        }

        .avatar-filter-btn {
            border: 1px solid #2a3a73;
            border-radius: 7px;
            background: #121834;
            color: #b7c3ec;
            font: inherit;
            font-size: 0.76rem;
            font-weight: 700;
            padding: 6px 5px;
            cursor: pointer;
        }

        .avatar-filter-btn.active {
            border-color: #4f69d2;
            background: linear-gradient(180deg, #30439a, #1f2e72);
            color: #fff;
        }

        .avatar-grid {
            display: grid;
            grid-template-columns: repeat(5, minmax(0, 1fr));
            gap: 6px;
        }

        .avatar-option {
            border: 1px solid #2d3d74;
            border-radius: 10px;
            background: linear-gradient(180deg, #171f45, #101733);
            aspect-ratio: 1 / 1;
            color: #e6edff;
            display: grid;
            place-items: center;
            cursor: pointer;
            transition: transform 120ms ease, border-color 120ms ease, box-shadow 120ms ease;
            overflow: hidden;
            position: relative;
            padding: 2px;
            isolation: isolate;
        }

        .avatar-option:hover {
            transform: translateY(-1px);
            border-color: #4b60ad;
        }

        .avatar-option.selected {
            border-color: #ffd54a;
            box-shadow: 0 0 0 2px #ffd54a4d;
            background: linear-gradient(180deg, #31235d, #1b2146);
        }

        .avatar-option-photo {
            width: 100%;
            height: 100%;
            object-fit: contain;
            display: block;
            border-radius: 8px;
            border: 0;
            filter: drop-shadow(0 4px 8px #0006) saturate(1.1) brightness(1.16) contrast(1.05);
            transition: transform 120ms ease;
            mix-blend-mode: normal;
        }

        .avatar-option:hover .avatar-option-photo {
            transform: translateY(-2px) scale(1.02);
        }

        .avatar-option.selected .avatar-option-photo {
            transform: translateY(-2px) scale(1.03);
        }

        .avatar-option-fallback {
            font-size: 1.45rem;
            line-height: 1;
            border-radius: 9px;
            border: 1px solid #3b4a85;
            width: 100%;
            height: 100%;
            display: grid;
            place-items: center;
            background: #111939;
        }

        .avatar-option-fallback[hidden] {
            display: none !important;
        }

        .avatar-option.selected .avatar-option-fallback {
            border-color: #ffd54a;
            box-shadow: 0 0 0 2px #ffd54a4d;
        }

        .phone.avatar-mode {
            grid-template-rows: 1fr;
            gap: 0;
            padding: 8px 10px 10px;
        }

        .phone.avatar-mode .top,
        .phone.avatar-mode .brand,
        .phone.avatar-mode .round,
        .phone.avatar-mode .city-pill,
        .phone.avatar-mode .stats,
        .phone.avatar-mode .cta,
        .phone.avatar-mode .entry-fee,
        .phone.avatar-mode .install,
        .phone.avatar-mode .tab-card[data-tab-view="invite"],
        .phone.avatar-mode .tab-card[data-tab-view="profile"],
        .phone.avatar-mode .bottom-nav {
            display: none !important;
        }

        .phone.avatar-mode .tab-card[data-tab-view="rooms"] {
            display: block;
            border: 0;
            background: transparent;
            padding: 0;
            margin: 0;
            align-self: stretch;
        }

        .phone.avatar-mode .avatar-shell {
            height: 100%;
        }

        .phone.arena-mode {
            grid-template-rows: 1fr;
            gap: 0;
            padding: 8px;
        }

        .phone.arena-mode .top,
        .phone.arena-mode .brand,
        .phone.arena-mode .round,
        .phone.arena-mode .city-pill,
        .phone.arena-mode .stats,
        .phone.arena-mode .cta,
        .phone.arena-mode .entry-fee,
        .phone.arena-mode .install,
        .phone.arena-mode .tab-card[data-tab-view="rooms"],
        .phone.arena-mode .tab-card[data-tab-view="invite"],
        .phone.arena-mode .tab-card[data-tab-view="profile"],
        .phone.arena-mode .bottom-nav {
            display: none !important;
        }

        .phone.arena-mode .tab-card[data-tab-view="arena"] {
            display: block;
            border: 0;
            background: transparent;
            padding: 0;
            margin: 0;
            align-self: stretch;
        }

        .avatar-confirm {
            border: 1px solid #d0a500;
            border-radius: 10px;
            background: linear-gradient(180deg, #ffd54a, #ffc928);
            color: #271800;
            font-family: 'Anton', sans-serif;
            letter-spacing: 0.45px;
            font-size: 1.1rem;
            padding: 10px 12px;
            text-transform: uppercase;
            cursor: pointer;
        }

        .avatar-note {
            margin: 0;
            color: #8df2ba;
            min-height: 1.2rem;
            font-size: 0.84rem;
            font-weight: 700;
            text-align: center;
        }

        .arena-shell {
            border: 1px solid #23497a;
            border-radius: 20px;
            background:
                radial-gradient(120% 90% at 50% 0%, #123768 0%, #0a2544 46%, #07172c 100%);
            box-shadow: inset 0 1px 0 #ffffff12, 0 16px 36px #0009;
            padding: 10px;
            height: 100%;
            display: grid;
            grid-template-rows: auto auto 1fr auto;
            gap: 8px;
        }

        .arena-head {
            display: grid;
            grid-template-columns: 26px 1fr 26px;
            align-items: center;
            gap: 6px;
            padding-bottom: 5px;
        }

        .arena-back-btn {
            width: 24px;
            height: 24px;
            border: 0;
            border-radius: 7px;
            background: #0d1f3f;
            color: #dce7ff;
            font-size: 1rem;
            cursor: pointer;
            padding: 0;
            line-height: 1;
        }

        .arena-title {
            margin: 0;
            text-align: center;
            font-family: 'Anton', sans-serif;
            font-size: 1.2rem;
            letter-spacing: 0.65px;
            color: #eaf2ff;
            text-transform: uppercase;
        }

        .arena-status {
            display: flex;
            align-items: center;
            gap: 6px;
            flex-wrap: wrap;
            justify-content: center;
            padding-bottom: 4px;
        }

        .arena-badge {
            border: 1px solid #315894;
            border-radius: 999px;
            padding: 3px 9px;
            font-size: 0.74rem;
            font-weight: 700;
            letter-spacing: 0.4px;
            text-transform: uppercase;
            color: #c7d9ff;
            background: #102548;
        }

        .arena-badge.live {
            border-color: #8e1d2f;
            color: #ffd6de;
            background: linear-gradient(180deg, #5b1626, #35101a);
        }

        .arena-badge.rest {
            border-color: #287942;
            color: #bbffd1;
            background: linear-gradient(180deg, #17462a, #0f301d);
        }

        .arena-map {
            position: relative;
            border: 1px solid #2a5e97;
            border-radius: 24px;
            padding: 10px 8px;
            background:
                radial-gradient(160% 120% at 12% 14%, #6ed0ff40 0%, transparent 38%),
                radial-gradient(140% 120% at 88% 82%, #5cb7ec33 0%, transparent 42%),
                radial-gradient(120% 120% at 50% 50%, #155686 0%, #0c3f66 42%, #082f4d 70%, #06253d 100%);
            box-shadow: inset 0 0 0 1px #6dbbff2b, 0 10px 22px #001526cc;
            display: grid;
            place-items: center;
            min-height: 446px;
            overflow: hidden;
        }

        .arena-map::before {
            content: '';
            position: absolute;
            inset: -20px;
            background:
                repeating-radial-gradient(circle at 12% 22%, #9adfff1a 0 16px, transparent 16px 32px),
                repeating-radial-gradient(circle at 78% 66%, #6bc4ea17 0 14px, transparent 14px 28px);
            pointer-events: none;
            opacity: 0.95;
        }

        .arena-map::after {
            content: '';
            position: absolute;
            inset: 0;
            background: radial-gradient(120% 90% at 50% 50%, transparent 58%, #00122473 100%);
            pointer-events: none;
        }

        .arena-island {
            position: relative;
            z-index: 1;
            width: min(100%, 296px);
            border: 2px solid #8ecff7;
            border-radius: 34% 29% 31% 27% / 27% 36% 24% 33%;
            background:
                radial-gradient(100% 86% at 50% 0%, #76d26a 0%, #58b053 45%, #408e43 100%);
            box-shadow:
                0 0 0 3px #e4f3ff,
                0 0 0 9px #8a6c47,
                0 0 0 13px #543d25,
                0 12px 24px #00142e;
            padding: 22px 14px;
        }

        .arena-island::before {
            content: '';
            position: absolute;
            inset: 8px;
            border-radius: 29% 25% 27% 24% / 24% 33% 23% 29%;
            background:
                linear-gradient(135deg, #3f9348 0%, #4fab53 24%, #3f9348 58%, #357f3d 100%),
                repeating-linear-gradient(
                    90deg,
                    #ffffff0f 0,
                    #ffffff0f 1px,
                    transparent 1px,
                    transparent 32px
                ),
                repeating-linear-gradient(
                    180deg,
                    #00000010 0,
                    #00000010 1px,
                    transparent 1px,
                    transparent 32px
                );
            box-shadow: inset 0 0 0 1px #1e5b2d66;
            pointer-events: none;
        }

        .arena-island::after {
            content: '';
            position: absolute;
            inset: -2px;
            border-radius: 34% 29% 31% 27% / 27% 36% 24% 33%;
            box-shadow: inset 0 0 0 2px #fff5be66;
            pointer-events: none;
        }

        .arena-grid {
            position: relative;
            z-index: 2;
            display: grid;
            grid-template-columns: repeat(8, minmax(0, 1fr));
            column-gap: 6px;
            row-gap: 7px;
            align-items: end;
        }

        .arena-player {
            aspect-ratio: 1 / 1;
            border-radius: 0;
            border: 0;
            background: transparent;
            display: grid;
            place-items: end center;
            overflow: visible;
            padding: 0;
        }

        .arena-player.is-self {
            filter: drop-shadow(0 0 7px #ffd54aac);
        }
        .arena-player.is-dead {
            opacity: 0.28;
            filter: grayscale(1) saturate(0.2);
        }

        .arena-player.is-empty {
            border: 1px dashed #2a6a39;
            background: #1c4a28cc;
            border-radius: 9px;
            opacity: 0.5;
        }

        .arena-player-photo {
            width: 94%;
            height: 94%;
            object-fit: cover;
            object-position: 50% 26%;
            filter: drop-shadow(0 2px 3px #0008) saturate(1.1) brightness(1.05);
            border-radius: 0;
        }

        .arena-player-fallback {
            font-size: 0.9rem;
            line-height: 1;
            color: #ebf5ff;
        }

        .arena-player-fallback[hidden] {
            display: none !important;
        }

        .arena-footer {
            border: 1px solid #1f365d;
            border-radius: 12px;
            padding: 8px;
            background: linear-gradient(180deg, #0b1b34, #071226);
            display: grid;
            grid-template-columns: 48px 1fr;
            align-items: center;
            gap: 8px;
        }

        .arena-footer.is-dead {
            border-color: #6c2732;
            background: linear-gradient(180deg, #2a0f16, #1a0a10);
        }

        .arena-footer.is-dead .arena-avatar {
            border-color: #6b3a43;
            background: #2d1419;
        }

        .arena-footer.is-dead .arena-avatar-photo {
            filter: grayscale(1) saturate(0.15) brightness(0.82);
        }

        .arena-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            border: 1px solid #4768a8;
            background: #122751;
            display: grid;
            place-items: center;
            overflow: hidden;
        }

        .arena-avatar-photo {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .arena-avatar-fallback {
            font-size: 1.2rem;
            line-height: 1;
        }

        .arena-avatar-fallback[hidden] {
            display: none !important;
        }

        .arena-alive {
            margin: 0;
            color: #71ffa4;
            font-size: 1.34rem;
            font-family: 'Anton', sans-serif;
            letter-spacing: 0.35px;
            text-transform: uppercase;
        }

        .arena-footer.is-dead .arena-alive {
            color: #ff8ea1;
        }

        .arena-luck {
            margin: 0;
            color: #d4e4ff;
            font-size: 0.95rem;
            font-weight: 700;
        }

        .arena-footer.is-dead .arena-luck {
            color: #ffd0d8;
        }

        .arena-luck span {
            color: #96b8ff;
            font-weight: 600;
        }

        .bottom-nav {
            border-top: 1px solid var(--line);
            display: flex;
            justify-content: space-between;
            gap: 6px;
            padding-top: 10px;
        }

        .nav-item {
            flex: 1 1 0;
            text-align: center;
            color: #7f89b4;
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 600;
            display: grid;
            gap: 4px;
            justify-items: center;
        }

        .nav-item .ico {
            width: 30px;
            height: 30px;
            border-radius: 9px;
            border: 1px solid #2f3b75;
            background: #10173b;
            display: grid;
            place-items: center;
        }

        .nav-item.active {
            color: var(--yellow);
        }

        .nav-item.active .ico {
            border-color: #d5a800;
            background: #3f3205;
            color: #ffd141;
        }

        @keyframes rise {
            from {
                transform: translateY(12px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        @keyframes avatarPick {
            0% {
                transform: translateY(-6px) scale(0.98);
            }

            100% {
                transform: translateY(0) scale(1);
            }
        }

        @media (max-width: 520px) {
            .phone {
                min-height: calc(100dvh - 12px);
                gap: 10px;
            }

            #enterNowButton.cta {
                width: 100%;
                max-width: 100%;
                font-size: 1.56rem !important;
                padding: 1px 10px !important;
                min-height: 42px !important;
                line-height: 1 !important;
                border-radius: 12px;
            }
        }

        @media (max-width: 420px) {
            .phone {
                width: min(344px, 100%);
                min-height: 740px;
                border-radius: 26px;
                border: 1px solid #2f3c7a;
                padding: 12px 10px 10px;
            }

            .phone.avatar-mode {
                min-height: calc(100vh - 20px);
                padding: 6px 8px 8px;
            }

            .brand .logo {
                max-width: 214px;
                margin-top: -29px;
            }

            .countdown {
                font-size: 2.7rem;
            }

            #enterNowButton.cta {
                font-size: 1.48rem !important;
                padding: 1px 10px !important;
                border-radius: 12px;
                width: 100%;
                max-width: 100%;
                min-height: 40px !important;
            }

            .avatar-grid {
                grid-template-columns: repeat(5, minmax(0, 1fr));
            }

            .avatar-stage {
                min-height: 280px;
            }

            .avatar-preview-face {
                width: 200px;
                height: 200px;
            }

            .arena-map {
                min-height: 392px;
            }

            .arena-island {
                width: min(100%, 284px);
                padding: 20px 12px;
            }

            .arena-grid {
                column-gap: 5px;
                row-gap: 6px;
            }
        }

        @media (max-width: 360px) {
            .phone {
                width: min(330px, 100%);
                min-height: 720px;
            }

            #enterNowButton.cta {
                width: 100%;
                max-width: 100%;
                font-size: 1.36rem !important;
                padding: 0 9px !important;
                min-height: 38px !important;
            }

            .arena-map {
                min-height: 352px;
                padding: 8px;
            }

            .arena-island {
                width: min(100%, 262px);
                padding: 18px 10px;
            }

            .arena-alive {
                font-size: 1.2rem;
            }
        }

        @media (prefers-reduced-motion: reduce) {
            .cta {
                animation: none;
            }

            .meta.live-tag {
                animation: none;
            }

            .payment-status.is-waiting {
                animation: none;
            }

            .payment-status.is-waiting::after {
                animation: none;
                width: 1.9ch;
            }

            .avatar-preview-face.is-picked {
                animation: none;
            }

            .meta.live-tag::before,
            .meta.live-tag::after {
                animation: none;
            }
        }
    </style>
</head>
<body data-next-round-at="<?php echo e($lobby['next_round_at']); ?>" data-live-endpoint="<?php echo e(route('game.live')); ?>">
    <main class="phone">
        <header class="top">
            <div class="icon-btn" aria-hidden="true">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
            </div>
            <form method="post" action="<?php echo e(route('logout')); ?>">
                <?php echo csrf_field(); ?>
                <button class="icon-btn logout" type="submit" title="Sair" aria-label="Sair">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M16 17v1a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1M10 12h10m0 0-3-3m3 3-3 3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
                </button>
            </form>
        </header>

        <section class="brand">
            <img class="logo" src="<?php echo e(asset('images/survive-logo.png')); ?>?v=3" alt="Survive - Só 1 pode ganhar!" decoding="async">
            <span class="sr-only">Survive - Só 1 pode ganhar!</span>
        </section>

        <section class="round" data-tab-view="home">
            <p class="label">Próxima rodada</p>
            <p class="countdown" id="countdown"><?php echo e($lobby['countdown']); ?></p>
            <p class="when" id="nextRoundLabel"><?php echo e($lobby['next_round_label']); ?></p>
        </section>

        <section class="city-pill" data-tab-view="home">
            Disputa da cidade: <?php echo e($player?->city && $player?->state ? $player->city . '/' . $player->state : ($player->city ?? $lobby['city'])); ?>

        </section>

        <section class="stats" data-tab-view="home">
            <article class="stat">
                <div class="label">Jogadores</div>
                <div class="value" id="playersOnline"><?php echo e($lobby['players_online_formatted']); ?></div>
                <div class="meta live-tag">Ao vivo</div>
            </article>
            <article class="stat">
                <div class="label">Prêmio</div>
                <div class="value green" id="estimatedPrize"><?php echo e($lobby['estimated_prize_brl']); ?></div>
                <div class="meta">Estimado</div>
            </article>
        </section>

        <button id="enterNowButton" class="cta" type="button" data-tab-view="home">Entrar agora</button>
        <p class="entry-fee" id="entryFee" data-tab-view="home"><?php echo e($lobby['entry_price_brl']); ?> por entrada</p>
        <button id="installApp" class="install" type="button" data-tab-view="home" hidden>Instalar aplicativo</button>

        <section id="paymentOverlay" class="payment-overlay" hidden aria-hidden="true">
            <article class="payment-sheet" role="dialog" aria-modal="true" aria-labelledby="paymentTitle">
                <button id="paymentClose" class="payment-close" type="button" aria-label="Fechar pagamento">×</button>
                <p id="paymentStatus" class="payment-status">Aguardando pagamento</p>
                <h2 id="paymentTitle" class="payment-title">Pague com PIX</h2>
                <p class="payment-subtitle">Escaneie o QR Code ou use o link copia e cola abaixo.</p>
                <div class="payment-qr-wrap">
                    <img id="paymentQr" class="payment-qr" alt="QR Code PIX para pagamento" loading="lazy" decoding="async">
                </div>
                <label class="payment-label" for="paymentCopyCode">Link copia e cola</label>
                <textarea id="paymentCopyCode" class="payment-copy" readonly></textarea>
                <div class="payment-actions">
                    <button id="copyPixButton" class="payment-copy-btn" type="button">Copiar código</button>
                    <button id="confirmDigitalPaymentButton" class="payment-confirm-btn" type="button">Já paguei</button>
                    <span id="paymentFeedback" class="payment-feedback" aria-live="polite"></span>
                </div>
                <p id="paymentMeta" class="payment-meta"></p>
            </article>
        </section>

        <section class="tab-card tab-hidden" data-tab-view="rooms">
            <section id="roomsAvatarCard" class="avatar-shell">
                <header class="avatar-header">
                    <button id="avatarBackButton" class="avatar-back-btn" type="button" aria-label="Voltar para início">‹</button>
                    <h2 class="avatar-header-title">Escolha Seu Avatar</h2>
                    <span aria-hidden="true"></span>
                </header>

                <section class="avatar-stage">
                    <div class="avatar-preview">
                        <div id="avatarPreviewFace" class="avatar-preview-face" aria-hidden="true">
                            <img id="avatarPreviewPhoto" class="avatar-preview-photo" alt="" loading="lazy" decoding="async">
                            <span id="avatarPreviewFallback" class="avatar-preview-fallback" hidden>😀</span>
                        </div>
                        <p id="avatarPreviewText" class="avatar-preview-text">Selecionado: Bombeira</p>
                    </div>
                </section>

                <div class="avatar-filters" role="tablist" aria-label="Filtro de avatar">
                    <button type="button" class="avatar-filter-btn active" data-avatar-filter="todos">Todos</button>
                    <button type="button" class="avatar-filter-btn" data-avatar-filter="raros">Raros</button>
                    <button type="button" class="avatar-filter-btn" data-avatar-filter="epicos">Épicos</button>
                    <button type="button" class="avatar-filter-btn" data-avatar-filter="lendarios">Lendários</button>
                </div>

                <div id="avatarGrid" class="avatar-grid" aria-label="Lista de avatares"></div>
                <button id="confirmAvatarButton" class="avatar-confirm" type="button">Confirmar avatar</button>
                <p id="avatarNote" class="avatar-note" aria-live="polite"></p>
            </section>
        </section>

        <section class="tab-card tab-hidden" data-tab-view="arena">
            <section class="arena-shell">
                <header class="arena-head">
                    <button id="arenaBackButton" class="arena-back-btn" type="button" aria-label="Voltar para início">‹</button>
                    <h2 id="arenaRoundLabel" class="arena-title">Mapa - Rodada #152</h2>
                    <span aria-hidden="true"></span>
                </header>

                <div class="arena-status">
                    <span class="arena-badge live">Ao vivo</span>
                    <span id="arenaRoundStage" class="arena-badge">Rodada 1 de 10</span>
                    <span id="arenaRemaining" class="arena-badge rest">Restantes: 1.256</span>
                </div>

                <section class="arena-map" aria-label="Mapa da rodada">
                    <div class="arena-island">
                        <div id="arenaGrid" class="arena-grid" aria-label="Jogadores no mapa"></div>
                    </div>
                </section>

                <footer class="arena-footer">
                    <div class="arena-avatar" aria-hidden="true">
                        <img id="arenaAlivePhoto" class="arena-avatar-photo" alt="" loading="lazy" decoding="async">
                        <span id="arenaAliveFallback" class="arena-avatar-fallback" hidden>🙂</span>
                    </div>
                    <div>
                        <p class="arena-alive">Você está vivo!</p>
                        <p class="arena-luck">Boa sorte! <span id="arenaAliveName">Avatar ativo: --</span></p>
                    </div>
                </footer>
            </section>
        </section>

        <section class="tab-card tab-hidden" data-tab-view="invite">
            <h2 class="title">Indicar Amigos</h2>
            <p class="text">Compartilhe seu convite e traga mais jogadores para a sua cidade.</p>
            <p class="text">Sua disputa local fica mais dinâmica com mais participantes online.</p>
        </section>

        <section class="tab-card tab-hidden" data-tab-view="profile">
            <h2 class="title">Perfil</h2>
            <p class="text">Jogador: <?php echo e($player?->name ?? 'Usuário'); ?></p>
            <p class="text">Local: <?php echo e($player?->city && $player?->state ? $player->city . '/' . $player->state : 'Não informado'); ?></p>
            <p class="text" id="profileAvatar">Avatar: Bombeira</p>
        </section>

        <nav class="bottom-nav" aria-label="Navegação principal">
            <a href="#" class="nav-item active" data-tab="home" aria-current="page">
                <span class="ico">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 3 2 10h3v10h6v-6h2v6h6V10h3L12 3Z" fill="currentColor"/></svg>
                </span>
                Início
            </a>
            <a href="#" class="nav-item" data-tab="rooms">
                <span class="ico">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M7 7h10v10H7V7Zm-4 8V9a2 2 0 0 1 2-2h2v2H5v6h2v2H5a2 2 0 0 1-2-2Zm16 2v-2h2V9h-2V7h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2Z" fill="currentColor"/></svg>
                </span>
                Minhas Salas
            </a>
            <a href="#" class="nav-item" data-tab="invite">
                <span class="ico">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M15 8a3 3 0 1 1 0 6 3 3 0 0 1 0-6Zm-6-4a3 3 0 1 1 0 6 3 3 0 0 1 0-6Zm0 10a3 3 0 1 1 0 6 3 3 0 0 1 0-6Zm10 1h3v2h-3v3h-2v-3h-3v-2h3v-3h2v3ZM9 12c-2.22 0-4 1.79-4 4v2h7.5a4.5 4.5 0 0 1 .5-2.06A4 4 0 0 0 9 12Zm0-10C6.24 2 4 4.24 4 7v2h5a4.98 4.98 0 0 1 3.53 1.47A4.98 4.98 0 0 1 16.06 9H19V7c0-2.76-2.24-5-5-5H9Z" fill="currentColor"/></svg>
                </span>
                Indicar
            </a>
            <a href="#" class="nav-item" data-tab="profile">
                <span class="ico">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 12a5 5 0 1 0-5-5 5 5 0 0 0 5 5Zm0 2c-4.42 0-8 2.24-8 5v2h16v-2c0-2.76-3.58-5-8-5Z" fill="currentColor"/></svg>
                </span>
                Perfil
            </a>
        </nav>
    </main>

    <script id="pixCheckoutData" type="application/json"><?php echo json_encode($pixCheckout, 15, 512) ?></script>
    <script id="selectedAvatarIdData" type="application/json"><?php echo json_encode($selectedAvatarId, 15, 512) ?></script>
    <script id="arenaData" type="application/json"><?php echo json_encode($arena, 15, 512) ?></script>

    <script>
        (() => {
            const state = {
                nextRoundAt: new Date(document.body.dataset.nextRoundAt).getTime(),
            };

            const countdownEl = document.getElementById('countdown');
            const nextRoundLabelEl = document.getElementById('nextRoundLabel');
            const playersOnlineEl = document.getElementById('playersOnline');
            const estimatedPrizeEl = document.getElementById('estimatedPrize');
            const entryFeeEl = document.getElementById('entryFee');
            const enterNowButton = document.getElementById('enterNowButton');
            const paymentOverlay = document.getElementById('paymentOverlay');
            const paymentClose = document.getElementById('paymentClose');
            const paymentStatus = document.getElementById('paymentStatus');
            const paymentQr = document.getElementById('paymentQr');
            const paymentCopyCode = document.getElementById('paymentCopyCode');
            const paymentMeta = document.getElementById('paymentMeta');
            const copyPixButton = document.getElementById('copyPixButton');
            const confirmDigitalPaymentButton = document.getElementById('confirmDigitalPaymentButton');
            const paymentFeedback = document.getElementById('paymentFeedback');
            const roomsAvatarCard = document.getElementById('roomsAvatarCard');
            const avatarPreviewFace = document.getElementById('avatarPreviewFace');
            const avatarPreviewPhoto = document.getElementById('avatarPreviewPhoto');
            const avatarPreviewFallback = document.getElementById('avatarPreviewFallback');
            const avatarPreviewText = document.getElementById('avatarPreviewText');
            const avatarGrid = document.getElementById('avatarGrid');
            const avatarBackButton = document.getElementById('avatarBackButton');
            const confirmAvatarButton = document.getElementById('confirmAvatarButton');
            const avatarNote = document.getElementById('avatarNote');
            const profileAvatar = document.getElementById('profileAvatar');
            const arenaGrid = document.getElementById('arenaGrid');
            const arenaBackButton = document.getElementById('arenaBackButton');
            const arenaRoundLabel = document.getElementById('arenaRoundLabel');
            const arenaRoundStage = document.getElementById('arenaRoundStage');
            const arenaRemaining = document.getElementById('arenaRemaining');
            const arenaAlivePhoto = document.getElementById('arenaAlivePhoto');
            const arenaAliveFallback = document.getElementById('arenaAliveFallback');
            const arenaAliveName = document.getElementById('arenaAliveName');
            const arenaAliveStatus = document.querySelector('.arena-alive');
            const arenaFooter = document.querySelector('.arena-footer');
            const avatarFilterButtons = Array.from(document.querySelectorAll('.avatar-filter-btn[data-avatar-filter]'));
            const tabItems = Array.from(document.querySelectorAll('.bottom-nav .nav-item[data-tab]'));
            const tabViews = Array.from(document.querySelectorAll('[data-tab-view]'));
            const pixCheckoutRaw = document.getElementById('pixCheckoutData')?.textContent || '{}';
            const selectedAvatarRaw = document.getElementById('selectedAvatarIdData')?.textContent || 'null';
            const arenaRaw = document.getElementById('arenaData')?.textContent || '{}';
            const phone = document.querySelector('.phone');
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
            const saveAvatarEndpoint = "<?php echo e(route('game.avatar.save')); ?>";
            const arenaLiveEndpoint = "<?php echo e(route('game.arena.live')); ?>";

            let pixCheckout;
            let serverSelectedAvatarId = null;
            let arenaData;

            try {
                pixCheckout = JSON.parse(pixCheckoutRaw);
            } catch (error) {
                pixCheckout = {};
            }

            try {
                serverSelectedAvatarId = JSON.parse(selectedAvatarRaw);
            } catch (error) {
                serverSelectedAvatarId = null;
            }

            try {
                arenaData = JSON.parse(arenaRaw);
            } catch (error) {
                arenaData = {};
            }

            const liveEndpoint = document.body.dataset.liveEndpoint;
            let activePaymentRef = null;
            const avatarStorageKey = 'survive.avatar.selection';
            const avatarProcessedCache = new Map();
            let avatarPreviewVersion = 0;
            let arenaSyncInFlight = false;
            const avatarCatalog = [
                { id: 'bombeira', label: 'Bombeira', tier: 'raros', image: "<?php echo e(asset('images/avatars/bombeira.png')); ?>", fallback: '🚒' },
                { id: 'operario', label: 'Operário', tier: 'todos', image: "<?php echo e(asset('images/avatars/operario.png')); ?>", fallback: '👷' },
                { id: 'enfermeira', label: 'Enfermeira', tier: 'raros', image: "<?php echo e(asset('images/avatars/enfermeira.png')); ?>", fallback: '👩‍⚕️' },
                { id: 'medico', label: 'Médico', tier: 'epicos', image: "<?php echo e(asset('images/avatars/medico.png')); ?>", fallback: '👨‍⚕️' },
                { id: 'ninja', label: 'Ninja', tier: 'epicos', image: "<?php echo e(asset('images/avatars/ninja.png')); ?>", fallback: '🥷' },
                { id: 'pirata', label: 'Pirata', tier: 'epicos', image: "<?php echo e(asset('images/avatars/pirata.png')); ?>", fallback: '🏴‍☠️' },
                { id: 'astronauta', label: 'Astronauta', tier: 'lendarios', image: "<?php echo e(asset('images/avatars/astronauta.png')); ?>", fallback: '👨‍🚀' },
                { id: 'vampiro', label: 'Vampiro', tier: 'lendarios', image: "<?php echo e(asset('images/avatars/vampiro.png')); ?>", fallback: '🧛' },
                { id: 'fantasma', label: 'Fantasma', tier: 'lendarios', image: "<?php echo e(asset('images/avatars/fantasma.png')); ?>", fallback: '👻' },
                { id: 'rei', label: 'Rei', tier: 'lendarios', image: "<?php echo e(asset('images/avatars/rei.png')); ?>", fallback: '👑' },
            ];
            let activeAvatarFilter = 'todos';
            let selectedAvatarId = 'bombeira';

            const setActiveTab = (tab) => {
                phone.classList.toggle('avatar-mode', tab === 'rooms');
                phone.classList.toggle('arena-mode', tab === 'arena');

                tabItems.forEach((item) => {
                    const isActive = item.dataset.tab === tab;
                    item.classList.toggle('active', isActive);
                    if (isActive) {
                        item.setAttribute('aria-current', 'page');
                    } else {
                        item.removeAttribute('aria-current');
                    }
                });

                tabViews.forEach((view) => {
                    const shouldShow = view.dataset.tabView === tab;
                    view.classList.toggle('tab-hidden', !shouldShow);
                });
            };

            const removeWhiteBackground = (imageUrl) => {
                if (avatarProcessedCache.has(imageUrl)) {
                    return avatarProcessedCache.get(imageUrl);
                }

                const task = new Promise((resolve) => {
                    const image = new Image();

                    image.onload = () => {
                        const canvas = document.createElement('canvas');
                        canvas.width = image.naturalWidth;
                        canvas.height = image.naturalHeight;

                        const context = canvas.getContext('2d', { willReadFrequently: true });

                        if (!context) {
                            resolve(imageUrl);
                            return;
                        }

                        context.drawImage(image, 0, 0);

                        const frame = context.getImageData(0, 0, canvas.width, canvas.height);
                        const pixels = frame.data;
                        const canvasWidth = canvas.width;

                        let minX = canvas.width;
                        let minY = canvas.height;
                        let maxX = -1;
                        let maxY = -1;

                        for (let index = 0; index < pixels.length; index += 4) {
                            const red = pixels[index];
                            const green = pixels[index + 1];
                            const blue = pixels[index + 2];
                            const alpha = pixels[index + 3];

                            if (alpha === 0) {
                                continue;
                            }

                            const maxChannel = Math.max(red, green, blue);
                            const minChannel = Math.min(red, green, blue);
                            const spread = maxChannel - minChannel;
                            const average = (red + green + blue) / 3;

                            // Remove fundo branco e suaviza bordas quase brancas.
                            if (average > 246 && spread < 18) {
                                pixels[index + 3] = 0;
                                continue;
                            }

                            if (average > 232 && spread < 24) {
                                const fade = Math.max(0, Math.min(1, (246 - average) / 14));
                                pixels[index + 3] = Math.round(alpha * fade);
                            }

                            const normalizedAlpha = pixels[index + 3];

                            if (normalizedAlpha > 3) {
                                const point = index / 4;
                                const x = point % canvasWidth;
                                const y = Math.floor(point / canvasWidth);

                                if (x < minX) {
                                    minX = x;
                                }

                                if (x > maxX) {
                                    maxX = x;
                                }

                                if (y < minY) {
                                    minY = y;
                                }

                                if (y > maxY) {
                                    maxY = y;
                                }
                            }
                        }

                        context.putImageData(frame, 0, 0);

                        if (maxX < minX || maxY < minY) {
                            resolve(canvas.toDataURL('image/png'));
                            return;
                        }

                        const contentWidth = maxX - minX + 1;
                        const contentHeight = maxY - minY + 1;
                        const padding = Math.round(Math.max(contentWidth, contentHeight) * 0.08);
                        const cropX = Math.max(0, minX - padding);
                        const cropY = Math.max(0, minY - padding);
                        const cropWidth = Math.min(canvas.width - cropX, contentWidth + padding * 2);
                        const cropHeight = Math.min(canvas.height - cropY, contentHeight + padding * 2);

                        const croppedCanvas = document.createElement('canvas');
                        croppedCanvas.width = cropWidth;
                        croppedCanvas.height = cropHeight;

                        const croppedContext = croppedCanvas.getContext('2d');

                        if (!croppedContext) {
                            resolve(canvas.toDataURL('image/png'));
                            return;
                        }

                        croppedContext.drawImage(
                            canvas,
                            cropX,
                            cropY,
                            cropWidth,
                            cropHeight,
                            0,
                            0,
                            cropWidth,
                            cropHeight
                        );

                        resolve(croppedCanvas.toDataURL('image/png'));
                    };

                    image.onerror = () => {
                        resolve(null);
                    };

                    image.src = imageUrl;
                });

                avatarProcessedCache.set(imageUrl, task);

                return task;
            };

            const applyAvatarImage = async (imageElement, fallbackElement, avatar) => {
                const source = avatar.image;
                imageElement.dataset.source = source;
                imageElement.hidden = true;
                fallbackElement.hidden = true;
                fallbackElement.textContent = avatar.fallback;

                const processed = await removeWhiteBackground(source);

                if (imageElement.dataset.source !== source) {
                    return;
                }

                if (!processed) {
                    imageElement.hidden = true;
                    fallbackElement.hidden = false;
                    return;
                }

                imageElement.src = processed;
                imageElement.hidden = false;
                fallbackElement.hidden = true;
            };

            const getAvatarById = (id) => {
                return avatarCatalog.find((avatar) => avatar.id === id) || avatarCatalog[0];
            };

            const formatTier = (tier) => {
                const map = {
                    todos: 'Comum',
                    raros: 'Raro',
                    epicos: 'Épico',
                    lendarios: 'Lendário',
                };

                return map[tier] || 'Comum';
            };

            const persistAvatarLocal = () => {
                try {
                    localStorage.setItem(avatarStorageKey, selectedAvatarId);
                } catch (error) {
                    // Sem bloqueio se localStorage estiver indisponível.
                }
            };

            const loadSavedAvatar = () => {
                if (serverSelectedAvatarId && avatarCatalog.some((avatar) => avatar.id === serverSelectedAvatarId)) {
                    selectedAvatarId = serverSelectedAvatarId;
                    persistAvatarLocal();
                    return;
                }

                try {
                    const savedAvatarId = localStorage.getItem(avatarStorageKey);

                    if (savedAvatarId && avatarCatalog.some((avatar) => avatar.id === savedAvatarId)) {
                        selectedAvatarId = savedAvatarId;
                    }
                } catch (error) {
                    // Mantém avatar padrão quando localStorage falha.
                }
            };

            const persistAvatarOnServer = async () => {
                if (!csrfToken || !saveAvatarEndpoint) {
                    return {
                        ok: false,
                        message: 'Token de segurança não encontrado.',
                    };
                }

                try {
                    const response = await fetch(saveAvatarEndpoint, {
                        method: 'POST',
                        headers: {
                            Accept: 'application/json',
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken,
                        },
                        body: JSON.stringify({ avatar_id: selectedAvatarId }),
                    });

                    const payload = await response.json().catch(() => ({}));

                    if (!response.ok || payload.ok !== true) {
                        return {
                            ok: false,
                            message: payload.message || 'Não foi possível salvar no servidor agora.',
                        };
                    }

                    serverSelectedAvatarId = payload.avatar_id || selectedAvatarId;

                    if (payload.arena && typeof payload.arena === 'object') {
                        arenaData = payload.arena;
                    }

                    return {
                        ok: true,
                        message: payload.message || 'Avatar salvo com sucesso.',
                    };
                } catch (error) {
                    return {
                        ok: false,
                        message: 'Sem conexão. Seu avatar ficou salvo localmente.',
                    };
                }
            };

            const updateAvatarPreview = async () => {
                const currentAvatar = getAvatarById(selectedAvatarId);
                const currentVersion = ++avatarPreviewVersion;
                avatarPreviewText.textContent = `Selecionado: ${currentAvatar.label} • ${formatTier(currentAvatar.tier)}`;
                profileAvatar.textContent = `Avatar: ${currentAvatar.label}`;

                avatarPreviewFace.classList.add('is-switching');
                avatarPreviewFace.classList.remove('is-picked');
                void avatarPreviewFace.offsetWidth;
                avatarPreviewFace.classList.add('is-picked');

                await applyAvatarImage(avatarPreviewPhoto, avatarPreviewFallback, currentAvatar);

                if (currentVersion !== avatarPreviewVersion) {
                    return;
                }

                avatarPreviewFace.classList.remove('is-switching');
            };

            const renderAvatarGrid = () => {
                const list = avatarCatalog.filter((avatar) => {
                    return activeAvatarFilter === 'todos' || avatar.tier === activeAvatarFilter;
                });

                avatarGrid.innerHTML = '';

                list.forEach((avatar) => {
                    const button = document.createElement('button');
                    button.type = 'button';
                    button.className = 'avatar-option';
                    button.dataset.avatarId = avatar.id;

                    if (avatar.id === selectedAvatarId) {
                        button.classList.add('selected');
                    }

                    button.setAttribute('aria-label', `Avatar ${avatar.label}`);
                    button.title = avatar.label;

                    const image = document.createElement('img');
                    image.className = 'avatar-option-photo';
                    image.alt = '';
                    image.loading = 'lazy';
                    image.decoding = 'async';

                    const fallback = document.createElement('span');
                    fallback.className = 'avatar-option-fallback';
                    fallback.textContent = avatar.fallback;
                    fallback.hidden = true;

                    button.appendChild(image);
                    button.appendChild(fallback);

                    applyAvatarImage(image, fallback, avatar);

                    avatarGrid.appendChild(button);
                });
            };

            const setAvatarFilter = (filter) => {
                activeAvatarFilter = filter;

                avatarFilterButtons.forEach((button) => {
                    button.classList.toggle('active', button.dataset.avatarFilter === filter);
                });

                renderAvatarGrid();
            };

            const normalizeArenaData = () => {
                if (!arenaData || typeof arenaData !== 'object') {
                    arenaData = {};
                }

                if (!Array.isArray(arenaData.players)) {
                    arenaData.players = [];
                }

                const gridSizeRaw = Number.parseInt(arenaData.grid_size, 10);
                arenaData.grid_size = Number.isFinite(gridSizeRaw) && gridSizeRaw > 0 ? gridSizeRaw : 64;

                const remainingRaw = Number.parseInt(arenaData.remaining_players, 10);
                arenaData.remaining_players = Number.isFinite(remainingRaw) && remainingRaw > 0 ? remainingRaw : 1;

                const stageTotalRaw = Number.parseInt(arenaData.round_stage_total, 10);
                arenaData.round_stage_total = Number.isFinite(stageTotalRaw) && stageTotalRaw > 0 ? stageTotalRaw : 10;

                const stageCurrentRaw = Number.parseInt(arenaData.round_stage, 10);
                arenaData.round_stage = Number.isFinite(stageCurrentRaw) && stageCurrentRaw > 0
                    ? stageCurrentRaw
                    : 1;

                if (typeof arenaData.round_label !== 'string' || arenaData.round_label.trim() === '') {
                    arenaData.round_label = 'Mapa - Rodada #1';
                }
            };

            const syncArenaSelfPlayer = () => {
                normalizeArenaData();

                const currentUserId = Number.parseInt(arenaData.current_user_id, 10);
                const hasCurrentUserId = Number.isFinite(currentUserId) && currentUserId > 0;

                let selfIndex = arenaData.players.findIndex((player) => player && player.is_self === true);

                if (selfIndex === -1 && hasCurrentUserId) {
                    selfIndex = arenaData.players.findIndex((player) => {
                        if (!player || player.user_id === null || player.user_id === undefined) {
                            return false;
                        }

                        return Number.parseInt(player.user_id, 10) === currentUserId;
                    });
                }

                const selfPlayer = {
                    user_id: hasCurrentUserId ? currentUserId : null,
                    name: 'Você',
                    avatar_id: selectedAvatarId,
                    is_self: true,
                };

                if (selfIndex >= 0) {
                    arenaData.players[selfIndex] = {
                        ...arenaData.players[selfIndex],
                        ...selfPlayer,
                    };
                } else {
                    const emptyIndex = arenaData.players.findIndex((player) => !player || !player.avatar_id);

                    if (emptyIndex >= 0) {
                        arenaData.players[emptyIndex] = selfPlayer;
                    } else {
                        arenaData.players.unshift(selfPlayer);
                    }
                }

                arenaData.players = arenaData.players.slice(0, arenaData.grid_size);
            };

            const resolveArenaAvatar = (avatarId, index) => {
                if (!avatarId) {
                    return avatarCatalog[index % avatarCatalog.length];
                }

                const byId = avatarCatalog.find((avatar) => avatar.id === avatarId);

                if (byId) {
                    return byId;
                }

                return avatarCatalog[index % avatarCatalog.length];
            };

            const renderArena = () => {
                if (!arenaGrid) {
                    return;
                }

                normalizeArenaData();
                syncArenaSelfPlayer();
                arenaGrid.innerHTML = '';

                const fragment = document.createDocumentFragment();
                const maxSlots = arenaData.grid_size;
                let selfIsAlive = true;
                let selfFound = false;

                for (let index = 0; index < maxSlots; index += 1) {
                    const player = arenaData.players[index] || null;
                    const avatar = resolveArenaAvatar(player?.avatar_id || null, index);
                    const tile = document.createElement('div');
                    tile.className = 'arena-player';

                    if (player?.is_self) {
                        tile.classList.add('is-self');
                        selfFound = true;
                        selfIsAlive = player.is_alive !== false;
                    }

                    if (player && player.is_alive === false) {
                        tile.classList.add('is-dead');
                    }

                    tile.setAttribute('aria-label', player?.name ? `Jogador ${player.name}` : 'Jogador');

                    const image = document.createElement('img');
                    image.className = 'arena-player-photo';
                    image.alt = '';
                    image.loading = 'lazy';
                    image.decoding = 'async';

                    const fallback = document.createElement('span');
                    fallback.className = 'arena-player-fallback';
                    fallback.textContent = avatar?.fallback || '🙂';
                    fallback.hidden = true;

                    tile.appendChild(image);
                    tile.appendChild(fallback);

                    applyAvatarImage(image, fallback, avatar);

                    fragment.appendChild(tile);
                }

                if (!selfFound) {
                    const winnerUserId = Number.parseInt(arenaData.winner_user_id, 10);
                    const currentUserId = Number.parseInt(arenaData.current_user_id, 10);

                    if (
                        arenaData.round_status === 'closed' &&
                        Number.isFinite(winnerUserId) &&
                        Number.isFinite(currentUserId) &&
                        winnerUserId !== currentUserId
                    ) {
                        selfIsAlive = false;
                    }
                }

                arenaGrid.appendChild(fragment);

                if (arenaRoundLabel) {
                    arenaRoundLabel.textContent = arenaData.round_label;
                }

                if (arenaRoundStage) {
                    arenaRoundStage.textContent = `Rodada ${arenaData.round_stage} de ${arenaData.round_stage_total}`;
                }

                if (arenaRemaining) {
                    arenaRemaining.textContent = `Restantes: ${arenaData.remaining_players.toLocaleString('pt-BR')}`;
                }

                const selectedAvatar = getAvatarById(selectedAvatarId);

                if (arenaFooter) {
                    arenaFooter.classList.toggle('is-dead', !selfIsAlive);
                }

                if (arenaAliveStatus) {
                    arenaAliveStatus.textContent = selfIsAlive
                        ? 'Você está vivo!'
                        : 'Você morreu. Tente novamente.';
                }

                if (arenaAliveName) {
                    arenaAliveName.textContent = selfIsAlive
                        ? `Avatar ativo: ${selectedAvatar.label}`
                        : 'Sua rodada terminou.';
                }

                if (arenaAlivePhoto && arenaAliveFallback) {
                    applyAvatarImage(arenaAlivePhoto, arenaAliveFallback, selectedAvatar);
                }
            };

            const refreshArenaLive = async () => {
                if (!arenaLiveEndpoint || arenaSyncInFlight) {
                    return;
                }

                arenaSyncInFlight = true;

                try {
                    const response = await fetch(arenaLiveEndpoint, {
                        headers: { Accept: 'application/json' },
                        cache: 'no-store',
                    });

                    if (!response.ok) {
                        return;
                    }

                    const payload = await response.json();

                    if (!payload || payload.ok !== true || !payload.arena) {
                        return;
                    }

                    arenaData = payload.arena;

                    if (phone.classList.contains('arena-mode')) {
                        renderArena();
                    }
                } catch (error) {
                    // Mantém tela local em caso de falha de conexão.
                } finally {
                    arenaSyncInFlight = false;
                }
            };

            const activateAvatarSelectionFromPayment = () => {
                setActiveTab('rooms');
                roomsAvatarCard.classList.remove('highlight');
                void roomsAvatarCard.offsetWidth;
                roomsAvatarCard.classList.add('highlight');
                avatarNote.textContent = 'Pagamento confirmado. Agora escolha seu avatar.';
            };

            tabItems.forEach((item) => {
                item.addEventListener('click', (event) => {
                    event.preventDefault();
                    setActiveTab(item.dataset.tab);
                });
            });

            setActiveTab('home');

            const formatCountdown = (targetMs) => {
                const diffSeconds = Math.max(0, Math.floor((targetMs - Date.now()) / 1000));
                const hours = Math.floor(diffSeconds / 3600);
                const minutes = Math.floor((diffSeconds % 3600) / 60);
                const seconds = diffSeconds % 60;

                return [hours, minutes, seconds]
                    .map((part) => String(part).padStart(2, '0'))
                    .join(':');
            };

            const adjustPrizeTypography = () => {
                const prizeText = estimatedPrizeEl.textContent.trim();
                const normalized = prizeText.replace(/\s/g, '');

                if (normalized.length >= 10) {
                    estimatedPrizeEl.classList.add('compact');
                } else {
                    estimatedPrizeEl.classList.remove('compact');
                }
            };

            const emvField = (id, value) => `${id}${String(value.length).padStart(2, '0')}${value}`;

            const normalizePixText = (value, maxLength) => {
                const normalized = String(value || '')
                    .normalize('NFD')
                    .replace(/[\u0300-\u036f]/g, '')
                    .toUpperCase()
                    .replace(/[^A-Z0-9 ]/g, ' ')
                    .replace(/\s+/g, ' ')
                    .trim();

                return normalized.slice(0, maxLength);
            };

            const crc16 = (payload) => {
                let crc = 0xFFFF;

                for (let i = 0; i < payload.length; i += 1) {
                    crc ^= payload.charCodeAt(i) << 8;

                    for (let bit = 0; bit < 8; bit += 1) {
                        crc = (crc & 0x8000) !== 0
                            ? ((crc << 1) ^ 0x1021)
                            : (crc << 1);
                        crc &= 0xFFFF;
                    }
                }

                return crc.toString(16).toUpperCase().padStart(4, '0');
            };

            const buildPixPayload = () => {
                const pixKey = String(pixCheckout.pix_key || '').trim();

                if (!pixKey) {
                    return null;
                }

                const merchantName = normalizePixText(pixCheckout.pix_key_holder || 'SURVIVE JOGO', 25) || 'SURVIVE JOGO';
                const merchantCity = normalizePixText(pixCheckout.location || 'RECIFE', 15) || 'RECIFE';
                const amount = Number(pixCheckout.amount || 5).toFixed(2);
                const txid = 'SURVIVEPIX';

                const merchantAccount = emvField('26',
                    emvField('00', 'BR.GOV.BCB.PIX') +
                    emvField('01', pixKey)
                );

                const additionalData = emvField('62', emvField('05', txid));
                const payloadNoCrc =
                    emvField('00', '01') +
                    merchantAccount +
                    emvField('52', '0000') +
                    emvField('53', '986') +
                    emvField('54', amount) +
                    emvField('58', 'BR') +
                    emvField('59', merchantName) +
                    emvField('60', merchantCity) +
                    additionalData +
                    '6304';

                return payloadNoCrc + crc16(payloadNoCrc);
            };

            const formatAmount = (value) => {
                return Number(value || 0).toLocaleString('pt-BR', {
                    style: 'currency',
                    currency: 'BRL',
                });
            };

            const setPaymentStatus = (value) => {
                const statusText = String(value || 'Aguardando pagamento').trim() || 'Aguardando pagamento';
                paymentStatus.textContent = statusText;
                paymentStatus.classList.toggle('is-waiting', /^(aguardando pagamento|processando pagamento)/i.test(statusText));
                paymentStatus.classList.toggle('is-approved', /^pagamento aprovado/i.test(statusText));
            };

            const createDigitalCode = () => {
                const amount = Number(pixCheckout.amount || 5).toFixed(2);
                const reference = `SURVIVE-${Date.now()}`;
                const holder = String(pixCheckout.pix_key_holder || 'SURVIVE JOGO').trim() || 'SURVIVE JOGO';
                const location = String(pixCheckout.location || 'RECIFE').trim() || 'RECIFE';

                return {
                    code: `SURVIVE|DIGITAL|REF:${reference}|VALOR:${amount}|PORTADOR:${holder}|LOCAL:${location}`,
                    reference,
                };
            };

            const openPayment = () => {
                setPaymentStatus(pixCheckout.status || 'Aguardando pagamento');

                const pixPayload = buildPixPayload();
                const digitalData = createDigitalCode();
                activePaymentRef = digitalData.reference;

                if (!pixPayload) {
                    paymentCopyCode.value = digitalData.code;
                    paymentQr.src = `https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=${encodeURIComponent(digitalData.code)}`;
                    paymentMeta.textContent = `Pagamento digital ativo • Ref: ${digitalData.reference} • Valor: ${formatAmount(pixCheckout.amount)}`;
                } else {
                    paymentCopyCode.value = pixPayload;
                    paymentQr.src = `https://api.qrserver.com/v1/create-qr-code/?size=280x280&data=${encodeURIComponent(pixPayload)}`;
                    paymentMeta.textContent = `Ref: ${digitalData.reference} • Valor: ${formatAmount(pixCheckout.amount)} • ${pixCheckout.pix_key_holder || 'SURVIVE JOGO'}`;
                }

                paymentFeedback.textContent = '';
                copyPixButton.disabled = false;
                confirmDigitalPaymentButton.disabled = false;
                paymentOverlay.hidden = false;
                paymentOverlay.setAttribute('aria-hidden', 'false');
                paymentCopyCode.focus();
                paymentCopyCode.select();
            };

            const closePayment = () => {
                paymentOverlay.hidden = true;
                paymentOverlay.setAttribute('aria-hidden', 'true');
                paymentFeedback.textContent = '';
            };

            const confirmDigitalPayment = () => {
                confirmDigitalPaymentButton.disabled = true;
                copyPixButton.disabled = true;
                setPaymentStatus('Processando pagamento');
                paymentFeedback.textContent = 'Aguardando confirmação digital...';

                window.setTimeout(() => {
                    setPaymentStatus('Pagamento aprovado');
                    paymentFeedback.textContent = `Pagamento confirmado. Ref: ${activePaymentRef || 'SURVIVE'}.`;

                    window.setTimeout(() => {
                        closePayment();
                        activateAvatarSelectionFromPayment();
                    }, 950);
                }, 1250);
            };

            const copyPixCode = async () => {
                const value = paymentCopyCode.value;

                if (!value) {
                    return;
                }

                try {
                    if (navigator.clipboard && window.isSecureContext) {
                        await navigator.clipboard.writeText(value);
                    } else {
                        paymentCopyCode.focus();
                        paymentCopyCode.select();
                        document.execCommand('copy');
                    }

                    paymentFeedback.textContent = 'Código copiado.';
                } catch (error) {
                    paymentFeedback.textContent = 'Não foi possível copiar automaticamente.';
                }
            };

            const tick = () => {
                countdownEl.textContent = formatCountdown(state.nextRoundAt);
            };

            const refreshLobby = async () => {
                try {
                    const response = await fetch(liveEndpoint, {
                        headers: { Accept: 'application/json' },
                        cache: 'no-store',
                    });

                    if (!response.ok) {
                        return;
                    }

                    const data = await response.json();
                    state.nextRoundAt = new Date(data.next_round_at).getTime();
                    nextRoundLabelEl.textContent = data.next_round_label;
                    playersOnlineEl.textContent = data.players_online_formatted;
                    estimatedPrizeEl.textContent = data.estimated_prize_brl;
                    entryFeeEl.textContent = `${data.entry_price_brl} por entrada`;
                    pixCheckout.amount = Number(data.entry_price || pixCheckout.amount || 5);

                    const livePlayers = Number.parseInt(data.players_online, 10);
                    if (Number.isFinite(livePlayers) && livePlayers > 0) {
                        arenaData.remaining_players = livePlayers;

                        if (arenaRemaining && phone.classList.contains('arena-mode')) {
                            arenaRemaining.textContent = `Restantes: ${livePlayers.toLocaleString('pt-BR')}`;
                        }
                    }

                    adjustPrizeTypography();
                    tick();
                } catch (error) {
                    // Ignora falhas de atualização para manter o lobby funcionando offline.
                }
            };

            adjustPrizeTypography();
            loadSavedAvatar();
            updateAvatarPreview();
            setAvatarFilter('todos');
            tick();
            setInterval(tick, 1000);
            setInterval(refreshLobby, 15000);
            setInterval(refreshArenaLive, 6000);

            if ('serviceWorker' in navigator) {
                window.addEventListener('load', () => {
                    navigator.serviceWorker.getRegistrations().then((registrations) => {
                        registrations.forEach((registration) => registration.unregister());

                        return navigator.serviceWorker.register('/sw.js?v=14');
                    }).catch(() => {
                        // Sem bloqueio para o usuário se o SW falhar.
                    });
                });
            }

            const installButton = document.getElementById('installApp');
            let deferredPrompt = null;

            enterNowButton.addEventListener('click', (event) => {
                event.preventDefault();
                openPayment();
            });

            paymentClose.addEventListener('click', closePayment);
            copyPixButton.addEventListener('click', copyPixCode);
            confirmDigitalPaymentButton.addEventListener('click', confirmDigitalPayment);
            avatarBackButton.addEventListener('click', () => setActiveTab('home'));
            arenaBackButton.addEventListener('click', () => setActiveTab('home'));

            avatarFilterButtons.forEach((button) => {
                button.addEventListener('click', () => {
                    setAvatarFilter(button.dataset.avatarFilter);
                });
            });

            avatarGrid.addEventListener('click', (event) => {
                const target = event.target.closest('button[data-avatar-id]');

                if (!target) {
                    return;
                }

                selectedAvatarId = target.dataset.avatarId;
                updateAvatarPreview();
                renderAvatarGrid();
                avatarNote.textContent = '';
            });

            confirmAvatarButton.addEventListener('click', async () => {
                confirmAvatarButton.disabled = true;
                avatarNote.textContent = 'Salvando avatar...';
                persistAvatarLocal();

                const result = await persistAvatarOnServer();
                const selectedAvatar = getAvatarById(selectedAvatarId);
                avatarNote.textContent = result.ok
                    ? `Avatar ${selectedAvatar.label} confirmado com sucesso.`
                    : `${result.message} Avatar ${selectedAvatar.label} mantido no dispositivo.`;
                confirmAvatarButton.disabled = false;

                if (result.ok) {
                    window.setTimeout(() => {
                        renderArena();
                        setActiveTab('arena');
                        refreshArenaLive();
                        avatarNote.textContent = '';
                    }, 450);
                }
            });

            paymentOverlay.addEventListener('click', (event) => {
                if (event.target === paymentOverlay) {
                    closePayment();
                }
            });

            window.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && !paymentOverlay.hidden) {
                    closePayment();
                }
            });

            window.addEventListener('beforeinstallprompt', (event) => {
                event.preventDefault();
                deferredPrompt = event;
                installButton.hidden = false;
            });

            installButton.addEventListener('click', async () => {
                if (!deferredPrompt) {
                    return;
                }

                deferredPrompt.prompt();
                await deferredPrompt.userChoice;
                deferredPrompt = null;
                installButton.hidden = true;
            });
        })();
    </script>
</body>
</html>
<?php /**PATH C:\xampp1\htdocs\servive jogo\resources\views/game.blade.php ENDPATH**/ ?>