// AdBlockMaxxer — Twitch channel-points auto-claim (ISOLATED world, twitch.tv).
//
// Twitch drops a floating "Claim Bonus" coin every ~15 min while you watch. This clicks it
// the instant it appears so you never miss the bonus. Honours the "twitchPoints" toggle and
// snooze. Purely a convenience clicker — it never touches the stream or ads.

(function () {
  "use strict";

  let enabled = true;
  let snoozeUntil = 0;
  let perf = false;
  const KEY = "twitchPoints";

  function active() { return enabled && Date.now() >= snoozeUntil; }

  chrome.storage.local.get([KEY, "snoozeUntil", "perfMode"], (r) => {
    if (r && r[KEY] === false) enabled = false;
    snoozeUntil = (r && r.snoozeUntil) || 0;
    if (r && r.perfMode) perf = true;
    startLoop();
  });
  chrome.storage.onChanged.addListener((c) => {
    if (c[KEY]) enabled = c[KEY].newValue !== false;
    if (c.snoozeUntil) snoozeUntil = c.snoozeUntil.newValue || 0;
    if (c.perfMode) { perf = !!c.perfMode.newValue; startLoop(); }
  });

  let lastClaim = 0;
  function claim() {
    if (!active()) return;
    // The claimable coin lives inside the community-points summary; selectors drift, so try a few.
    const btn =
      document.querySelector(".claimable-bonus__icon") ||
      document.querySelector('[data-test-selector="community-points-summary"] button .claimable-bonus__icon') ||
      document.querySelector('button[aria-label*="Claim Bonus" i]');
    if (!btn) return;
    const clickable = btn.closest("button") || btn;
    const now = Date.now();
    if (now - lastClaim < 3000) return; // de-dupe rapid mutations of the same coin
    lastClaim = now;
    clickable.click();
  }

  // The 4s interval already claims any coin within 4s (it sits there until clicked).
  // The observer just makes it snappier — but Twitch chat fires hundreds of mutations/sec,
  // so we coalesce them to one probe per second instead of running querySelector on each.
  let loopIv = null;
  function startLoop() {
    if (loopIv) clearInterval(loopIv);
    loopIv = setInterval(claim, perf ? 8000 : 4000);
  }
  startLoop();
  let scheduled = false;
  const mo = new MutationObserver(() => {
    if (scheduled) return;
    scheduled = true;
    setTimeout(() => { scheduled = false; claim(); }, 1000);
  });
  function attach() {
    if (document.body) mo.observe(document.body, { childList: true, subtree: true });
    else requestAnimationFrame(attach);
  }
  attach();
})();
