(function (wp) {
  if (!wp || !wp.plugins || !wp.editPost || !wp.element || !wp.components || !wp.data || !wp.apiFetch) {
    return;
  }

  var el = wp.element.createElement;
  var registerPlugin = wp.plugins.registerPlugin;
  var PluginSidebar = wp.editPost.PluginSidebar;
  var PluginSidebarMoreMenuItem = wp.editPost.PluginSidebarMoreMenuItem;
  var PanelBody = wp.components.PanelBody;
  var Button = wp.components.Button;
  var Notice = wp.components.Notice;
  var ProgressBar = wp.components.ProgressBar;
  var SelectControl = wp.components.SelectControl;
  var useState = wp.element.useState;
  var useRef = wp.element.useRef;

  function api(path, method, data) {
    return wp.apiFetch({
      path: path,
      method: method || 'GET',
      data: data || undefined,
    });
  }

  function normalizeKeyword(s) {
    return (s || '').toString().trim();
  }

  function ensureTagIdByName(name) {
    name = normalizeKeyword(name);
    if (!name) {
      return Promise.resolve(null);
    }

    // Search existing tags
    return api('/wp/v2/tags?search=' + encodeURIComponent(name) + '&per_page=100', 'GET')
      .then(function (list) {
        if (Array.isArray(list)) {
          for (var i = 0; i < list.length; i++) {
            if (list[i] && list[i].name && (list[i].name.toString() === name)) {
              return list[i].id;
            }
          }
          if (list[0] && list[0].id) {
            return list[0].id;
          }
        }
        return null;
      })
      .then(function (id) {
        if (id) {
          return id;
        }
        // Create tag
        return api('/wp/v2/tags', 'POST', { name: name })
          .then(function (created) {
            return created && created.id ? created.id : null;
          });
      })
      .catch(function () {
        return null;
      });
  }

  function ensureTagIds(keywords) {
    if (!Array.isArray(keywords) || !keywords.length) {
      return Promise.resolve([]);
    }
    var jobs = keywords.map(function (k) { return ensureTagIdByName(k); });
    return Promise.all(jobs).then(function (ids) {
      var out = [];
      for (var i = 0; i < ids.length; i++) {
        if (ids[i]) {
          out.push(ids[i]);
        }
      }
      // unique
      var uniq = [];
      for (var j = 0; j < out.length; j++) {
        if (uniq.indexOf(out[j]) === -1) {
          uniq.push(out[j]);
        }
      }
      return uniq;
    });
  }

  function App() {
    var _a = useState(false), running = _a[0], setRunning = _a[1];
    var _b = useState(''), statusText = _b[0], setStatusText = _b[1];
    var _c = useState(0), progress = _c[0], setProgress = _c[1];
    var _d = useState(''), jobId = _d[0], setJobId = _d[1];
    var _e = useState(null), error = _e[0], setError = _e[1];
    var _h = useState(null), notice = _h[0], setNotice = _h[1];

    var defaultModel = (window.AIPostEditorGenerate && window.AIPostEditorGenerate.defaultModel) ? (window.AIPostEditorGenerate.defaultModel || '') : '';
    var modelOptions = (window.AIPostEditorGenerate && Array.isArray(window.AIPostEditorGenerate.models)) ? window.AIPostEditorGenerate.models : [{ value: '', label: '账号默认' }];
    var _f = useState(defaultModel), model = _f[0], setModel = _f[1];
    var _g = useState('t2i'), imageMode = _g[0], setImageMode = _g[1];
    var t2iProviders = (window.AIPostEditorGenerate && Array.isArray(window.AIPostEditorGenerate.t2iProviders)) ? window.AIPostEditorGenerate.t2iProviders : [];
    var _t2i = useState(t2iProviders.length ? t2iProviders[0].value : ''), t2iProvider = _t2i[0], setT2iProvider = _t2i[1];

    var timerRef = useRef(null);

    function stopPolling() {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }

    function poll(id) {
      stopPolling();
      timerRef.current = setInterval(function () {
        api('/aipost/v1/editor-generate/status?job_id=' + encodeURIComponent(id), 'GET').then(function (res) {
          if (!res || !res.ok || !res.data) {
            return;
          }
          var d = res.data;
          setStatusText((d.message || '') + (d.step ? ('（' + d.step + '）') : ''));
          setProgress(parseInt(d.progress || 0, 10));

          if (d.status === 'failed') {
            stopPolling();
            setRunning(false);
            setError(d.error || 'unknown');
            return;
          }
          if (d.status === 'canceled') {
            stopPolling();
            setRunning(false);
            setStatusText('已取消');
            setProgress(100);
            return;
          }
          if (d.status === 'success') {
            stopPolling();
            setRunning(false);
            setError(null);
            setStatusText('完成（标签/SEO字段若未即时刷新可保存或刷新页面查看）');
            setProgress(100);

            try {
              if (d.result && d.result.content) {
                wp.data.dispatch('core/editor').editPost({ content: d.result.content });
              }
              if (d.result && d.result.description) {
                wp.data.dispatch('core/editor').editPost({ excerpt: d.result.description });
              }
            } catch (e) {}

            try {
              if (d.result && Array.isArray(d.result.keywords) && d.result.keywords.length) {
                ensureTagIds(d.result.keywords).then(function (ids) {
                  if (ids && ids.length) {
                    try {
                      wp.data.dispatch('core/editor').editPost({ tags: ids });
                    } catch (e) {}
                  }
                });
              }
            } catch (e) {}
          }
        }).catch(function () {
          // ignore
        });
      }, 1500);

      // tick immediately
      api('/aipost/v1/editor-generate/status?job_id=' + encodeURIComponent(id), 'GET').then(function () {}).catch(function () {});
    }

    function insertImage() {
      if (!wp.data.select('core/editor').getCurrentPostId()) {
        setNotice({ status: 'warning', message: '请先保存草稿后再插入图片' });
        return;
      }
      var title = wp.data.select('core/editor').getEditedPostAttribute('title');
      if (!title) {
        setNotice({ status: 'warning', message: '请先填写标题' });
        return;
      }

      setRunning(true);

      if (imageMode === 't2i') {
        if (!t2iProviders.length) {
          setNotice({ status: 'error', message: '请先配置文生图模型的秘钥：当前支持豆包、智谱、阿里百炼，至少配置一个' });
          setRunning(false);
          return;
        }
        setNotice({ status: 'info', message: '文生图生成中（可能需要30~60秒）...' });
        api('/aipost/v1/editor-text-to-image', 'POST', { post_id: wp.data.select('core/editor').getCurrentPostId(), title: title, provider: t2iProvider }).then(function (res) {
          if (!res || !res.ok || !res.data || !res.data.html) {
            setNotice({ status: 'error', message: '文生图失败' + (res && res.error ? '：' + res.error : '') });
            return;
          }
          try {
            var cur = wp.data.select('core/editor').getEditedPostContent() || '';
            var merged = (res.data.html || '') + (cur ? ('\n' + cur) : '');
            wp.data.dispatch('core/editor').editPost({ content: merged });
            var tip = '文生图已插入到正文开头';
            if (res.data.provider) tip += '（' + res.data.provider + (res.data.model ? ' / ' + res.data.model : '') + '）';
            setNotice({ status: 'success', message: tip });
          } catch (e) {
            setNotice({ status: 'error', message: '插入失败：' + (e && e.message ? e.message : 'unknown') });
          }
        }).catch(function (e) {
          setNotice({ status: 'error', message: (e && e.message) ? e.message : '请求失败' });
        }).finally(function () {
          setRunning(false);
        });
      } else {
        setNotice({ status: 'info', message: '生成标题图...' });
        api('/aipost/v1/editor-title-image', 'POST', { post_id: wp.data.select('core/editor').getCurrentPostId(), title: title }).then(function (res) {
          if (!res || !res.ok || !res.data || !res.data.html) {
            setNotice({ status: 'error', message: '生成标题图失败' });
            return;
          }
          try {
            var cur = wp.data.select('core/editor').getEditedPostContent() || '';
            var merged = (res.data.html || '') + (cur ? ('\n' + cur) : '');
            wp.data.dispatch('core/editor').editPost({ content: merged });
            setNotice({ status: 'success', message: '标题图已插入到正文开头' });
          } catch (e) {
            setNotice({ status: 'error', message: '插入失败：' + (e && e.message ? e.message : 'unknown') });
          }
        }).catch(function (e) {
          setNotice({ status: 'error', message: (e && e.message) ? e.message : '请求失败' });
        }).finally(function () {
          setRunning(false);
        });
      }
    }

    function onStart() {
      if (!wp.data.select('core/editor').getCurrentPostId()) {
        setNotice({ status: 'warning', message: '请先保存草稿后再生成' });
        return;
      }
      var title = wp.data.select('core/editor').getEditedPostAttribute('title');
      if (!title) {
        setError('请先填写标题');
        return;
      }
      if (!window.confirm('将覆盖当前正文/摘要/标签/SEO描述，是否继续？')) {
        return;
      }

      setRunning(true);
      setStatusText('生成中...');
      setProgress(15);

      api('/aipost/v1/editor-generate', 'POST', { post_id: wp.data.select('core/editor').getCurrentPostId(), title: title, force: true, model: (model || '').toString(), sync: true }).then(function (res) {
        if (!res || !res.ok || !res.data) {
          setRunning(false);
          setError('生成失败');
          return;
        }

        // 同步优先：直接返回最终 job
        if (res.data.job && res.data.job.status) {
          var d = res.data.job;
          setStatusText((d.message || '') + (d.step ? ('（' + d.step + '）') : ''));
          setProgress(parseInt(d.progress || 0, 10));

          if (d.status === 'failed') {
            setRunning(false);
            setError(d.error || 'unknown');
            return;
          }

          if (d.status === 'success') {
            setRunning(false);
            setError(null);
            setStatusText('完成（标签/SEO字段若未即时刷新可保存或刷新页面查看）');
            setProgress(100);

            try {
              if (d.result && d.result.content) {
                wp.data.dispatch('core/editor').editPost({ content: d.result.content });
              }
              if (d.result && d.result.description) {
                wp.data.dispatch('core/editor').editPost({ excerpt: d.result.description });
              }
            } catch (e) {}

            try {
              if (d.result && Array.isArray(d.result.keywords) && d.result.keywords.length) {
                ensureTagIds(d.result.keywords).then(function (ids) {
                  if (ids && ids.length) {
                    try {
                      wp.data.dispatch('core/editor').editPost({ tags: ids });
                    } catch (e) {}
                  }
                });
              }
            } catch (e) {}

            return;
          }
        }

        // 兼容：仍返回 job_id 时回退到轮询
        if (res.data.job_id) {
          setJobId(res.data.job_id);
          setStatusText('任务已创建，开始执行...');
          poll(res.data.job_id);
          return;
        }

        setRunning(false);
        setError('生成失败');
      }).catch(function (e) {
        setRunning(false);
        setError((e && e.message) ? e.message : '请求失败');
      });
    }

    function onCancel() {
      if (!jobId) {
        return;
      }
      api('/aipost/v1/editor-generate/cancel', 'POST', { job_id: jobId }).finally(function () {
        stopPolling();
        setRunning(false);
        setStatusText('已取消');
        setProgress(100);
      });
    }

    return el(
      'div',
      { style: { padding: '12px' } },
      notice ? el(Notice, { status: notice.status, isDismissible: true, onRemove: function () { setNotice(null); } }, notice.message) : null,
      error ? el(Notice, { status: 'error', isDismissible: true, onRemove: function(){ setError(null); } }, error) : null,
      el(PanelBody, { title: 'AI 生成', initialOpen: true },
        el('div', { style: { marginBottom: '8px' } }, el(SelectControl, { label: '模型', value: model, options: modelOptions, onChange: function(v){ setModel(v); }, disabled: running })),
        el('div', { style: { marginBottom: '8px' } }, el(SelectControl, { label: '插入图片', value: imageMode, options: [{ value: 't2i', label: '文生图' }, { value: 'title', label: '标题图片' }], onChange: function(v){ setImageMode(v); }, disabled: running })),
        (imageMode === 't2i' && t2iProviders.length > 0) ? el('div', { style: { marginBottom: '8px' } }, el(SelectControl, { label: '文生图模型', value: t2iProvider, options: t2iProviders.map(function(p){ return { value: p.value, label: p.label }; }), onChange: function(v){ setT2iProvider(v); }, disabled: running })) : null,
        el('p', null, el(Button, { variant: 'secondary', onClick: insertImage, disabled: running }, running ? '处理中...' : '插入图片')),
        el('p', null, el(Button, { variant: 'primary', onClick: onStart, disabled: running }, running ? '生成中...' : '生成正文 + 关键词 + 描述')),
        el('p', null, el(Button, { variant: 'secondary', onClick: onCancel, disabled: !running }, '取消')),
        el('div', { style: { marginTop: '10px' } }, el(ProgressBar, { value: progress })),
        el('p', { style: { marginTop: '8px', color: '#444' } }, statusText)
      )
    );
  }

  registerPlugin('aipost-editor-generate', {
    render: function () {
      return el(
        wp.element.Fragment,
        null,
        el(PluginSidebarMoreMenuItem, { target: 'aipost-editor-generate-sidebar' }, 'AI 生成内容'),
        el(PluginSidebar, { name: 'aipost-editor-generate-sidebar', title: 'AI 生成内容' }, el(App))
      );
    },
    icon: null,
  });
})(window.wp);
