// rtp.js
document.addEventListener("DOMContentLoaded", () => {
  function updateRTP() {
    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)"; // hijau
        gameTitle.innerHTML = gameTitle.textContent; // reset jadi hitam
      } else if (rtp >= 30) {
        progressBar.style.backgroundColor = "rgb(250,204,21)"; // kuning
        gameTitle.innerHTML = gameTitle.textContent; // reset jadi hitam
      } else {
        progressBar.style.backgroundColor = "rgb(239,68,68)"; // merah
        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);
      }
    });
  }

  updateRTP();
  setInterval(updateRTP, 600000);
});

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

    if (!searchInput) return;

    searchInput.addEventListener("input", () => {
        const keyword = searchInput.value.toLowerCase().trim();

        gameCards.forEach(card => {
            const gameNameEl = card.querySelector("h4");
            const gameName = gameNameEl ? gameNameEl.textContent.toLowerCase() : "";

            if (gameName.includes(keyword)) {
                card.style.display = ""; // tampilkan
            } else {
                card.style.display = "none"; // sembunyikan
            }
        });
    });
});


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

  const overlay = document.createElement("div");
  overlay.id = "overlayPola";
  overlay.style.display = "none";
  overlay.style.position = "fixed";
  overlay.style.top = "0";
  overlay.style.left = "0";
  overlay.style.width = "100%";
  overlay.style.height = "100%";
  overlay.style.backgroundColor = "rgba(0,0,0,0.7)";
  overlay.style.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);

  // ===== TOMBOL LIHAT POLA =====
  const buttons = Array.from(document.querySelectorAll("button"))
    .filter(btn => btn.innerText.trim().toLowerCase().includes("lihat pola"));

  buttons.forEach(btn => {
    btn.removeAttribute("disabled");
    btn.addEventListener("click", () => {
      const card = btn.closest("div.relative.w-full.rounded-xl.overflow-hidden");
      if (!card) return;

      const gameTitle = card.querySelector("h4")?.textContent.trim() || "Unknown Game";
      const providerImg = "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 rtpSection = `
<div class="mb-1.5 text-center">
  <p class="text-sm text-gray-300 mb-1.5">Data per: ${dataPer}</p>
  <h3 class="text-center text-lg font-semibold text-white mb-1.5">5 RTP Rate Terakhir</h3>
  <div class="bg-[#1a1a3a] p-2 rounded-lg" style="height: 130px;">
    <canvas id="rtpChart" role="img" height="130"></canvas>
  </div>
</div>
      `;

      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/login-untungbet" 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: rgb(28, 37, 38);">Main Sekarang</a>
  </div>

</div>
`;


      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("DOMContentLoaded", () => {
  document.querySelectorAll(".text-black.bg-green-600").forEach(btn => {
    btn.addEventListener("click", () => {
      const card = btn.closest(".relative.w-full.rounded-xl.overflow-hidden");
      const gameTitle = card?.querySelector("h4 span")?.textContent.trim() || "Nama Game";
      // ambil rtp persen misalnya 39% → 39
      const rtpStr = card?.querySelector(".animate-progress")?.style.width || "39%";
      const rtpNum = parseFloat(rtpStr) || 39;

      // overlay
      const overlay = document.createElement("div");
      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 = "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: rgb(28, 37, 38);">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
      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)); // sisanya  

        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-row items-center justify-center gap-4">
              <canvas id="myChart" width="120" height="120"></canvas>
              <div class="text-xs text-left space-y-1">
                <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>
                <p>Taruhan: Rp ${bet}</p>
                <p>Modal: Rp ${modalAmount}</p>
                <p>Gacor: 012:52-03:22</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");
        ctx.style.width = "120px";
        ctx.style.height = "120px";
        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: false,
            cutout: '70%',
            plugins: { legend: { display: false } }
          }
        });
      });
    });
  });
});


document.addEventListener("DOMContentLoaded", () => {
  // BUAT overlay gelap
  const overlay = document.createElement("div");
  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);

  // BUAT modal
  const modal = document.createElement("div");
  modal.className = "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"
  });

  // HTML modal persis yang kamu kirim
  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://cobahalbaru.site/masuk/popup.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: rgb(28, 37, 38);">DAFTAR</a>
    </div>
  `;
  document.body.appendChild(modal);

  // fungsi close
  const closePopup = () => {
    modal.remove();
    overlay.remove();
  };

  // tombol X
  modal.querySelector("#closeWelcomeModal").addEventListener("click", closePopup);
  // klik luar modal (overlay)
  overlay.addEventListener("click", closePopup);
});

