<?php

include 'template/includes/config_web.php'; 
?>

<!DOCTYPE html>
<html lang="id">
  
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= $title; ?></title>
  <meta name="description" content="<?= $deskripsi; ?>">
  <meta name="keywords" content="<?= $keyword; ?>">
  <meta name="author" content="koiwin">
  <meta name="robots" content="index, follow">
  <link rel="canonical" href="<?= $urlweb; ?>">
  <meta name="theme-color" content="#151515">
  <meta name="msapplication-TileColor" content="#151515">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta property="og:title" content="<?= $title; ?>">
  <meta property="og:description" content="<?= $deskripsi; ?>">
  <meta property="og:type" content="website">
  <meta property="og:url" content="<?= $urlweb; ?>">
  <meta property="og:image" content="<?= $urlweb; ?>/assets/img/<?= $logo; ?>">
  <meta property="og:site_name" content="koiwin">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="<?= $title; ?>">
  <meta name="twitter:description" content="<?= $deskripsi; ?>">
  <meta name="twitter:image" content="<?= $urlweb; ?>/assets/img/<?= $logo; ?>">
  <link rel="icon" href="<?= $urlweb; ?>/assets/img/koi_ico_notext.png">
  <link rel="preload" as="font" href="themes/default/font/font-awesome/webfonts/fa-solid-900.woff2" type="font/woff2" crossorigin>

  <!-- CSS -->
  <link rel="stylesheet" href="themes/default/css/global.css?v=2.2.0.0">
  <link rel="stylesheet" href="themes/default/font/font-awesome/css/all.min.css?v=2.2.0.0">

  <?php if ($warna === "luxury-them") { ?>
    <link rel="stylesheet" href="luxury-them/custom/css/style.css?v=2.2.0.0">
  <?php } elseif ($warna === "merah-kuning") { ?>
    <link rel="stylesheet" href="merah-kuning/custom/css/style.css?v=2.2.0.0">
  <?php } ?>
  <link rel="stylesheet" href="themes/default/sass/custom.css?v=2.2.0.0">
</head>
<body>
  
<?php include 'template/includes/header.php'; ?>

<!-- ================= OVERLAY ================= -->
<div id="overlay"></div>

<!-- ================= GLOBAL LOADER ================= -->
<div class="discord-loader" id="globalLoader">

  <div class="discord-logo dice-gg">
    <svg id="diceSvg" width="58" height="58" viewBox="0 0 100 100">

      <defs>
        <filter id="glow">
          <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
          <feMerge>
            <feMergeNode in="coloredBlur"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
      </defs>

      <!-- DICE BODY -->
      <rect
        x="10"
        y="10"
        width="80"
        height="80"
        rx="18"
        fill="#cfa14a"
        filter="url(#glow)"
        />

      <!-- DICE DOTS -->
      <g id="dots" fill="#0f0f13"></g>

    </svg>
  </div>

  <!-- LOADING DOTS -->
  <div class="dots">
    <span></span><span></span><span></span>
  </div>
</div>

<link
  rel="stylesheet"
  type="text/css"
  href="luxury-them/custom/css/loading.css?v=2.2.0.0"
/>

<!-- ================= END GLOBAL LOADER ================= -->
<?php include 'template/includes/claim_scater.php'; ?>
<?php include 'template/includes/sidenav.php'; ?>

<?php
if ($_GET['page'] == "home") {
  
  include 'template/page/home.php';
} else if ($_GET['page'] == "promosi") {
  include 'template/page/promosi.php';
} else if ($_GET['page'] == "daftar") {
  include 'template/page/daftar.php';
} else if ($_GET['page'] == "slot") {
  include 'template/page/game/slot.php';
} else if ($_GET['page'] == "casino") {
  include 'template/page/game/casino.php';
} else if ($_GET['page'] == "arcade") {
  include 'template/page/game/arcade.php';
} else if ($_GET['page'] == "fishing") {
  include 'template/page/game/fishing.php';
} else if ($_GET['page'] == "sportbok") {
  include 'template/page/game/sportbok.php';
} else if ($_GET['page'] == "rtp") {
  include 'template/page/game/rtp.php';
} else if ($_GET['page'] == "togel") {
  include 'template/page/game/togel.php';
} else if ($_GET['page'] == "roda") {
  include 'template/page/hadiah/roda.php';
} else if ($_GET['page'] == "contact") {
  include 'template/page/contact.php';
} else if ($_GET['page'] == "deposit") {
  include 'template/page/deposit.php';
} else if ($_GET['page'] == "riwayat") {
  include 'template/page/riwayat.php';
} else if ($_GET['page'] == "referral") {
  include 'template/page/referral.php';
} else if ($_GET['page'] == "profile") {
  include 'template/page/profil.php';
} else if ($_GET['page'] == "withdraw") {
  include 'template/page/withdraw.php';
} else if ($_GET['page'] == "bahan-iklan") {
  include 'template/page/bahan-iklan.php';
  
  
  //API TEST
} else if ($_GET['page'] == "playgame") {
  include '../play/game/playgame.php';
  
  
  
} else {
  include 'template/page/home.php';
}
?>

<?php include 'template/includes/footer.php'; ?>
<?php include 'template/includes/login_modal.php'; ?>
   
<!-- ================= HOME POPUP ================= -->
<div class="home-popup-overlay" id="homePopup">
  <div class="home-popup">
    <button class="popup-close" onclick="closeHomePopup()">✕</button>

    <div class="popup-logo">
      <img data-src="../assets/img/<?php echo $logo ?>" alt="KOIWIN88">
    </div>

    <h3>Bonus New Member 🎁</h3>
    <p>
      Daftar sekarang dan dapatkan bonus langsung untuk memulai permainan!
    </p>

    <div class="popup-actions">
      <a href="?page=daftar" class="btn-popup primary">Daftar Sekarang</a>
      <a href="#"
         class="btn-popup ghost"
         data-toggle="modal"
         data-target="#loginModal"
         onclick="closeHomePopup()"
         style="flex:1">
        <i class="fas fa-sign-in-alt"></i> Masuk
      </a>
    </div>
    <div class="popup-note">
      * Syarat & ketentuan berlaku
    </div>
  </div>
</div>

<!-- ================= WALLET POPUP ================= -->
<div class="wallet-popup-overlay" id="walletOverlay"></div>
<div class="wallet-popup" id="walletPopup">
  
  <!-- Deposit -->
  <a href="?page=deposit" class="wallet-card deposit">
    <i class="fas fa-arrow-down"></i>
    <span>Deposit</span>
  </a>

  <!-- Riwayat (TENGAH) -->
  <a href="?page=riwayat" class="wallet-card history">
    <i class="fas fa-history"></i>
    <span>Riwayat</span>
  </a>

  <!-- Withdraw -->
  <a href="?page=withdraw" class="wallet-card withdraw">
    <i class="fas fa-arrow-up"></i>
    <span>Withdraw</span>
  </a>
</div>

</body>
</html>

<!-- ================= CUSTOM JA ================= -->
<script src="themes/default/js/vendor.js"></script>
<script src="themes/default/js/global.js?v=2.0.1445"></script>
<script src="themes/default/js/index.js?v=2.0.1445"></script>
<script src="themes/default/vendor/jquery-validate/jquery.validate.min.js"></script>
<script src="https://code.iconify.design/3/3.1.0/iconify.min.js"></script>
<!-- end fungsi CUSTOM JS -->

<!-- ================= SWEETALERT NOTIF ================= -->
<script>
function showNotif(type, title, message, timer = 10000) {
  // tampilkan overlay
  $('#overlay').fadeIn(150);

  Swal.fire({
    icon: type,
    title: title,
    html: `<span class="swal-desc">${message}</span>`,

    // 🔥 tombol OK aktif
    showConfirmButton: true,
    confirmButtonText: 'OK',

    // timer boleh tetap (opsional)
    timer: timer,
    timerProgressBar: true,

    background: '#121212',
    color: '#fff',
    iconColor:
      type === 'success' ? '#d6a24f' :
      type === 'error'   ? '#e74c3c' :
                           '#3498db',

    backdrop: false,
    allowOutsideClick: false, // biar fokus
    allowEscapeKey: true,

    customClass: {
      popup: 'swal-premium',
      title: 'swal-title',
      confirmButton: 'swal-btn'
    }
  }).then(() => {
    // nutup overlay kalau klik OK / timer habis
    $('#overlay').fadeOut(150);
  });
}
</script>
<!-- ================= SWEETALERT NOTIF ================= -->

<!-- ================= PHP ALERT HANDLER ================= -->
<?php
if (!empty($_GET['pesan'])) {

  $notif = [
    1  => ['error','Email Sudah Digunakan','Silakan gunakan email lain'],
    2  => ['error','Captcha Salah','Periksa kembali captcha Anda'],
    3  => ['success','Registrasi Berhasil','Akun Anda berhasil dibuat'],
    4  => ['error','Validasi Gagal','Password dan konfirmasi tidak sama'],
    5  => ['error','Gagal','Pendaftaran akun gagal'],
    6  => ['error','Akun Disuspend','Akun Anda disuspend oleh admin'],
    7  => ['error','Login Gagal','Username atau password salah'],
    8  => ['success','Logout','Anda berhasil logout'],
    9  => ['success','Deposit Berhasil','Silakan hubungi admin'],
    10 => ['error','Upload Gagal','Gagal mengupload gambar'],
    11 => ['error','File Terlalu Besar','Ukuran file melebihi batas'],
    12 => ['error','Format Salah','Format gambar harus JPG atau PNG'],
    13 => ['error','Deposit Pending','Masih ada proses deposit berjalan'],
    14 => ['error','Promo Tidak Berlaku','Promo hanya untuk member baru'],
    15 => ['error','Nominal Salah','Nominal tidak sesuai ketentuan bonus'],
    16 => ['info','Deposit Minimal',"Minimal deposit $min_depo"],
    17 => ['info','Turnover Belum Cukup','Silakan lanjutkan permainan'],
    18 => ['error','Saldo Kurang','Saldo tidak mencukupi'],
    19 => ['info','Withdraw Minimal',"Minimal withdraw $min_wd"],
    20 => ['success','Withdraw Berhasil','Silakan hubungi admin'],
    21 => ['error','Withdraw Pending','Masih ada proses withdraw'],
    22 => ['info','Perhatian','Segera hubungi admin'],
    23 => ['error','Akses Ditolak','Silakan login terlebih dahulu'],
    24 => ['error','Gagal','Ubah password gagal'],
    25 => ['error','Password Salah','Password lama salah'],
    26 => ['info','Validasi','Password baru & konfirmasi harus sama'],
    27 => ['success','Berhasil','Password berhasil diubah'],
    28 => ['info','Login Diperlukan','Silakan login untuk bermain'],
    29 => ['error','Akun Disuspend','Akun Anda disuspend'],
    30 => ['error','Username Digunakan','Gunakan username lain'],
    31 => ['error','Maintenance','Game sedang dalam perbaikan'],
    32 => ['success','BERHASIL','Rekening berhasil di tambahkan'],
    33 => ['info','SPIN 2X SEHARI','Silahkan datang lagi besok'],
    34 => ['info','Maintenance','sedang dalam perbaikan. silahkan kembali lagi nanti'],
    35 => ['error','ERROR','Terjadi kesalahan saat memuat data silahkan tutup browser dan buka kembali jika masih sama hubungi admin'],
    36 => ['info','informasi','Sedang tidak ada turnamen silahkan kembali lagi nanti'],
    37 => ['success','Berhasil','Claim bonus scater berhasil di proses silahkah status di halaman riwayat transaksi'],
    38 => ['error','informasi','Maaf ada kesalahan tidak terduka silahkan lougout dan login kembali'],
    
    39 => ['info','informasi','minimal saldo untuk bermain adalah 500k']

  ];

  if (isset($notif[$_GET['pesan']])) {
    [$type, $title, $msg] = $notif[$_GET['pesan']];
    echo "<script>showNotif('$type','$title','$msg');</script>";
  }
}
?>
<!-- ================= PHP ALERT HANDLER ================= -->

<?php if (!empty($id_livechat)) { ?>
<!-- ================= TAWK.TO ================= -->
<script type="text/javascript">
var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
(function(){
  var s1 = document.createElement("script"),
      s0 = document.getElementsByTagName("script")[0];
  s1.async = true;
  s1.src = "https://embed.tawk.to/<?php echo $id_livechat; ?>/1jfqmmalb";
  s1.charset = "UTF-8";
  s1.setAttribute("crossorigin","*");
  s0.parentNode.insertBefore(s1,s0);
})();
</script>

<script>
let tawkUnread = parseInt(localStorage.getItem('tawk_unread') || '0', 10);
let lastSeenUnread = parseInt(localStorage.getItem('tawk_last_seen') || '0', 10);

function showTawkBadge(count){
  const badge = document.getElementById('tawkBadge');
  if (!badge) return;

  if (count > 0) {
    badge.textContent = count > 9 ? '9+' : count;
    badge.style.display = 'inline-block';
  } else {
    badge.style.display = 'none';
  }
}

function showTawkContext(){
  const ctx = document.getElementById('tawkContext');
  if (!ctx) return;

  ctx.classList.add('show');
  setTimeout(() => {
    ctx.classList.remove('show');
  }, 8000);
}

// 🔄 Saat reload → kalau ada unread yg belum pernah dilihat → munculin context
document.addEventListener('DOMContentLoaded', () => {
  showTawkBadge(tawkUnread);

  if (tawkUnread > lastSeenUnread) {
    showTawkContext(); // 👈 muncul tiap reload kalau ada chat baru
  }
});

// 🔔 CS kirim pesan
Tawk_API.onChatMessageAgent = function(){
  if (!Tawk_API.isChatMaximized()) {
    tawkUnread++;
    localStorage.setItem('tawk_unread', tawkUnread);
    showTawkBadge(tawkUnread);
    showTawkContext();
  }
};

// 🔄 Reset saat user buka chat
function openLiveChat() {
  if (window.Tawk_API && Tawk_API.maximize) {
    localStorage.setItem('tawk_last_seen', tawkUnread); // tandai semua sudah "dilihat"
    tawkUnread = 0;
    localStorage.setItem('tawk_unread', 0);
    showTawkBadge(0);
    Tawk_API.maximize();
  }
}
</script>
<!-- ================= TAWK.TO ================= -->
<?php } ?>

<!-- ================= SMART GLOBAL LOADER ================= -->
<script>
document.addEventListener("DOMContentLoaded", function(){
  const loader = document.getElementById("globalLoader");
  const MAX_WAIT = 1500; // ⏱️ batas maksimal nunggu (ms)
  let loaderClosed = false;

  function closeLoader(){
    if (loader && !loaderClosed) {
      loaderClosed = true;
      loader.style.opacity = "0";
      loader.style.pointerEvents = "none";
    }
  }

  // 1️⃣ TUTUP JIKA PAGE SELESAI
  window.addEventListener("load", closeLoader);

  // 2️⃣ PAKSA TUTUP JIKA KELEWAT TIMEOUT
  setTimeout(closeLoader, MAX_WAIT);

  // 3️⃣ SAAT KLIK LINK → TAMPILKAN LOADER
  document.querySelectorAll('a').forEach(link => {
    link.addEventListener('click', function() {
      const href = this.getAttribute('href');
      const isExternal = href && href.startsWith('http') && !href.includes(location.hostname);

      if (
        href &&
        href !== '#' &&
        !href.startsWith('javascript') &&
        !this.hasAttribute('target') &&
        !this.hasAttribute('data-toggle') &&
        !isExternal
      ) {
        if (loader) {
          loaderClosed = false; // reset state
          loader.style.opacity = "1";
          loader.style.pointerEvents = "all";

          // safety timeout pas pindah halaman
          setTimeout(closeLoader, MAX_WAIT);
        }
      }
    });
  });
});

const patterns = [
  [[50,50]],
  [[30,30],[70,70]],
  [[30,30],[50,50],[70,70]],
  [[30,30],[70,30],[30,70],[70,70]],
  [[30,30],[70,30],[50,50],[30,70],[70,70]],
  [[30,30],[70,30],[30,50],[70,50],[30,70],[70,70]]
];

let diceInterval = null;

function startDiceDots(){
  const dots = document.getElementById("dots");
  if (!dots) return;

  function render(){
    dots.innerHTML = "";
    const p = patterns[Math.floor(Math.random()*patterns.length)];
    p.forEach(d=>{
      const c=document.createElementNS("http://www.w3.org/2000/svg","circle");
      c.setAttribute("cx",d[0]);
      c.setAttribute("cy",d[1]);
      c.setAttribute("r","5");
      dots.appendChild(c);
    });
  }

  render();
  clearInterval(diceInterval);
  diceInterval = setInterval(render, 200);
}

document.addEventListener("DOMContentLoaded", startDiceDots);
</script>
<!-- ================= SMART GLOBAL LOADER ================= -->

<!-- ================= SEARCH FILTER ================= -->
<script>
(() => {
  const box = document.querySelector('.sgx-search-box');
  const btn = document.getElementById('sgxSearchBtn');
  const input = document.getElementById('sgxSearchInput');
  const cards = document.querySelectorAll('.sgx-game-card');

  if (!box || !btn || !input) return;

  const close = () => {
    box.classList.remove('active');
    input.value = '';
    cards.forEach(c => c.style.display = '');
  };

  btn.onclick = e => {
    e.stopPropagation();
    box.classList.add('active');
    setTimeout(() => input.focus(), 250);
  };

  input.oninput = () => {
    const v = input.value.toLowerCase();
    cards.forEach(c => {
      c.style.display = c.dataset.name.includes(v) ? '' : 'none';
    });
  };

  document.onclick = e => !box.contains(e.target) && close();
})();
</script>
<!-- ================= SEARCH FILTER ================= -->

<!-- ================= PAKSA DPI 420 ================= -->
<script>
(function () {
  const targetWidth = 400;
  const screenWidth = window.screen.width;
  const scale = screenWidth / targetWidth;

  const meta = document.createElement("meta");
  meta.name = "viewport";
  meta.content =
    "width=" + targetWidth +
    ", initial-scale=" + scale +
    ", minimum-scale=" + scale +
    ", maximum-scale=" + scale +
    ", user-scalable=no";

  document.head.appendChild(meta);
})();
</script>
<!-- ================= PAKSA DPI 420 ================= -->

<link rel="stylesheet" href="luxury-them/custom/css/index_mobile.css?v=2.2.0.0">

<!-- ===== CLICK EFFECT ===== -->
<audio id="clickSound" preload="auto">
<source src="luxury-them/custom/click.mp3" type="audio/mpeg"></audio>
<script>
  const btn = document.querySelector('.mbnav-center-inner');
  const sound = document.getElementById('clickSound');
  
  btn.addEventListener('click', () => {
    sound.volume = 0.3;
    sound.currentTime = 0; // reset biar bisa spam klik
    sound.play();
  });
</script>
<!-- ===== CLICK EFFECT ===== -->

<!-- ================= POPUP ================ -->
<script>
document.addEventListener("DOMContentLoaded", function () {
  const popup = document.getElementById("homePopup");

  // tampil hanya sekali
  if (!localStorage.getItem("homePopupShown")) {
    popup.style.display = "flex";
  }
});

function closeHomePopup() {
  document.getElementById("homePopup").style.display = "none";
  localStorage.setItem("homePopupShown", "yes");
}
</script>
<!-- ================= POPUP ================ -->

<script>
  $(document).on('show.bs.modal', '.modal', function() {
    // Tampilkan overlay saat modal muncul
    $('#overlay').fadeIn(150);
  });
  
  $(document).on('hidden.bs.modal', '.modal', function() {
    // Cek apakah masih ada modal yang terbuka
    if ($('.modal.show').length === 0) {
      // Kalau gak ada modal terbuka, sembunyikan overlay
      $('#overlay').fadeOut(150);
    }
  });
</script>

<!-- ================= NOTIF ================ -->
<script>
  document.addEventListener("DOMContentLoaded", function() {
    const bellBtn = document.querySelector('.bell-btn');
    const notifDropdown = document.getElementById('notifDropdown');
    const notifBadge = document.getElementById('notifBadge');
  
    // Set jumlah notifikasi badge dari PHP
    const notifCount = <?= $notifCount ?>;
    if (notifCount > 0) {
      notifBadge.textContent = notifCount;
      notifBadge.style.display = 'inline-block';
    } else {
      notifBadge.style.display = 'none';
    }
  
    bellBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      if (notifDropdown.style.display === 'none' || notifDropdown.style.display === '') {
        notifDropdown.style.display = 'block';
      } else {
        notifDropdown.style.display = 'none';
      }
    });
  
    document.addEventListener('click', function() {
      notifDropdown.style.display = 'none';
    });
  });
</script>
<!-- ================= NOTIF ================ -->

<!-- ================= CHAT ================= -->
<script>
document.addEventListener("DOMContentLoaded", () => {

  /* =============================
     ELEMENT
  ============================== */
  const chatBtn    = document.querySelector('.chat-btn');
  const chatBox    = document.getElementById('chatDropdown');
  const overlay    = document.getElementById('chatSheetOverlay');
  const chatClose  = document.querySelector('.chat-close');

  const chatList   = document.getElementById('chatMessages');
  const chatInput  = document.getElementById('chatInput');
  const chatSend   = document.getElementById('chatSend');
  const voiceBtn   = document.getElementById('voiceBtn');
  const newNotice  = document.getElementById('newChatNotice');

  let lastMsgCount = 0;
  let chatTimer    = null;
  let unreadChat   = 0;

  /* =============================
     BADGE CHAT
  ============================== */
  function showChatBadge(count) {
    const badge = document.getElementById('chatBadge');
    if (!badge) return;

    if (count > 0) {
      badge.textContent = count > 9 ? '9+' : count;
      badge.style.display = 'inline-block';
    } else {
      badge.style.display = 'none';
    }
  }

  /* =============================
     CHAT OPEN / CLOSE
  ============================== */
  function openChat() {
    chatBox.classList.add('active');
    overlay.classList.add('active');
    document.body.style.overflow = 'hidden';

    unreadChat = 0;
    showChatBadge(0);

    loadChat(true);
    startChatInterval();
  }

  function closeChat() {
    chatBox.classList.remove('active');
    overlay.classList.remove('active');
    document.body.style.overflow = '';
    stopChatInterval();
  }

  chatBtn.addEventListener('click', e => {
    e.stopPropagation();
    openChat();
  });

  chatClose.addEventListener('click', e => {
    e.stopPropagation();
    closeChat();
  });

  overlay.addEventListener('click', closeChat);
  chatBox.addEventListener('click', e => e.stopPropagation());

  /* =============================
     CHAT INTERVAL
  ============================== */
  function startChatInterval() {
    if (chatTimer) return;
    chatTimer = setInterval(() => loadChat(false), 3000);
  }

  function stopChatInterval() {
    clearInterval(chatTimer);
    chatTimer = null;
  }

  /* =============================
     SCROLL
  ============================== */
  function isAtBottom() {
    return chatList.scrollHeight - chatList.scrollTop - chatList.clientHeight < 30;
  }

  function scrollToBottom() {
    chatList.scrollTop = chatList.scrollHeight;
    newNotice.style.display = 'none';
  }

  newNotice.onclick = scrollToBottom;

  /* =============================
     LOAD CHAT
  ============================== */
  function maskName(name) {
    if (!name) return '';
    return name.slice(0,2) + '***' + name.slice(-4);
  }

  function maskDangerousMessage(msg) {
    if (!msg) return msg;
    const forbidden = ['http','https','kontol','anjing','memek','babi','asu','tai'];
    const phone = /\b\d{6,}\b/;
    const low = msg.toLowerCase();

    if (forbidden.some(w => low.includes(w)) || phone.test(msg)) {
      return '<i style="color:#ff6b6b">TEXT SENSOR BY KOWINBOT</i>';
    }
    return msg;
  }

  function loadChat(forceScroll = false) {
    fetch('public/ajax_public.php')
      .then(r => r.json())
      .then(data => {
        if (!Array.isArray(data)) return;

        if (data.length > lastMsgCount && !forceScroll) {
          const newMsg = data.length - lastMsgCount;
          unreadChat += newMsg;
          showChatBadge(unreadChat);
        }

        if (data.length === lastMsgCount) return;

        for (let i = lastMsgCount; i < data.length; i++) {
          const c = data[i];
          let html = '';

          if (c.type === 'voice') {
            html = `
              <div class="chat-voice">
                <strong style="color:#d6a24f">${maskName(c.user)}</strong>
                <small style="color:#888"> ${c.time}</small>
                <audio src="${c.msg}" preload="metadata"></audio>
                <div class="voice-ui" onclick="toggleVoice(this)">
                  <i class="fas fa-play"></i>
                  <div class="wave">
                    <span></span><span></span><span></span><span></span><span></span>
                  </div>
                  <span class="duration">0:00</span>
                </div>
              </div>`;
          } else {

            const isMine = c.user === "<?= $_SESSION['username'] ?? '' ?>";
            html = `
              <div class="chat-text" data-id="${c.id}">
                <div style="display:flex;justify-content:space-between;align-items:center">
                  <div>
                    <strong style="color:#d6a24f">${maskName(c.user)}</strong>
                    <small style="color:#888"> ${c.time}</small>
                  </div>
          
                  ${isMine ? `
                    <i class="fas fa-trash chat-delete"
                       title="Hapus"
                       style="cursor:pointer;color:#ff6b6b;font-size:12px"
                       onclick="deleteChat(${c.id})">
                    </i>
                  ` : ``}
                </div>
                ${maskDangerousMessage(c.msg)}
              </div>
            `;
          }

          chatList.insertAdjacentHTML('beforeend', html);
        }

        if (forceScroll || isAtBottom()) {
          scrollToBottom();
        } else {
          newNotice.style.display = 'block';
        }

        lastMsgCount = data.length;
      });
  }
  
    /* =============================
   AUTO CREATE DELETE MODAL
============================== */

// Buat CSS
const deleteStyle = document.createElement('style');
deleteStyle.innerHTML = `
#deleteModal{
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.6);
  display:none;
  align-items:center;
  justify-content:center;
  z-index:99999;
  backdrop-filter:blur(4px);
}
#deleteBox{
  background:#1f1f1f;
  padding:20px;
  width:90%;
  max-width:320px;
  border-radius:16px;
  text-align:center;
  box-shadow:0 10px 40px rgba(0,0,0,.4);
  animation:fadeIn .2s ease;
  color:#fff;
}
#deleteBox h3{
  margin:0 0 10px;
}
#deleteBox p{
  font-size:13px;
  color:#aaa;
  margin-bottom:15px;
}
.delete-actions{
  display:flex;
  gap:10px;
}
.delete-actions button{
  flex:1;
  padding:8px;
  border:none;
  border-radius:8px;
  cursor:pointer;
  font-weight:600;
}
#cancelDelete{
  background:#333;
  color:#fff;
}
#confirmDelete{
  background:#ff4d4f;
  color:#fff;
}
@keyframes fadeIn{
  from{transform:scale(.9);opacity:0}
  to{transform:scale(1);opacity:1}
}
`;
document.head.appendChild(deleteStyle);

// Buat HTML
const deleteModal = document.createElement('div');
deleteModal.id = 'deleteModal';
deleteModal.innerHTML = `
  <div id="deleteBox">
    <h3>Hapus Pesan?</h3>
    <p>Pesan yang dihapus tidak bisa dikembalikan.</p>
    <div class="delete-actions">
      <button id="cancelDelete">Batal</button>
      <button id="confirmDelete">Hapus</button>
    </div>
  </div>
`;
document.body.appendChild(deleteModal);


/* =============================
   DELETE FUNCTION
============================== */

let deleteTargetId = null;

window.deleteChat = function(id) {
  deleteTargetId = id;
  deleteModal.style.display = 'flex';
};

document.getElementById('cancelDelete').onclick = function() {
  deleteTargetId = null;
  deleteModal.style.display = 'none';
};

document.getElementById('confirmDelete').onclick = function() {
  if (!deleteTargetId) return;
  
  fetch('public/ajax_public.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'delete_id=' + deleteTargetId
  }).then(() => {
    const el = document.querySelector('.chat-text[data-id="' + deleteTargetId + '"]');
    if (el) el.remove();
    
    deleteTargetId = null;
    deleteModal.style.display = 'none';
  });
};
  /* =============================
     SEND TEXT
  ============================== */
  function sendChat() {
    const msg = chatInput.value.trim();
    if (!msg) return;

    fetch('public/ajax_public.php', {
      method: 'POST',
      headers: {'Content-Type':'application/x-www-form-urlencoded'},
      body: 'message=' + encodeURIComponent(msg)
    }).then(() => {
      chatInput.value = '';
      loadChat(true);
    });
  }

  chatSend.onclick = e => { e.stopPropagation(); sendChat(); };
  chatInput.onkeydown = e => {
    if (e.key === 'Enter') {
      e.preventDefault();
      sendChat();
    }
  };

  /* =============================
     PLAY VOICE
  ============================== */
  window.toggleVoice = function(el) {
    const audio = el.previousElementSibling;
    const icon  = el.querySelector('i');
    const dur   = el.querySelector('.duration');

    document.querySelectorAll('.voice-ui').forEach(ui => {
      if (ui !== el) {
        ui.classList.remove('playing');
        ui.querySelector('i').className = 'fas fa-play';
        ui.previousElementSibling.pause();
      }
    });

    if (audio.paused) {
      stopChatInterval();
      audio.play();
      el.classList.add('playing');
      icon.className = 'fas fa-pause';
    } else {
      audio.pause();
      el.classList.remove('playing');
      icon.className = 'fas fa-play';
      startChatInterval();
    }

    audio.onended = () => {
      el.classList.remove('playing');
      icon.className = 'fas fa-play';
      startChatInterval();
    };
  };
  
  
    /* VOICE RECORDER */
  let mediaRecorder, audioChunks = [], recording = false, recordStart = 0;

  voiceBtn.onclick = async () => {
    if (!recording) {
      const stream = await navigator.mediaDevices.getUserMedia({ audio:true });
      mediaRecorder = new MediaRecorder(stream);
      audioChunks = [];
      recordStart = Date.now();

      mediaRecorder.ondataavailable = e => {
        if (e.data.size > 0) audioChunks.push(e.data);
      };

      mediaRecorder.onstop = () => {
        const blob = new Blob(audioChunks, { type:'audio/webm' });
        if (blob.size === 0) return alert('Rekaman gagal');

        const fd = new FormData();
        fd.append('voice', blob);

        fetch('public/ajax_public.php', { method:'POST', body:fd })
          .then(() => loadChat(true));
      };

      mediaRecorder.start();
      recording = true;
      voiceBtn.innerHTML = '<i class="fas fa-stop"></i>';
      voiceBtn.style.background = '#d9534f';

    } else {
      if (Date.now() - recordStart < 1000) {
        return alert('Minimal rekam 1 detik');
      }
      mediaRecorder.stop();
      recording = false;
      voiceBtn.innerHTML = '<i class="fas fa-microphone"></i>';
      voiceBtn.style.background = '#444';
    }
  };


  /* =============================
     AUTO START
  ============================== */
  startChatInterval();

});
</script>
<!-- ================= CHAT ================= -->

<!-- ================= SHOW/HIDE PASS    ================== -->
<script>
  const togglePassword = document.getElementById("togglePassword");
  const passwordInput = document.getElementById("password");

  togglePassword.addEventListener("click", function () {
    const type = passwordInput.getAttribute("type") === "password" ? "text" : "password";
    passwordInput.setAttribute("type", type);

    // Ganti ikon mata
    this.classList.toggle("fa-eye");
    this.classList.toggle("fa-eye-slash");
  });
</script>
<!-- ================= SHOW/HIDE PASS    ================== -->

<!-- ================= WALLET REFRESH    ================== -->
<script>
document.addEventListener("DOMContentLoaded", () => {

    /* =============================
       CEK PAGE AKTIF
    ============================== */
    const params = new URLSearchParams(window.location.search);
    const currentPage = params.get('page');

    // 🚫 JANGAN REFRESH WALLET SAAT MAIN GAME
    if (currentPage === 'playgame') {
        console.log('[Wallet] Skip refresh (playgame)');
        return;
    }

    /* =============================
       ELEMENT
    ============================== */
    const refreshBtn = document.querySelector('.wallet-refresh');
    const amountEl   = document.querySelector('.wallet-balance .amount');

    if (!refreshBtn || !amountEl) return;

    /* =============================
       WALLET REFRESH
    ============================== */
    function doWalletRefresh(force = false) {

        // 🚫 Cegah auto refresh berulang (kecuali klik manual)
        if (!force && sessionStorage.getItem('walletUpdated') === '1') return;

        const icon = refreshBtn.querySelector('i');
        icon?.classList.add('fa-spin');

        fetch('../../play/game/wd.php')
            .then(r => r.json())
            .then(data => {
                if (data?.status === 'ok' && data.balance !== undefined) {

                    sessionStorage.setItem('walletUpdated', '1');

                    amountEl.textContent =
                        Number(data.balance).toLocaleString('id-ID');
                }
            })
            .catch(err => {
                console.error('[Wallet] Error:', err);
            })
            .finally(() => {
                icon?.classList.remove('fa-spin');
            });
    }

    /* =============================
       AUTO LOAD
    ============================== */
    doWalletRefresh();

    /* =============================
       MANUAL CLICK
    ============================== */
    refreshBtn.addEventListener('click', () => {
        doWalletRefresh(true);
    });

});
</script>
<!-- ================= WALLET REFRESH    ==================-->

<!-- ================= LAZY IMAGE LOAD ================= -->
<script>
 // =====================
// GLOBAL LAZY LOAD IMAGES (OPTIMAL)
// =====================
document.addEventListener("DOMContentLoaded", () => {
  const lazyImages = document.querySelectorAll('img[data-src]');
  if (!lazyImages.length) return; // ga ada gambar, skip
  
  // fallback modern browser
  lazyImages.forEach(img => img.setAttribute('loading', 'lazy'));
  
  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver((entries, obs) => {
      for (const entry of entries) {
        if (!entry.isIntersecting) continue;
        
        const img = entry.target;
        img.src = img.dataset.src;
        img.removeAttribute('data-src');
        
        obs.unobserve(img);
      }
    }, {
      rootMargin: "50px 0px", // preload sebelum muncul layar
      threshold: 0.01
    });
    
    for (const img of lazyImages) observer.observe(img);
    
  } else {
    // fallback: load semua langsung
    for (const img of lazyImages) {
      img.src = img.dataset.src;
      img.removeAttribute('data-src');
    }
  }
});
</script>
<!-- ================= LAZY IMAGE LOAD ================= -->

<!-- ================= NAV WALLET ================= -->
<script>
const walletBtn = document.getElementById("walletToggle");
const popup = document.getElementById("walletPopup");
const overlay = document.getElementById("walletOverlay");

walletBtn.addEventListener("click", () => {
  popup.classList.toggle("active");
  overlay.classList.toggle("active");
});

overlay.addEventListener("click", () => {
  popup.classList.remove("active");
  overlay.classList.remove("active");
});
</script>
<!-- ================= NAV WALLET ================= -->

<!-- ================= TOGEL TIME ================= -->
<script>
function startTogelTimer() {
  const cards = document.querySelectorAll('.togel-card');

  cards.forEach(card => {
    const closeTime = card.dataset.close;
    if (!closeTime) return;

    const [h, m] = closeTime.split(':');

    function update() {
      const now = new Date();
      const target = new Date();

      target.setHours(parseInt(h));
      target.setMinutes(parseInt(m));
      target.setSeconds(0);

      // kalau sudah lewat, set ke besok
      if (target < now) {
        target.setDate(target.getDate() + 1);
      }

      const diff = target - now;

      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
      const minutes = Math.floor((diff / (1000 * 60)) % 60);
      const seconds = Math.floor((diff / 1000) % 60);

      card.querySelector('.day').textContent = String(days).padStart(2, '0');
      card.querySelector('.hour').textContent = String(hours).padStart(2, '0');
      card.querySelector('.minute').textContent = String(minutes).padStart(2, '0');
      card.querySelector('.second').textContent = String(seconds).padStart(2, '0');
    }

    update();
    setInterval(update, 1000);
  });
}

document.addEventListener('DOMContentLoaded', startTogelTimer);

</script>
<!-- ================= TOGEL TIME ================= -->

<!-- ================= DESKTOP DETECT ================= -->
<script>
const isMobileUA = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile/i
    .test(navigator.userAgent);

const screenWidth = window.innerWidth;

// Anggap mobile hanya jika:
// 1. UserAgent mobile
// 2. Lebar layar <= 768px
const isRealMobile = isMobileUA && screenWidth <= 768;

if (!isRealMobile) {
    window.location.href = 'error_page/alert_desktop.php';
}
</script>
<!-- ================= DESKTOP DETECT ================= -->