(function (global) {
  global.ARQ = global.ARQ || {};
  var enabled = false;

  ARQ.aiGate = {
    isEnabled: function () {
      return !!enabled;
    },

    refresh: function () {
      var self = this;
      return ARQ.projects.openaiKeyStatus().then(function (r) {
        enabled = !!(r && r.success && r.hasKey);
        ARQ.bus.emit(ARQ.EVENTS.AI_GATE_CHANGED, { enabled: enabled });
        return enabled;
      }).catch(function () {
        enabled = false;
        ARQ.bus.emit(ARQ.EVENTS.AI_GATE_CHANGED, { enabled: false });
        return false;
      });
    },

    init: function () {
      return this.refresh();
    },
  };
})(typeof window !== 'undefined' ? window : this);
