(function($){
  function escapeHtml(s){
    s = (s === null || s === undefined) ? '' : (s + '');
    return s
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function setStatus($box, text){
    $box.find('.aipost-eg-status').text(text || '');
  }

  function setProgress($box, pct){
    pct = parseInt(pct || 0, 10);
    if (pct < 0) pct = 0;
    if (pct > 100) pct = 100;
    $box.find('.aipost-eg-progress-bar').css('width', pct + '%');
  }

  function getTitle(){
    var $t = $('#title');
    return $t.length ? ($t.val() || '').trim() : '';
  }

  function getContent(){
    try {
      if (window.tinymce && window.tinymce.activeEditor && !window.tinymce.activeEditor.isHidden()) {
        return window.tinymce.activeEditor.getContent() || '';
      }
    } catch(e) {}
    var $c = $('#content');
    return $c.length ? ($c.val() || '') : '';
  }

  function setContent(content){
    try {
      if (window.tinymce && window.tinymce.activeEditor && !window.tinymce.activeEditor.isHidden()) {
        window.tinymce.activeEditor.setContent(content);
        return;
      }
    } catch(e) {}

    var $c = $('#content');
    if ($c.length) {
      $c.val(content);
    }
  }

  function setExcerpt(excerpt){
    var $e = $('#excerpt');
    if ($e.length) {
      $e.val(excerpt);
    }
  }

  function fillTags(keywords){
    if (!keywords || !keywords.length) return;
    var list = [];
    for (var i=0;i<keywords.length;i++) {
      var t = (keywords[i] || '').toString().trim();
      if (t) list.push(t);
    }
    if (!list.length) return;

    var box = window.wp && window.wp.tagsBox ? window.wp.tagsBox : null;

    // Try detect current taxonomy from tags metabox id: #tagsdiv-{taxonomy}
    var taxonomy = 'post_tag';
    var $tagsDiv = $('.tagsdiv').first();
    if ($('#tagsdiv-post_tag').length) {
      taxonomy = 'post_tag';
      $tagsDiv = $('#tagsdiv-post_tag');
    } else if ($tagsDiv.length && $tagsDiv.attr('id')) {
      var m = ($tagsDiv.attr('id') || '').match(/^tagsdiv-(.+)$/);
      if (m && m[1]) {
        taxonomy = m[1];
      }
    }

    var $input = $('#new-tag-' + taxonomy);
    var $btn = $('#tagadd-' + taxonomy + ', #tagadd, .tagadd');
    var $ta = $('#tax-input-' + taxonomy);

    function refreshUI(){
      try {
        if (box && typeof box.parseTags === 'function') {
          box.parseTags(taxonomy);
        }
        if (box && typeof box.quickClicks === 'function') {
          box.quickClicks(taxonomy);
        }
        if (box && typeof box.flushTags === 'function') {
          box.flushTags(taxonomy, false);
        }
      } catch(e) {}
    }

    function mergeToTextarea(){
      if (!$ta.length) return false;
      var cur = ($ta.val() || '').toString().trim();
      var merged = cur ? (cur + ',' + list.join(',')) : list.join(',');
      $ta.val(merged).trigger('input').trigger('change');
      refreshUI();
      return true;
    }

    // If tagsBox not ready yet, write textarea first and retry UI refresh later
    if (!box || (typeof box.quickClicks !== 'function' && typeof box.addTag !== 'function')) {
      if (mergeToTextarea()) {
        var tries = 0;
        var t = setInterval(function(){
          tries++;
          box = window.wp && window.wp.tagsBox ? window.wp.tagsBox : null;
          if (box) {
            refreshUI();
            clearInterval(t);
          }
          if (tries >= 10) {
            clearInterval(t);
          }
        }, 300);
      }
      return;
    }

    // 最稳路径：先写 textarea，再触发 WP 渲染（不依赖 addTag 的 ajax 成功与否）
    if (mergeToTextarea()) {
      // 同步把输入框清空，避免用户误操作
      try { $input.val(''); } catch(e) {}
      return;
    }

    // 次优路径：使用WordPress内置tagsBox.addTag（会走 ajax + UI）
    if (typeof box.addTag === 'function' && $input.length) {
      var idx1 = 0;
      var addNext1 = function(){
        if (idx1 >= list.length) {
          refreshUI();
          return;
        }
        $input.val(list[idx1]);
        // addTag会读取当前输入框并执行ajax+UI刷新
        box.addTag({ target: $input.get(0) });
        idx1++;
        setTimeout(addNext1, 250);
      };
      addNext1();
      return;
    }

    // 最后兜底：模拟点击添加按钮
    if ($input.length && $btn.length) {
      var idx2 = 0;
      var addNext2 = function(){
        if (idx2 >= list.length) return;
        $input.val(list[idx2]);
        $btn.eq(0).trigger('click');
        idx2++;
        setTimeout(addNext2, 250);
      };
      addNext2();
    }
  }

  function apiFetch(path, method, data){
    var url = (AIPostEditorGenerateClassic.restUrl || '/wp-json/') + path.replace(/^\//,'');
    return $.ajax({
      url: url,
      method: method || 'GET',
      data: data || undefined,
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      beforeSend: function(xhr){
        if (AIPostEditorGenerateClassic.restNonce) {
          xhr.setRequestHeader('X-WP-Nonce', AIPostEditorGenerateClassic.restNonce);
        }
      },
      processData: method === 'GET'
    });
  }

  function startPolling($box, jobId){
    var timer = null;
    var stopped = false;

    function stop(){
      stopped = true;
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    }

    function tick(){
      if (stopped) return;
      apiFetch('/aipost/v1/editor-generate/status', 'GET', {job_id: jobId})
        .done(function(res){
          if (!res || !res.ok || !res.data) {
            return;
          }
          var d = res.data;
          setStatus($box, (d.message || '') + (d.step ? ('（' + d.step + '）') : ''));
          setProgress($box, d.progress || 0);

          if (d.status === 'failed') {
            stop();
            setStatus($box, '失败：' + (d.error || 'unknown'));
            return;
          }
          if (d.status === 'canceled') {
            stop();
            setStatus($box, '已取消');
            return;
          }
          if (d.status === 'success') {
            stop();
            if (d.result && d.result.content) {
              setContent(d.result.content);
            }
            if (d.result && d.result.description) {
              setExcerpt(d.result.description);
            }
            if (d.result && d.result.keywords) {
              fillTags(d.result.keywords);
            }
            setStatus($box, '完成（已写入，标签/SEO字段若未即时刷新可保存或刷新页面查看）');
            setProgress($box, 100);
          }
        })
        .fail(function(){
          // ignore
        });
    }

    timer = setInterval(tick, 1500);
    tick();

    $box.find('.aipost-eg-cancel').prop('disabled', false).off('click').on('click', function(){
      apiFetch('/aipost/v1/editor-generate/cancel', 'POST', JSON.stringify({job_id: jobId}))
        .always(function(){
          stop();
          setStatus($box, '已取消');
          setProgress($box, 100);
        });
    });
  }

  function render($mount){
    var html = '';
    html += '<div class="aipost-eg">';
    html += '  <p style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">';
    html += '    <label style="display:flex;align-items:center;gap:6px;">模型';
    html += '      <select class="aipost-eg-model" style="min-width:220px;">';
    if (window.AIPostEditorGenerateClassic && Array.isArray(window.AIPostEditorGenerateClassic.models)) {
      for (var i = 0; i < window.AIPostEditorGenerateClassic.models.length; i++) {
        var opt = window.AIPostEditorGenerateClassic.models[i];
        if (!opt) continue;
        var v = (opt.value || '').toString();
        var label = (opt.label || v || '').toString();
        html += '        <option value="' + escapeHtml(v) + '">' + escapeHtml(label) + '</option>';
      }
    } else {
      html += '        <option value="">账号默认</option>';
    }
    html += '      </select>';
    html += '    </label>';
    html += '    <button type="button" class="button aipost-eg-title-image">插入标题图</button> ';
    html += '    <button type="button" class="button button-primary aipost-eg-start">AI 生成正文 + 关键词 + 描述</button> ';
    html += '  <button type="button" class="button aipost-eg-cancel" disabled>取消</button></p>';
    html += '  <div class="aipost-eg-progress" style="background:#eee;height:8px;border-radius:6px;overflow:hidden;max-width:520px;">';
    html += '    <div class="aipost-eg-progress-bar" style="height:8px;width:0;background:#2271b1;"></div>';
    html += '  </div>';
    html += '  <p class="aipost-eg-status" style="margin-top:8px;color:#444;"></p>';
    html += '</div>';
    $mount.html(html);

    var defaultModel = (window.AIPostEditorGenerateClassic && window.AIPostEditorGenerateClassic.defaultModel) ? (window.AIPostEditorGenerateClassic.defaultModel || '').toString() : '';
    if (defaultModel) {
      $mount.find('.aipost-eg-model').val(defaultModel);
    }

    var postId = parseInt($mount.data('post-id') || 0, 10);

    $mount.find('.aipost-eg-title-image').on('click', function(){
      if (!postId) {
        alert('请先保存草稿后再插入标题图');
        return;
      }
      if (!getTitle()) {
        alert('请先填写标题');
        return;
      }

      var $btn = $(this);
      $btn.prop('disabled', true);
      setStatus($mount, '生成标题图...');
      setProgress($mount, 5);

      apiFetch('/aipost/v1/editor-title-image', 'POST', JSON.stringify({post_id: postId, title: getTitle()}))
        .done(function(res){
          if (!res || !res.ok || !res.data || !res.data.html) {
            setStatus($mount, '生成标题图失败');
            setProgress($mount, 0);
            return;
          }
          var cur = getContent();
          var imgHtml = (res.data.html || '').toString();
          var merged = imgHtml + (cur ? ('\n' + cur) : '');
          setContent(merged);
          setStatus($mount, '标题图已插入到正文开头');
          setProgress($mount, 100);
        })
        .fail(function(xhr){
          var msg = (xhr && xhr.responseJSON && (xhr.responseJSON.error || xhr.responseJSON.message)) ? (xhr.responseJSON.error || xhr.responseJSON.message) : '请求失败';
          setStatus($mount, msg);
          setProgress($mount, 0);
        })
        .always(function(){
          $btn.prop('disabled', false);
        });
    });

    $mount.find('.aipost-eg-start').on('click', function(){
      if (!postId) {
        alert('请先保存草稿后再生成');
        return;
      }
      if (!getTitle()) {
        alert('请先填写标题');
        return;
      }
      if (!window.confirm(AIPostEditorGenerateClassic.confirmOverwrite || '确认覆盖？')) {
        return;
      }

      var $btn = $(this);
      $btn.prop('disabled', true);
      $mount.find('.aipost-eg-title-image').prop('disabled', true);
      setStatus($mount, '生成中...');
      setProgress($mount, 15);

      var model = ($mount.find('.aipost-eg-model').val() || '').toString();
      apiFetch('/aipost/v1/editor-generate', 'POST', JSON.stringify({post_id: postId, title: getTitle(), force: true, model: model, sync: true}))
        .done(function(res){
          if (!res || !res.ok || !res.data) {
            setStatus($mount, '生成失败');
            setProgress($mount, 0);
            return;
          }

          // 同步优先：直接返回最终 job
          if (res.data.job && res.data.job.status) {
            var d = res.data.job;
            if (d.status === 'success') {
              if (d.result && d.result.content) {
                setContent(d.result.content);
              }
              if (d.result && d.result.description) {
                setExcerpt(d.result.description);
              }
              if (d.result && d.result.keywords) {
                fillTags(d.result.keywords);
              }
              setStatus($mount, '完成（已写入，标签/SEO字段若未即时刷新可保存或刷新页面查看）');
              setProgress($mount, 100);
              return;
            }
            if (d.status === 'failed') {
              setStatus($mount, '失败：' + (d.error || 'unknown'));
              setProgress($mount, 0);
              return;
            }
          }

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

          setStatus($mount, '生成失败');
          setProgress($mount, 0);
        })
        .fail(function(xhr){
          var msg = (xhr && xhr.responseJSON && (xhr.responseJSON.error || xhr.responseJSON.message)) ? (xhr.responseJSON.error || xhr.responseJSON.message) : '请求失败';
          setStatus($mount, msg);
          setProgress($mount, 0);
        })
        .always(function(){
          $btn.prop('disabled', false);
          $mount.find('.aipost-eg-title-image').prop('disabled', false);
        });
    });
  }

  $(function(){
    var $mount = $('#aipost-editor-generate-classic');
    if ($mount.length) {
      render($mount);
    }
  });
})(jQuery);
