/**
 * 主题门户极验 4.0 — float 嵌入（与站内 geetest_addon 一致，appendTo 挂载）
 */
(function (global) {
  const CAPTCHA_ID = global.PORTAL_GEETEST_ID || '';
  /** @type {Record<string, { obj: object, elId: string, payload: object|null }>} */
  const instances = {};

  function waitGt4() {
    return new Promise((resolve, reject) => {
      if (typeof global.initGeetest4 === 'function') {
        resolve();
        return;
      }
      let n = 0;
      const t = setInterval(() => {
        if (typeof global.initGeetest4 === 'function') {
          clearInterval(t);
          resolve();
          return;
        }
        if (++n > 100) {
          clearInterval(t);
          reject(new Error('极验脚本加载失败，请检查网络'));
        }
      }, 100);
    });
  }

  function readPayload(obj) {
    const r = obj.getValidate();
    if (!r || !r.lot_number) {
      return null;
    }
    return {
      lot_number: r.lot_number,
      pass_token: r.pass_token,
      gen_time: r.gen_time,
      captcha_output: r.captcha_output,
    };
  }

  function mount(scene, elId) {
    if (!CAPTCHA_ID) {
      return Promise.reject(new Error('极验 CaptchaId 未配置'));
    }
    const el = document.getElementById(elId);
    if (!el) {
      return Promise.reject(new Error('极验挂载点不存在'));
    }
    if (instances[scene] && instances[scene].elId === elId && instances[scene].obj) {
      return Promise.resolve(instances[scene].obj);
    }
    return waitGt4().then(() => new Promise((resolve, reject) => {
      try {
        if (instances[scene] && instances[scene].obj && typeof instances[scene].obj.destroy === 'function') {
          try {
            instances[scene].obj.destroy();
          } catch (e) {}
        }
      } catch (e) {}
      el.innerHTML = '';
      global.initGeetest4({
        captchaId: CAPTCHA_ID,
        product: 'float',
        language: 'zho',
        nativeButton: { width: '100%', height: '44px' },
      }, (obj) => {
        try {
          obj.appendTo('#' + elId);
          obj.onSuccess(() => {
            const p = readPayload(obj);
            if (p) {
              instances[scene].payload = p;
            }
          });
          instances[scene] = { obj, elId, payload: null };
          resolve(obj);
        } catch (e) {
          reject(e);
        }
      });
    }));
  }

  function getPayload(scene) {
    const row = instances[scene];
    if (!row || !row.obj) {
      return null;
    }
    const p = readPayload(row.obj);
    if (p) {
      row.payload = p;
    }
    return row.payload || p;
  }

  function reset(scene) {
    const row = instances[scene];
    if (!row) {
      return;
    }
    row.payload = null;
    try {
      if (typeof row.obj.reset === 'function') {
        row.obj.reset();
      }
    } catch (e) {}
  }

  global.PortalGeetest = {
    mount,
    getPayload,
    reset,
  };
})(window);
