/**
 * PlayCraft CTA Adapter - 统一的跳转应用商店适配器
 * 
 * 提供统一的 API 接口，自动适配不同渠道的 CTA 调用方式
 * 游戏开发者只需调用 window.PlayCraftCTA.jump() 即可
 * 
 * 支持的广告渠道:
 *   MRAID       - mraid.open(url)
 *   DAPI        - dapi.openStoreUrl()
 *   Nucleo      - NUC.trigger.convert(url)
 *   BigoAds     - BGY_MRAID.open()
 *   Facebook    - FbPlayableAd.onCTAClick()
 *   Snapchat    - snapchatCta()
 *   Smadex      - smxTracking.redirect()
 *   Vungle      - parent.postMessage('download','*')
 *   Google      - ExitApi.exit()
 *   Mintegral   - window.install()
 *   Tapjoy      - TJ_API.click()
 *   TikTok      - window.openAppStore()
 *   其他/兜底    - window.open(url)
 */
(function() {
  'use strict';

  // 商店跳转地址：优先读取构建时注入的全局变量，无则留空（由平台 SDK 接管）
  var _storeUrls = (typeof window !== 'undefined' && window.__PLAYCRAFT_STORE_URLS__) || {};
  var IOS_STORE_URL = _storeUrls.ios || '';
  var ANDROID_STORE_URL = _storeUrls.android || '';

  function getOS() {
    var ua = navigator.userAgent || '';
    if (/iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) {
      return 'ios';
    } else if (/Android/i.test(ua)) {
      return 'android';
    }
    return 'unknown';
  }

  function getStoreUrl() {
    return getOS() === 'ios' ? IOS_STORE_URL : ANDROID_STORE_URL;
  }

  // CTA 适配器类
  function CTAAdapter() {
    this.platform = null;
    this.isReady = false;
    this.readyCallbacks = [];
    
    // 自动检测并初始化
    this.detectPlatform();
    this.initialize();
  }

  /**
   * 检测当前运行的平台
   * 通过检测全局对象来判断广告渠道
   */
  CTAAdapter.prototype.detectPlatform = function() {
    if (typeof FbPlayableAd !== 'undefined') {
      this.platform = 'facebook'; // Facebook / Moloco / Remerge
    } else if (typeof mraid !== 'undefined') {
      this.platform = 'mraid'; // MRAID 系列（AppLovin, ironSource, Unity Ads, Snapchat, Liftoff, InMobi, Adikteev）
    } else if (typeof dapi !== 'undefined') {
      this.platform = 'dapi'; // ironSource DAPI
    } else if (typeof ExitApi !== 'undefined') {
      this.platform = 'google'; // Google Ads
    } else if (typeof window.BGY_MRAID !== 'undefined') {
      this.platform = 'bigo'; // BIGO Ads
    } else if (typeof snapchatCta === 'function') {
      this.platform = 'snapchat'; // Snapchat
    } else if (typeof window.openAppStore === 'function') {
      this.platform = 'tiktok'; // TikTok / Pangle
    } else if (typeof window.install === 'function') {
      this.platform = 'mintegral'; // Mintegral
    } else if (typeof window.TJ_API !== 'undefined' && typeof window.TJ_API.click === 'function') {
      this.platform = 'tapjoy'; // Tapjoy
    } else if (typeof window.NUC !== 'undefined' && window.NUC.trigger && typeof window.NUC.trigger.convert === 'function') {
      this.platform = 'nucleo'; // Nucleo
    } else if (typeof window.smxTracking !== 'undefined' && typeof window.smxTracking.redirect === 'function') {
      this.platform = 'smadex'; // Smadex
    } else {
      this.platform = 'unknown';
      console.warn('[PlayCraft CTA] 未检测到已知的广告平台 API');
    }
    
    console.log('[PlayCraft CTA] 检测到平台:', this.platform);
  };

  /**
   * 初始化平台 API
   */
  CTAAdapter.prototype.initialize = function() {
    var self = this;
    
    switch (this.platform) {
      case 'facebook':
      case 'google':
      case 'bigo':
      case 'snapchat':
      case 'tiktok':
      case 'mintegral':
      case 'tapjoy':
      case 'nucleo':
      case 'smadex':
        // 以上平台通常直接就绪
        this.isReady = true;
        this.notifyReady();
        break;
        
      case 'mraid':
        // MRAID 需要等待 ready 事件
        if (mraid.isReady && mraid.isReady()) {
          this.isReady = true;
          this.notifyReady();
        } else if (mraid.addEventListener) {
          mraid.addEventListener('ready', function() {
            self.isReady = true;
            self.notifyReady();
            console.log('[PlayCraft CTA] MRAID ready');
          });
        }
        break;
        
      case 'dapi':
        // DAPI 需要等待 ready 事件
        if (dapi.isReady && dapi.isReady()) {
          this.isReady = true;
          this.notifyReady();
        } else if (dapi.addEventListener) {
          dapi.addEventListener('ready', function() {
            self.isReady = true;
            self.notifyReady();
            console.log('[PlayCraft CTA] DAPI ready');
          });
        }
        break;
        
      default:
        // 未知平台，标记为就绪（使用降级方案）
        this.isReady = true;
        this.notifyReady();
        break;
    }
  };

  /**
   * 通知所有等待的回调
   */
  CTAAdapter.prototype.notifyReady = function() {
    for (var i = 0; i < this.readyCallbacks.length; i++) {
      try {
        this.readyCallbacks[i]();
      } catch (e) {
        console.error('[PlayCraft CTA] Ready callback error:', e);
      }
    }
    this.readyCallbacks = [];
  };

  /**
   * 注册就绪回调
   */
  CTAAdapter.prototype.onReady = function(callback) {
    if (this.isReady) {
      // 已经就绪，立即调用
      setTimeout(callback, 0);
    } else {
      // 等待就绪
      this.readyCallbacks.push(callback);
    }
  };

  /**
   * 跳转到应用商店（主方法）
   * @param {Object} options - 可选配置
   * @param {string} options.url - 自定义 URL（不推荐，仅用于测试）
   */
  CTAAdapter.prototype.jump = function(options) {
    options = options || {};
    
    if (!this.isReady) {
      console.warn('[PlayCraft CTA] API 尚未就绪，跳转可能失败');
    }

    // Store URL 空值预警
    var _jumpUrl = options.url || getStoreUrl();
    if (!_jumpUrl) {
      console.error('[PlayCraft CTA] Store URL is not configured. Platform:', this.platform,
        '| OS:', getOS(),
        '| iOS URL:', IOS_STORE_URL,
        '| Android URL:', ANDROID_STORE_URL);
    }
    
    console.log('[PlayCraft CTA] 跳转应用商店 - 平台:', this.platform);
    
    try {
      switch (this.platform) {
        case 'facebook':
          // Facebook / Moloco / Remerge
          if (typeof FbPlayableAd !== 'undefined' && FbPlayableAd.onCTAClick) {
            FbPlayableAd.onCTAClick();
          }
          break;
          
        case 'mraid':
          // MRAID 系列（AppLovin, ironSource, Unity Ads, Snapchat, Liftoff, InMobi, Adikteev）
          if (typeof mraid !== 'undefined' && mraid.open) {
            mraid.open(options.url || getStoreUrl());
          }
          break;
          
        case 'dapi':
          // ironSource DAPI
          if (typeof dapi !== 'undefined' && dapi.openStoreUrl) {
            dapi.openStoreUrl();
          }
          break;
          
        case 'google':
          // Google Ads
          if (typeof ExitApi !== 'undefined' && ExitApi.exit) {
            ExitApi.exit();
          }
          break;
          
        case 'bigo':
          // BIGO Ads
          if (typeof window.BGY_MRAID !== 'undefined' && window.BGY_MRAID.open) {
            window.BGY_MRAID.open();
          }
          break;
          
        case 'snapchat':
          // Snapchat
          if (typeof snapchatCta === 'function') {
            snapchatCta();
          }
          break;

        case 'tiktok':
          // TikTok / Pangle
          if (typeof window.openAppStore === 'function') {
            window.openAppStore();
          }
          break;

        case 'mintegral':
          // Mintegral
          if (typeof window.install === 'function') {
            window.install();
          }
          break;

        case 'tapjoy':
          // Tapjoy
          if (typeof window.TJ_API !== 'undefined' && window.TJ_API.click) {
            window.TJ_API.click();
          }
          break;

        case 'nucleo':
          // Nucleo
          if (typeof window.NUC !== 'undefined' && window.NUC.trigger && window.NUC.trigger.convert) {
            window.NUC.trigger.convert(options.url || getStoreUrl());
          }
          break;

        case 'smadex':
          // Smadex
          if (typeof window.smxTracking !== 'undefined' && window.smxTracking.redirect) {
            window.smxTracking.redirect();
          }
          break;
          
        default:
          // 降级方案：尝试所有可能的 API
          console.warn('[PlayCraft CTA] 未知平台，尝试降级方案');
          this.fallbackJump(options.url);
          break;
      }
    } catch (e) {
      console.error('[PlayCraft CTA] 跳转失败:', e);
      // 尝试降级方案
      this.fallbackJump(options.url);
    }
  };

  /**
   * 降级跳转方案 - 按优先级尝试各种 API，最终兜底到 window.open
   */
  CTAAdapter.prototype.fallbackJump = function(url) {
    var storeUrl = url || getStoreUrl();

    // 按优先级尝试各种 API
    if (typeof FbPlayableAd !== 'undefined' && FbPlayableAd.onCTAClick) {
      FbPlayableAd.onCTAClick();
    } else if (typeof mraid !== 'undefined' && mraid.open) {
      mraid.open(storeUrl);
    } else if (typeof dapi !== 'undefined' && dapi.openStoreUrl) {
      dapi.openStoreUrl();
    } else if (typeof ExitApi !== 'undefined' && ExitApi.exit) {
      ExitApi.exit();
    } else if (typeof window.BGY_MRAID !== 'undefined' && window.BGY_MRAID.open) {
      window.BGY_MRAID.open();
    } else if (typeof snapchatCta === 'function') {
      snapchatCta();
    } else if (typeof window.openAppStore === 'function') {
      window.openAppStore();
    } else if (typeof window.install === 'function') {
      window.install();
    } else if (typeof window.TJ_API !== 'undefined' && window.TJ_API.click) {
      window.TJ_API.click();
    } else if (typeof window.NUC !== 'undefined' && window.NUC.trigger && window.NUC.trigger.convert) {
      window.NUC.trigger.convert(storeUrl);
    } else if (typeof window.smxTracking !== 'undefined' && window.smxTracking.redirect) {
      window.smxTracking.redirect();
    } else {
      // 最后的降级方案：直接打开应用商店链接
      console.warn('[PlayCraft CTA] 使用降级方案: window.open');
      try {
        parent.postMessage('download', '*');
      } catch (e) {
        // Vungle 兜底
      }
      if (!storeUrl) {
        console.error('[PlayCraft CTA] Store URL is not configured for this platform. Aborting redirect.');
      } else {
        window.open(storeUrl, '_blank');
      }
    }
  };

  /**
   * 获取当前平台信息
   */
  CTAAdapter.prototype.getPlatform = function() {
    return this.platform;
  };

  /**
   * 检查是否就绪
   */
  CTAAdapter.prototype.checkReady = function() {
    return this.isReady;
  };

  // 创建全局实例
  var ctaAdapter = new CTAAdapter();

  // 暴露简洁的全局 API
  window.PlayCraftCTA = {
    /**
     * 跳转到应用商店（推荐使用）
     * @param {Object} options - 可选配置
     */
    jump: function(options) {
      ctaAdapter.jump(options);
    },

    /**
     * 跳转到应用商店（别名，简化调用）
     */
    jump2AppStore: function(options) {
      ctaAdapter.jump(options);
    },

    /**
     * 注册就绪回调
     * @param {Function} callback - 回调函数
     */
    onReady: function(callback) {
      ctaAdapter.onReady(callback);
    },

    /**
     * 获取当前平台
     */
    getPlatform: function() {
      return ctaAdapter.getPlatform();
    },

    /**
     * 检查是否就绪
     */
    isReady: function() {
      return ctaAdapter.checkReady();
    }
  };

  // 向后兼容的别名
  window.jump2AppStore = window.PlayCraftCTA.jump2AppStore;

  console.log('[PlayCraft CTA] 适配器已加载，平台:', ctaAdapter.getPlatform());
})();
