/**
 * 主站页面对接层：在 Cocos 启动后提供与 Unity WebGL 相同的 unityInstance.SendMessage API
 * 用法：构建产物 index.html 末尾引入本脚本，或在主站模板中引入
 */
(function (global) {
  function wrap(name, hookKey) {
    return function (json) {
      var hook = global[hookKey];
      if (typeof hook === 'function') hook(json);
      try {
        console.log('[' + name + ']', JSON.parse(json));
      } catch (e) {
        console.log('[' + name + ']', json);
      }
    };
  }

  function processData(json) { wrap('processData', '__tfrhOnProcessData')(json); }
  function processVehicleData(json) { wrap('processVehicleData', '__tfrhOnProcessVehicleData')(json); }
  function externalResult(json) { wrap('externalResult', '__tfrhOnExternalResult')(json); }
  function externalLevelInfo(json) { wrap('externalLevelInfo', '__tfrhOnExternalLevelInfo')(json); }
  function coinsData(json) { wrap('coinsData', '__tfrhOnCoinsData')(json); }

  /** Editor 注册真实回调；同时写入 hook 与 window.processData 等全局名 */
  global.tfrhBindUnityCallbacks = function (hooks) {
    if (!hooks || typeof hooks !== 'object') return;
    if (typeof hooks.processData === 'function') {
      global.__tfrhOnProcessData = hooks.processData;
      global.processData = wrap('processData', '__tfrhOnProcessData');
    }
    if (typeof hooks.processVehicleData === 'function') {
      global.__tfrhOnProcessVehicleData = hooks.processVehicleData;
      global.processVehicleData = wrap('processVehicleData', '__tfrhOnProcessVehicleData');
    }
    if (typeof hooks.externalResult === 'function') {
      global.__tfrhOnExternalResult = hooks.externalResult;
      global.externalResult = wrap('externalResult', '__tfrhOnExternalResult');
    }
    if (typeof hooks.externalLevelInfo === 'function') {
      global.__tfrhOnExternalLevelInfo = hooks.externalLevelInfo;
      global.externalLevelInfo = wrap('externalLevelInfo', '__tfrhOnExternalLevelInfo');
    }
    if (typeof hooks.coinsData === 'function') {
      global.__tfrhOnCoinsData = hooks.coinsData;
      global.coinsData = wrap('coinsData', '__tfrhOnCoinsData');
    }
  };

  global.processData = processData;
  global.processVehicleData = processVehicleData;
  global.externalResult = externalResult;
  global.externalLevelInfo = externalLevelInfo;
  global.coinsData = coinsData;

  // 动态 processPlayerA1 等
  ['A1', 'A2', 'A3', 'B1', 'B2', 'B3'].forEach(function (id) {
    global['processPlayer' + id] = function (json) { console.log('[processPlayer' + id + ']', JSON.parse(json)); };
    global['processVehicle' + id] = function (json) { console.log('[processVehicle' + id + ']', JSON.parse(json)); };
  });

  function waitInstance(maxMs) {
    maxMs = maxMs || 30000;
    return new Promise(function (resolve, reject) {
      var t0 = Date.now();
      (function tick() {
        if (global.cocosIns || global.unityInstance) return resolve(global.cocosIns || global.unityInstance);
        if (Date.now() - t0 > maxMs) return reject(new Error('Cocos instance timeout'));
        requestAnimationFrame(tick);
      })();
    });
  }

  global.tfrhReady = waitInstance;

  document.addEventListener('DOMContentLoaded', function () {
    waitInstance().then(function () {
      console.log('[tfrh] Cocos bridge ready, use unityInstance.SendMessage(...)');
    }).catch(function (e) { console.warn('[tfrh]', e.message); });
  });
})(typeof window !== 'undefined' ? window : globalThis);
