Auto Claim Battle Mine Reward (Anti-sleep Optimized)

Tự động nhận phần thưởng Mine

// ==UserScript==
// @name         Auto Claim Battle Mine Reward (Anti-sleep Optimized)
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  Tự động nhận phần thưởng Mine
// @author       KeshiNguyen
// @match        https://cmangax2.com/*
// @grant        none
// ==/UserScript==
(function () {
  'use strict';

  // ======= GIỮ TAB KHÔNG BỊ TREO =======
  const keepTabAwake = () => {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    setInterval(() => {
      window.focus();
      document.dispatchEvent(new MouseEvent('mousemove'));
    }, 20000);
  };

  // ======= QUẢN LÝ TIMEOUT VÀ INTERVAL =======
  let intervals = [];
  let timeouts = [];
    let baseUrl = "https://cmangax2.com"

  const clearAll = () => {
    intervals.forEach(clearInterval);
    timeouts.forEach(clearTimeout);
    intervals = [];
    timeouts = [];
  };

  // ======= PHẦN CHÍNH NHẬN THƯỞNG =======
  function startAutoClaim() {
    const SCORE_URL = `${baseUrl}/api/score_list?type=battle_mine_target&target=${window.my_character}`;
    const CLAIM_URL = `${baseUrl}/assets/ajax/character_activity.php`;
    async function fetchScore() {
      try {
        const res = await fetch(SCORE_URL);
        return res.ok ? await res.json() : null;
      } catch (err) {
        console.error('[x] Lỗi fetchScore:', err);
        return null;
      }
    }

    async function claimReward() {
      try {
        const res = await fetch(CLAIM_URL, {
          method: 'POST',
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
          body: new URLSearchParams({
            action: 'battle_mine_take_reward',
            target: 'public'
          })
        });
        const result = await res.json();
        console.log('[✓] Nhận thưởng:', result);
        clearAll();
        timeouts.push(setTimeout(checkAndClaimReward, 60000)); // Check lại sau 1 phút
      } catch (err) {
        console.error('[x] Lỗi claimReward:', err);
      }
    }

    async function checkAndClaimReward() {
      try {
        const data = await fetchScore();
        if (!data?.length) return console.log('[!] Đã bị sút khỏi hmk');

        const {miner} = JSON.parse(data[0].data);
        console.log(`[i] Thời gian hiện tại: ${miner.times} phút`);

        if (miner.times >= 60) {
          await claimReward();
        } else {
          schedule(miner.times);
        }
      } catch (err) {
        console.error('[x] Lỗi checkAndClaim:', err);
      }
    }

    function schedule(currentMinutes) {
      clearAll(); // Clear trước khi tạo mới

      // Tính thời gian chờ chính xác
      const waitMinutes = 59 - currentMinutes;
      const waitMs = waitMinutes * 60000;
      console.log(`[~] Đợi ${waitMinutes} phút`);

      // Timer chính xác
      timeouts.push(setTimeout(checkAndClaimReward, waitMs));

      // Backup check mỗi phút
      intervals.push(setInterval(checkAndClaimReward, 60000));
    }

    checkAndClaimReward();
  }

  window.addEventListener('load', () => {
    keepTabAwake();
    startAutoClaim();
  });
})();