/**
 * PlayCraft Tracking Adapter (Bridge Layer)
 *
 * 职责：在正确的生命周期节点调用 window.PlayCraftTracking 的方法。
 * 渠道埋点逻辑由 @playcraft/ads-tracking 的 tracking 模块提供（构建时自动提取注入）。
 * 如果 ads-tracking 未注入，adapter 的调用会静默忽略。
 *
 * 新 API 对照（@playcraft/ads-tracking v1.0.0）：
 *   onPlaycraftTrackingInit      - SDK 初始化开始
 *   onPlaycraftTrackingLoading   - 游戏资源加载中
 *   onPlaycraftTrackingLoaded    - 资源加载完成、主场景就绪
 *   onPlaycraftChallengeStart    - 游戏挑战开始（首次用户交互）
 *   onPlaycraftChallengeProgress - 进度上报 (percent 0-100)，内部自动触发里程碑
 *   onPlaycraftChallengeSuccess  - 游戏挑战成功
 *   onPlaycraftChallengeFailed   - 游戏挑战失败
 *   onPlaycraftChallengeFinish   - 游戏结束
 *   onPlaycraftInstall           - 点击安装
 *   onPlaycraftRetry             - 重试游戏
 */
(function() {
  'use strict';

  var _config = (typeof window !== 'undefined' && window.__PLAYCRAFT_TRACKING_CONFIG__) || {};
  var adNetwork = _config.adNetwork || '';
  var totalInteractions = _config.totalInteractions || 0;

  function getTracking() {
    return window.PlayCraftTracking || null;
  }

  function call(method, args) {
    var t = getTracking();
    if (t && typeof t[method] === 'function') {
      t[method].apply(t, args || []);
    }
  }

  // ===== 进度上报（兼容旧的 setTotalInteractions + checkInteractionProgress）=====
  // 新包只提供 onPlaycraftChallengeProgress(percent 0-100)，里程碑由 SDK 内部处理。
  // 这里维护 total 状态，将 (current/total*100) 转换为百分比上报。
  var _total = totalInteractions > 0 ? totalInteractions : 0;
  function setTotal(n) {
    if (typeof n === 'number' && n > 0) _total = n;
  }
  function reportProgress(current) {
    if (typeof current !== 'number') return;
    var percent;
    if (_total > 0) {
      percent = Math.min(100, Math.max(0, (current / _total) * 100));
    } else {
      // 未设置 total 时，把传入值当作已经是百分比
      percent = Math.min(100, Math.max(0, current));
    }
    call('onPlaycraftChallengeProgress', [percent]);
  }

  // ===== 自动埋点 =====

  // 1. onPlaycraftTrackingInit（立即）
  call('onPlaycraftTrackingInit', [adNetwork]);

  // 2. onPlaycraftTrackingLoading（页面加载完成）
  if (document.readyState === 'complete') {
    setTimeout(function() { call('onPlaycraftTrackingLoading', [adNetwork]); }, 0);
  } else {
    window.addEventListener('load', function() { call('onPlaycraftTrackingLoading', [adNetwork]); });
  }

  // 2.5 onPlaycraftTrackingLoaded（游戏完全就绪，可交互）
  // 优先级: playcraft:interactive 事件 > PlayCanvas app.on('start') fallback
  var _interactive = false;
  function triggerInteractive() {
    if (_interactive) return;
    _interactive = true;
    call('onPlaycraftTrackingLoaded', [adNetwork]);
  }
  // 优先监听游戏主动派发的 playcraft:interactive
  document.addEventListener('playcraft:interactive', triggerInteractive);
  // Fallback: 如果游戏没有派发 playcraft:interactive，则在 PlayCanvas app start 后自动触发
  var _pcPollCount = 0;
  function pollPlayCanvasApp() {
    if (_interactive) return; // 已被 playcraft:interactive 触发，不再 fallback
    var app = (typeof pc !== 'undefined' && pc.Application && pc.Application.getApplication)
      ? pc.Application.getApplication() : null;
    if (app) {
      if (app._time > 0 || app.frame > 0) {
        triggerInteractive();
      } else {
        app.once('start', triggerInteractive);
      }
      return;
    }
    if (++_pcPollCount < 200) setTimeout(pollPlayCanvasApp, 50);
  }
  setTimeout(pollPlayCanvasApp, 0);

  // 3. onPlaycraftChallengeStart（首次用户交互，只触发一次）
  var _interacted = false;
  function onFirstInteraction() {
    if (_interacted) return;
    _interacted = true;
    call('onPlaycraftChallengeStart', [adNetwork]);
    document.removeEventListener('touchstart', onFirstInteraction, true);
    document.removeEventListener('mousedown', onFirstInteraction, true);
    document.removeEventListener('pointerdown', onFirstInteraction, true);
  }
  document.addEventListener('touchstart', onFirstInteraction, true);
  document.addEventListener('mousedown', onFirstInteraction, true);
  document.addEventListener('pointerdown', onFirstInteraction, true);

  // 4. onPlaycraftInstall（hook CTA adapter）
  var _ctaAttempts = 0;
  function hookCTA() {
    if (window.PlayCraftCTA && window.PlayCraftCTA.jump) {
      var _orig = window.PlayCraftCTA.jump;
      window.PlayCraftCTA.jump = function(opts) {
        call('onPlaycraftInstall', [adNetwork]);
        _orig.call(window.PlayCraftCTA, opts);
      };
      if (window.jump2AppStore) window.jump2AppStore = window.PlayCraftCTA.jump;
      return;
    }
    if (++_ctaAttempts < 50) setTimeout(hookCTA, 100);
  }
  setTimeout(hookCTA, 0);

  // ===== 游戏协作事件（CustomEvent）=====
  var once = {};
  function listenOnce(name, method, extraArgs) {
    document.addEventListener(name, function() {
      if (once[name]) return; once[name] = true;
      call(method, extraArgs || [adNetwork]);
    });
  }
  function listen(name, method, extraArgs) {
    document.addEventListener(name, function() {
      call(method, extraArgs || [adNetwork]);
    });
  }

  listenOnce('playcraft:finish', 'onPlaycraftChallengeFinish');
  listen('playcraft:success', 'onPlaycraftChallengeSuccess');
  listen('playcraft:failed', 'onPlaycraftChallengeFailed');
  document.addEventListener('playcraft:retry', function() {
    once['playcraft:finish'] = false;
    call('onPlaycraftRetry', [adNetwork]);
  });
  document.addEventListener('playcraft:setTotal', function(e) {
    var d = e.detail;
    var n = typeof d === 'number' ? d : (d && d.total);
    if (typeof n === 'number') setTotal(n);
  });
  document.addEventListener('playcraft:progress', function(e) {
    var d = e.detail;
    // 兼容两种传参：number（当前值）或 { current, total, percent }
    if (typeof d === 'number') {
      reportProgress(d);
    } else if (d && typeof d === 'object') {
      if (typeof d.total === 'number') setTotal(d.total);
      if (typeof d.percent === 'number') {
        call('onPlaycraftChallengeProgress', [Math.min(100, Math.max(0, d.percent))]);
      } else if (typeof d.current === 'number') {
        reportProgress(d.current);
      }
    }
  });
})();
