// === FUNGSI GLOBAL updateRTP ===
window.updateRTP = function () {
  const cards = document.querySelectorAll(
    "div.relative.w-full.rounded-xl.overflow-hidden"
  );

  cards.forEach((card) => {
    const oldOverlay = card.querySelector(".rtp-overlay, .bg-black\\/60");
    if (oldOverlay) oldOverlay.remove();

    const progressBar = card.querySelector(".animate-progress");
    const rtpSpan = card.querySelector(
      "span.absolute.inset-0.flex.items-center.justify-center"
    );
    const gameTitle = card.querySelector("h4.jsx-60e4719cfc9a198c");

    if (!progressBar || !rtpSpan || !gameTitle) return;

    const rtp = Math.floor(Math.random() * 100);

    rtpSpan.textContent = rtp + "%";
    progressBar.style.width = rtp + "%";

    if (rtp >= 61) {
      progressBar.style.backgroundColor = "rgb(34,197,94)";
      gameTitle.innerHTML = gameTitle.textContent;
    } else if (rtp >= 30) {
      progressBar.style.backgroundColor = "rgb(250,204,21)";
      gameTitle.innerHTML = gameTitle.textContent;
    } else {
      progressBar.style.backgroundColor = "rgb(239,68,68)";
      gameTitle.innerHTML = `
        <span class="jsx-60e4719cfc9a198c pointer-events-none text-red-600 transition-colors duration-300">
          ${gameTitle.textContent}
        </span>
      `;
      const overlay = document.createElement("div");
      overlay.className =
        "rtp-overlay absolute inset-0 bg-black/60 flex flex-col items-center justify-center rounded-xl text-white text-xs font-semibold z-10";
      overlay.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
             viewBox="0 0 24 24" fill="none" stroke="currentColor"
             stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
             class="lucide lucide-triangle-alert h-6 w-6 mb-1 text-red-500"
             aria-hidden="true">
          <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/>
          <path d="M12 9v4"/>
          <path d="M12 17h.01"/>
        </svg>
        RTP TIDAK BAGUS
      `;
      card.appendChild(overlay);
    }
  });
};

// === JALANKAN SAAT PAGE LOAD ===
document.addEventListener("DOMContentLoaded", () => {
  window.updateRTP();
  setInterval(window.updateRTP, 600000); // setiap 10 menit
});

function fixButtons() {
  // hapus disabled
  document.querySelectorAll('button[disabled]').forEach(btn => btn.removeAttribute('disabled'));
  // hapus md:hidden
  document.querySelectorAll('[class*="md:hidden"]').forEach(el => {
    el.className = el.className.replace(/md:hidden/g, '');
  });
  // hilangkan overlay
  document.querySelectorAll('.bg-black\\/60').forEach(overlay => {
    overlay.style.opacity = '0';
    overlay.style.pointerEvents = 'none';
  });
}

// jalankan pertama kali
document.addEventListener('DOMContentLoaded', fixButtons);
// jalankan lagi setelah 1 detik (jaga-jaga)
setTimeout(fixButtons, 1500);






document.addEventListener("DOMContentLoaded", () => {
  // === SEARCH ===
  const searchInput = document.querySelector("input[placeholder*='Cari game']");
  const gameCards = document.querySelectorAll(".relative.w-full.rounded-xl"); // selector utk card game

  if (searchInput) {
    searchInput.addEventListener("input", () => {
      const keyword = searchInput.value.toLowerCase().trim();
      gameCards.forEach(card => {
        const gameNameEl = card.querySelector("h4");
        const gameName = gameNameEl ? gameNameEl.textContent.toLowerCase() : "";
        card.style.display = gameName.includes(keyword) ? "" : "none";
      });
    });
  }

  // === MODAL ===
  const modal = document.createElement("div");
  modal.id = "modalPola";
  Object.assign(modal.style, {
    display: "none",
    position: "fixed",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    zIndex: "9999",
    maxHeight: "90vh",
    overflowY: "auto",
  });
  document.body.appendChild(modal);

  const overlay = document.createElement("div");
  overlay.id = "overlayPola";
  Object.assign(overlay.style, {
    display: "none",
    position: "fixed",
    top: "0",
    left: "0",
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0,0,0,0.7)",
    zIndex: "9998",
  });
  document.body.appendChild(overlay);

  function openModal(content) {
    modal.innerHTML = content;
    modal.style.display = "block";
    overlay.style.display = "block";
    const closeBtn = modal.querySelector("button[aria-label='Close detail game']");
    if (closeBtn) closeBtn.addEventListener("click", closeModal);
  }
  function closeModal() {
    modal.style.display = "none";
    overlay.style.display = "none";
  }
  overlay.addEventListener("click", closeModal);

  // === EVENT DELEGATION UNTUK TOMBOL LIHAT POLA ===
  // Supaya tombol â€œLihat Polaâ€ yang muncul setelah AJAX juga ikut kebaca
  document.body.addEventListener("click", (e) => {
    const btn = e.target.closest("button");
    if (!btn) return;

    // cek teks tombolnya
    if (!btn.innerText.trim().toLowerCase().includes("lihat pola")) return;

    const card = btn.closest("div.relative.w-full.rounded-xl.overflow-hidden");
    if (!card) return;

    // ====== Data untuk modal ======
    const gameTitle = card.querySelector("h4")?.textContent.trim() || "Unknown Game";
    const providerImg = "https://masukkk.online/foto/rtp/assets/provider-game/pragmatic-play/logo.webp";
    const gameImg = card.querySelector("img[src*='game-images']")?.src || "/game-images/default.webp";
    const rtpValue = card.querySelector("span.absolute")?.textContent.trim() || "0%";

    // ===== JAM GACOR =====
    const now = new Date();
    const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
    const formatTime = (d) => {
      let h = d.getHours();
      const m = d.getMinutes().toString().padStart(2, "0");
      const ampm = h >= 12 ? "PM" : "AM";
      h = h % 12 || 12;
      return `${h}:${m} ${ampm}`;
    };
    const jamGacor = `${formatTime(now)} - ${formatTime(oneHourLater)}`;

    // ===== POLA SPIN =====
    const manualRandom = () => Math.floor(Math.random() * (67 - 14 + 1)) + 14;
    const autoOptions = [10, 20, 30, 50, 70, 100];
    const autoRandom = () => autoOptions[Math.floor(Math.random() * autoOptions.length)];

    const polaSpins = [
      { type: "Manual", value: manualRandom() },
      { type: "Automatic", value: autoRandom() },
      { type: "Manual", value: manualRandom() },
      { type: "Manual", value: manualRandom() },
    ];

    let spinHTML = "";
    polaSpins.forEach(spin => {
      const color = spin.type === "Manual" ? "text-red-400" : "text-green-400";
      spinHTML += `<p class="text-sm">Spin: ${spin.value} <span class="${color} font-bold">${spin.type}</span></p>`;
    });

    // ===== DATA PER & CHART =====
    const dataPer = now.toLocaleString("id-ID", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    });

    // Buat 5 data RTP terakhir random
    const rtpData = Array.from({ length: 5 }, () => Math.floor(Math.random() * 50) + 30);
    const rtpLabels = rtpData.map((_, i) => {
      const hour = now.getHours() + i * 0.25; // misal tiap 15 menit
      const h = Math.floor(hour % 24);
      const m = Math.floor((hour % 1) * 60).toString().padStart(2, "0");
      return `${h}:${m}`;
    });

    const content = `
<div class="bg-black rounded-xl max-w-md w-full p-4 relative text-white border border-[#d6b56e] space-y-4">
  <!-- CLOSE BUTTON -->
  <button aria-label="Close detail game" 
        class="absolute top-2 right-2 w-8 h-8 flex items-center justify-center rounded-full bg-red-500 text-white hover:bg-red-600 active:scale-95 transition-all duration-200 shadow-lg z-50">
  <svg xmlns="http://www.w3.org/2000/svg" 
       width="20" height="20" fill="none" stroke="currentColor" 
       stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M18 6 6 18"/>
    <path d="m6 6 12 12"/>
  </svg>
  </button>

  <!-- PROVIDER IMAGE -->
  <div class="text-center p-2 border-b-2 border-yellow-400">
    <img alt="Provider" class="w-12 h-12 object-contain mx-auto" src="${providerImg}">
  </div>

  <!-- GAME IMAGE & TITLE -->
  <div class="text-center p-2 border-b-2 border-yellow-400">
    <img alt="${gameTitle}" class="w-28 h-28 object-contain rounded-lg mx-auto mb-2" src="${gameImg}">
    <h2 class="text-xl font-bold">${gameTitle}</h2>
  </div>

  <!-- RTP -->
  <div class="text-center p-2 border-b-2 border-yellow-400">
    <p class="text-3xl font-semibold">${rtpValue}</p>
  </div>

  <!-- JAM GACOR -->
  <div class="text-center p-2 border-b-2 border-yellow-400 text-sm flex items-center justify-center space-x-1">
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" class="w-5 h-5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
    <span>Gacor: ${jamGacor}</span>
  </div>

  <!-- POLA SPIN -->
  <div class="p-2 border-b-2 border-yellow-400 text-sm space-y-1 text-center">
    ${spinHTML}
    <p class="italic text-xs mt-1">Jika banyak yang pecah, bisa dicoba untuk membeli buy free spin</p>
    <p class="text-xs">Nilai bet disesuaikan dengan nominal deposit masing-masing</p>
  </div>

  <!-- RTP CHART -->
  <div class="p-2 border-b-2 border-yellow-400">
    <p class="text-center text-sm text-gray-300 mb-1">Data per: ${dataPer}</p>
    <h3 class="text-center text-lg font-semibold mb-2">5 RTP Rate Terakhir</h3>
    <div class="bg-[#1a1a3a] p-1 rounded-lg" style="height:150px; width:100%;">
      <canvas id="rtpChart" style="width:100%; height:100%;" role="img"></canvas>
    </div>
  </div>

  <!-- BUTTON -->
  <div class="text-center p-2">
    <a href="https://rebrand.ly/untungbet/login" target="_blank" rel="noopener noreferrer" class="w-full inline-block font-semibold px-3 py-1 rounded-md transition-all duration-300 text-sm border border-[#d6b56e] hover:shadow-lg hover:scale-105 cursor-pointer" style="background: linear-gradient(
  rgb(2, 15, 50),
  rgb(10, 25, 70),
  rgb(20, 35, 90),
  rgb(2, 15, 50)
);
 color: white;">Main Sekarang</a>
  </div>
</div>
`;

    // buka modal dengan content
    openModal(content);

    // ===== INISIALISASI CHART =====
    const ctx = document.getElementById('rtpChart').getContext('2d');
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: rtpLabels,
        datasets: [{
          label: 'RTP (%)',
          data: rtpData,
          fill: false,
          borderColor: '#00FFAA',
          tension: 0.4,
          pointBackgroundColor: '#00FFAA',
          pointRadius: 4
        }]
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: false }
        },
        scales: {
          y: {
            min: 0,
            max: 100
          }
        }
      }
    });
  });
});


document.addEventListener("click", (e) => {
  // cek klik pada tombol simulasi (cocokkan class di HTML kamu)
  const btn = e.target.closest(".bg-green-600"); // ganti sesuai class tombolmu
  if (!btn) return; // kalau bukan klik tombol simulasi â†’ stop

  // hapus modal/overlay lama
  document.querySelectorAll(".simulasi-modal").forEach(m => m.remove());
  document.querySelectorAll(".simulasi-overlay").forEach(o => o.remove());

  // ambil info dari card terkait
  const card = btn.closest(".relative.w-full.rounded-xl.overflow-hidden");
  const gameTitle = card?.querySelector("h4 span")?.textContent.trim() || "UNTUNGBET";

  // ambil rtp persen misalnya 39% â†’ 39
  const rtpStr = card?.querySelector(".animate-progress")?.style.width || "39%";
  const rtpNum = parseFloat(rtpStr.replace('%', '')) || 39;

  // jam gacor otomatis 1 jam
  const now = new Date();
  const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
  const formatTime = (d) => {
    let h = d.getHours();
    const m = d.getMinutes().toString().padStart(2, "0");
    const ampm = h >= 12 ? "PM" : "AM";
    h = h % 12 || 12;
    return `${h}:${m} ${ampm}`;
  };
  const jamGacor = `${formatTime(now)} - ${formatTime(oneHourLater)}`;

  // overlay
  const overlay = document.createElement("div");
  overlay.className = "simulasi-overlay";
  Object.assign(overlay.style, {
    position: "fixed",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0,0,0,0.7)",
    zIndex: "9998"
  });
  document.body.appendChild(overlay);

  // modal
  const modal = document.createElement("div");
  modal.className = "simulasi-modal bg-black rounded-xl max-w-md w-full p-4 relative text-white border-2 border-[#d6b56e]";
  Object.assign(modal.style, {
    position: "fixed",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    zIndex: "9999"
  });
  modal.innerHTML = `
    <button aria-label="Close simulation modal" class="absolute top-2 right-2 bg-red-500 text-white w-6 h-6 flex items-center justify-center rounded-full hover:bg-red-600 active:scale-95 transition-all duration-200" id="closeSimulasiBtn">
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
      </svg>
    </button>
    <h2 class="text-center text-xl font-bold mb-4">Simulasi Kemenangan</h2>
    <p class="text-center text-md mb-2">Game: ${gameTitle}</p>
    <p class="text-center text-md mb-4">RTP: ${rtpNum}%</p>
    <form class="space-y-4 mb-4">
      <div>
        <label class="block text-sm mb-1">Nilai Bet</label>
        <input placeholder="Masukkan nilai bet (Rp)" required class="input-rp w-full p-2 rounded-md bg-[#1a1a3a] text-white border border-[#d6b56e]" type="text">
      </div>
      <div>
        <label class="block text-sm mb-1">Jumlah Modal</label>
        <input placeholder="Masukkan jumlah modal (Rp)" required class="input-rp w-full p-2 rounded-md bg-[#1a1a3a] text-white border border-[#d6b56e]" type="text">
      </div>
      <div class="flex justify-center">
        <button type="submit" class="w-full text-center font-semibold px-4 py-2 rounded-md text-sm border border-[#d6b56e] transition-all duration-300 hover:shadow-lg hover:scale-105" style="background: linear-gradient(
  rgb(2, 15, 50),
  rgb(10, 25, 70),
  rgb(20, 35, 90),
  rgb(2, 15, 50)
);
 color: #fff;">Simulasi</button>
      </div>
    </form>
    <div id="hasilSimulasi"></div>
  `;
  document.body.appendChild(modal);

  // close modal
  const closeModal = () => { modal.remove(); overlay.remove(); };
  modal.querySelector("#closeSimulasiBtn").addEventListener("click", closeModal);
  overlay.addEventListener("click", closeModal);

  // format input Rp
  const rpInputs = modal.querySelectorAll(".input-rp");
  rpInputs.forEach(inp => {
    inp.addEventListener("input", () => {
      let angka = inp.value.replace(/[^0-9]/g, "");
      if (angka === "") {
        inp.value = "";
        return;
      }
      angka = Number(angka).toLocaleString("id-ID");
      inp.value = "Rp " + angka;
    });
    inp.addEventListener("keydown", e => {
      if (["Backspace","Delete","ArrowLeft","ArrowRight","Tab"].includes(e.key)) return;
      if (!/[0-9]/.test(e.key)) e.preventDefault();
    });
  });

  // handle submit simulasi
  modal.querySelector("form").addEventListener("submit", e => {
    e.preventDefault();
    const vals = Array.from(rpInputs).map(i =>
      i.value.replace(/[^0-9]/g, "")
    );
    const betNum = Number(vals[0] || 0);
    const modalNum = Number(vals[1] || 0);
    const bet = betNum.toLocaleString("id-ID");
    const modalAmount = modalNum.toLocaleString("id-ID");

    // hitung potensi menang (random 3â€“5Ã— modal)
    const randomMultiplier = (Math.random() * (5 - 3) + 3); // 3â€“5
    const potensi = Math.floor(modalNum * randomMultiplier).toLocaleString("id-ID");

    // hitung persentase menang sesuai RTP
    const persenMenang = rtpNum;
    const persenKalah = 100 - persenMenang;
    const persenExtra = Math.max(0, 100 - (persenMenang + persenKalah));

    const hasilDiv = modal.querySelector("#hasilSimulasi");
   hasilDiv.innerHTML = `
  <div class="mt-4 p-4 rounded-xl bg-[#1a1a3a] border border-[#d6b56e] text-white">
    <h4 class="text-lg font-bold mb-4 text-center">Probabilitas Kemenangan</h4>
    <div class="flex flex-col md:flex-row items-center justify-center gap-6">
      <div class="flex-shrink-0">
        <canvas id="myChart" width="160" height="160"></canvas>
      </div>
      <div class="text-sm text-left space-y-1 w-full md:w-auto">
        <p><span class="inline-block w-3 h-3 bg-[#00ff9d] mr-1"></span>Menang</p>
        <p><span class="inline-block w-3 h-3 bg-[#e73e4f] mr-1"></span>Kalah</p>
        <p><span class="inline-block w-3 h-3 bg-[#ffd700] mr-1"></span>Persentase Menang</p>
        <hr class="my-2 border-[#d6b56e]" />
        <p>Taruhan: Rp ${bet}</p>
        <p>Modal: Rp ${modalAmount}</p>
        <p>Gacor: ${jamGacor}</p>
        <p>Potensi: Rp ${potensi}</p>
      </div>
    </div>
  </div>
  <p class="text-sm font-bold text-green-400 animate-pulse text-center mt-2">Potensi Menang: Rp ${potensi}</p>
  <div class="space-y-1 text-xs text-white text-center mt-2">
    <p class="font-bold text-red-400">CARI GAME DENGAN RTP â‰¥ 80%!</p>
    <p class="italic">Peluang menang sesuai RTP dan strategi.</p>
    <p class="italic">Hadiah potensial dari taruhan dan modal.</p>
  </div>
`;


    // bikin chart lingkaran
    const ctx = hasilDiv.querySelector("#myChart");
    new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['Menang', 'Kalah', 'Persentase Menang'],
        datasets: [{
          data: [persenMenang, persenKalah, persenExtra],
          backgroundColor: ['#00ff9d', '#e73e4f', '#ffd700'],
          borderColor: '#fff',
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '70%',
        plugins: { legend: { display: false } }
      }
    });
  });
});


document.addEventListener("DOMContentLoaded", () => {
  // overlay gelap
  const overlay = document.createElement("div");
  overlay.className = "welcome-overlay";
  Object.assign(overlay.style, {
    position: "fixed",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0,0,0,0.7)",
    zIndex: "9998"
  });
  document.body.appendChild(overlay);

  // modal box
  const modal = document.createElement("div");
  modal.className =
    "welcome-modal bg-black rounded-xl max-w-md w-full p-4 relative text-white border-2 border-[#d6b56e]";
  Object.assign(modal.style, {
    position: "fixed",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    zIndex: "9999"
  });

  // isi modal
  modal.innerHTML = `
    <button aria-label="Close modal" class="absolute top-2 right-2 bg-red-500 text-white w-6 h-6 flex items-center justify-center rounded-full hover:bg-red-600 active:scale-95 transition-all duration-200" id="closeWelcomeModal">
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
      </svg>
    </button>
    <h2 class="text-center text-2xl font-bold mb-3">Hallo Selamat Datang</h2>
    <h3 class="text-center text-lg mb-3">Dapatkan informasi Seputar RTP dan Odds</h3>
    <div class="flex justify-center mb-3">
      <div class="relative w-full h-90">
        <img alt="Modal Image" decoding="async" class="object-contain rounded-md" src="https://api2-utb.imgnxb.com/images/YxpPgAbYuyo/id_popup_44d3192a-247d-4e87-94be-5baacf80ac01_1714556737507.jpg" style="width:100%; height:auto;">
      </div>
    </div>
    <p class="text-center text-sm mb-3">Anda dapat melihat Pola dan Simulasi di RTP ini dan pastikan pilih game yang RTP nya di atas 90% keatas</p>
    <div class="flex justify-center">
      <a href="https://t.ly/UNTUNGBET" target="_blank" rel="noopener noreferrer" class="w-full text-center font-semibold px-4 py-2 rounded-md text-sm border border-[#d6b56e] transition-all duration-300 hover:shadow-lg hover:scale-105" style="background: linear-gradient(
  rgb(2, 15, 50),
  rgb(10, 25, 70),
  rgb(20, 35, 90),
  rgb(2, 15, 50)
);
 color: #fff;">DAFTAR</a>
    </div>
  `;
  document.body.appendChild(modal);

  // fungsi close
  const closePopup = () => {
    modal.remove();
    overlay.remove();
  };
  modal.querySelector("#closeWelcomeModal").addEventListener("click", closePopup);
  overlay.addEventListener("click", closePopup);
});