/* Fissue 前端脚本。
 *
 * 两件事:
 * 1. **消费 SSE 进度流**:长任务(抓取/评测/修复)有实时反馈,而不是让人干等;
 * 2. **危险动作二次确认**:打标签、吊销 Key 这类动作点了就生效在外部系统上,
 *    误点的代价很高,所以要弹一次确认。
 *
 * 设计口径:
 * - **SSE 断了要重连**:EventSource 自带重连,但服务端若关闭了要能恢复;
 * - **进度显示要有终止态**:否则前端会一直转圈;
 * - **确认弹窗说清后果**:「不会自动合并」这种关键信息必须写在弹窗里。
 */
(function () {
  'use strict';

  /* -- SSE 进度 ------------------------------------------------------- */

  function progressEl() {
    var el = document.getElementById('fissue-progress');
    if (!el) {
      el = document.createElement('div');
      el.id = 'fissue-progress';
      el.style.cssText =
        'position:fixed;right:16px;bottom:16px;max-width:360px;' +
        'border:1px solid var(--line,#d0d7de);border-radius:8px;padding:12px;' +
        'background:var(--bg,#fff);box-shadow:0 6px 20px rgba(0,0,0,.12);' +
        'font-size:13px;z-index:9999;display:none';
      document.body.appendChild(el);
    }
    return el;
  }

  function showProgress(event) {
    var el = progressEl();
    var phase = event.phase || '';
    var msg = event.message || '';
    var counter = '';
    if (event.total) {
      counter = ' (' + (event.done || 0) + '/' + event.total + ')';
    }
    el.innerHTML =
      '<div style="font-weight:600">' + escapeHtml(phase) + counter + '</div>' +
      '<div>' + escapeHtml(msg) + '</div>';
    el.style.display = 'block';
  }

  function hideProgress() {
    var el = document.getElementById('fissue-progress');
    if (el) {
      el.style.display = 'none';
    }
  }

  function escapeHtml(text) {
    return String(text == null ? '' : text)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  function connectProgress() {
    if (typeof EventSource === 'undefined') {
      return;
    }
    var source;
    try {
      source = new EventSource('/api/v1/progress');
    } catch (err) {
      return;
    }
    source.onmessage = function (message) {
      var event;
      try {
        event = JSON.parse(message.data);
      } catch (err) {
        return;
      }
      if (event.finished) {
        if (!event.ok) {
          showProgress({ phase: event.phase, message: '失败:' + (event.message || '') });
        } else {
          hideProgress();
        }
        return;
      }
      showProgress(event);
    };
    source.onerror = function () {
      // EventSource 会自己重连;这里只把界面收起来,别一直转圈。
      hideProgress();
    };
    window.addEventListener('beforeunload', function () {
      source.close();
    });
  }

  /* -- 危险动作的二次确认 ---------------------------------------------- */

  var CONFIRMATIONS = {
    'approve-merge': {
      title: '确认可以合并?',
      // 批准理由在提交时才拿到(表单里的 note 字段),所以这里只放模板,
      // 实际文案在 bindConfirmations 里按 note 拼出来。
      body:
        '会在平台上打 merge-approved 标签。' +
        '<b>不会自动合并</b>,仍需人工在平台点确认。',
    },
    'api-keys': {
      title: '确认吊销这把 Key?',
      body: '吊销后用它调 API 的请求会立刻失败(行保留用于审计)。',
    },
    'webhooks': {
      title: '确认执行?',
      body: '这会改动远端机器上的部署状态。',
    },
  };

  /**
   * 给表单加确认。
   * 表单上写 `data-confirm="approve-merge"`,提交前弹一次。
   */
  function bindConfirmations() {
    var forms = document.querySelectorAll('form[data-confirm]');
    Array.prototype.forEach.call(forms, function (form) {
      form.addEventListener('submit', function (event) {
        var key = form.getAttribute('data-confirm');
        var spec = CONFIRMATIONS[key];
        if (!spec) {
          return;
        }
        var noteField = form.querySelector('[name="note"]');
        var note = noteField ? noteField.value : '';
        var body = spec.body;
        if (key === 'approve-merge' && note) {
          body =
            '会在平台上打 merge-approved 标签并留一条评论:' +
            escapeHtml(note) +
            '。<b>不会自动合并</b>,仍需人工在平台点确认。';
        }
        if (!window.confirm(spec.title + '\n\n' + body)) {
          event.preventDefault();
        }
      });
    });
  }

  /* -- 启动 ------------------------------------------------------------ */

  document.addEventListener('DOMContentLoaded', function () {
    connectProgress();
    bindConfirmations();
  });
})();