(function (global) {
  global.ARQ = global.ARQ || {};
  function sheetHist(sheet) {
    sheet.historial = sheet.historial || { undo: [], redo: [] };
    return sheet.historial;
  }
  function maxUndo() {
    var p = ARQ.storage.get(ARQ.STORAGE_KEYS.UI_PREFS) || {};
    var n = parseInt(p.maxUndo, 10);
    return n >= 5 && n <= 200 ? n : 50;
  }

  ARQ.history = {
    pushUndo: function () {
      var project = ARQ.store.getProject();
      var sheet = ARQ.utils.activeSheet(project);
      if (!sheet) return;
      var h = sheetHist(sheet);
      var snap = ARQ.utils.deepClone(sheet);
      delete snap.historial;
      h.undo.push(JSON.stringify({ capas: snap.capas, timestamp: Date.now() }));
      while (h.undo.length > maxUndo()) {
        h.undo.shift();
      }
      h.redo = [];
      ARQ.bus.emit(ARQ.EVENTS.HISTORY_CHANGED);
    },
    pushDescription: function (label) {
      var project = ARQ.store.getProject();
      var sheet = ARQ.utils.activeSheet(project);
      if (!sheet) return;
      this._refreshTimeline(sheet, label || 'Cambio');
    },
    _refreshTimeline: function (sheet, label) {
      var ul = global.document.getElementById('history-timeline');
      if (!ul) return;
      var h = sheetHist(sheet);
      var li = global.document.createElement('li');
      li.textContent = new Date().toLocaleTimeString() + ' — ' + label;
      ul.insertBefore(li, ul.firstChild);
      while (ul.children.length > 80) {
        ul.removeChild(ul.lastChild);
      }
    },
    undo: function () {
      var project = ARQ.store.getProject();
      var sheet = ARQ.utils.activeSheet(project);
      if (!sheet) return;
      var h = sheetHist(sheet);
      if (!h.undo.length) return;
      var current = ARQ.utils.deepClone(sheet);
      delete current.historial;
      var redoSnap = JSON.stringify({ capas: current.capas });
      var prev = h.undo.pop();
      h.redo.push(redoSnap);
      var data = JSON.parse(prev);
      sheet.capas = data.capas;
      ARQ.store.setDirty(true);
      ARQ.canvasEngine.redraw();
      ARQ.bus.emit(ARQ.EVENTS.HISTORY_CHANGED);
      ARQ.layers && ARQ.layers.renderPanel && ARQ.layers.renderPanel();
    },
    redo: function () {
      var project = ARQ.store.getProject();
      var sheet = ARQ.utils.activeSheet(project);
      if (!sheet) return;
      var h = sheetHist(sheet);
      if (!h.redo.length) return;
      var current = ARQ.utils.deepClone(sheet);
      delete current.historial;
      h.undo.push(JSON.stringify({ capas: current.capas }));
      var next = h.redo.pop();
      var data = JSON.parse(next);
      sheet.capas = data.capas;
      ARQ.store.setDirty(true);
      ARQ.canvasEngine.redraw();
      ARQ.bus.emit(ARQ.EVENTS.HISTORY_CHANGED);
      ARQ.layers && ARQ.layers.renderPanel && ARQ.layers.renderPanel();
    },
  };
})(typeof window !== 'undefined' ? window : this);
