(function (global) {
  global.ARQ = global.ARQ || {};
  var project = null;
  var dirty = false;
  var activeLayerId = null;

  ARQ.store = {
    getProject: function () { return project; },
    setProject: function (p) {
      project = p;
      if (p && p.hoja_activa_id) {
        var sh = ARQ.utils.activeSheet(p);
        if (sh && sh.capas && sh.capas.length) {
          var sorted = ARQ.utils.sortLayers(sh.capas);
          activeLayerId = sorted[sorted.length - 1].id;
        }
      }
    },
    isDirty: function () { return dirty; },
    setDirty: function (v) {
      dirty = !!v;
      ARQ.bus.emit(ARQ.EVENTS.DIRTY, dirty);
    },
    getActiveLayerId: function () { return activeLayerId; },
    setActiveLayerId: function (id) { activeLayerId = id; },
    activeLayer: function () {
      var sh = ARQ.utils.activeSheet(project);
      if (!sh || !sh.capas) return null;
      for (var i = 0; i < sh.capas.length; i++) {
        if (sh.capas[i].id === activeLayerId) return sh.capas[i];
      }
      var sorted = ARQ.utils.sortLayers(sh.capas);
      return sorted.length ? sorted[sorted.length - 1] : null;
    },
  };
})(typeof window !== 'undefined' ? window : this);
