(function(){
  // AIPostSecure: 前端保存令牌的工具，使用 REST 路由 aipost/v1/settings/save-token
  // 依赖：在 PHP 中通过 wp_localize_script 注入 AIPostSecureConfig { restBase, nonce }
  if (window.AIPostSecure && typeof window.AIPostSecure.saveToken === 'function') {
    return; // 已存在则不重复定义
  }

  function ensureConfig(){
    if (!window.AIPostSecureConfig || !window.AIPostSecureConfig.restBase || !window.AIPostSecureConfig.nonce) {
      throw new Error('AIPostSecureConfig 未初始化');
    }
  }

  async function postJson(url, payload){
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': String(window.AIPostSecureConfig.nonce || '')
      },
      cache: 'no-store',
      body: JSON.stringify(payload || {})
    });
    let data = null;
    const text = await res.text();
    try { data = JSON.parse(text); } catch (e) {
      const snippet = (text || '').slice(0, 200);
      throw new Error('非JSON响应，请检查WAF/CDN：' + snippet);
    }
    if (!res.ok || (data && data.success === false)) {
      const msg = (data && data.message) || '保存失败';
      throw new Error(msg);
    }
    return data;
  }

  // 保存令牌：{k, v} 或 {k, parts: ['...','...']}
  async function saveToken(input){
    ensureConfig();
    if (!input || typeof input !== 'object') throw new Error('参数错误');
    const url = (window.AIPostSecureConfig.restBase || '').replace(/\/$/, '') + '/aipost/v1/settings/save-token';
    const payload = {};
    if (input.k) payload.k = String(input.k);
    if (input.v) payload.v = String(input.v);
    if (Array.isArray(input.parts)) payload.parts = input.parts.map(String);
    if (input.group) payload.group = String(input.group);
    return postJson(url, payload);
  }

  window.AIPostSecure = {
    saveToken: saveToken
  };
})();
