(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.utils = {
    uuid: function () {
      if (global.crypto && crypto.randomUUID) return crypto.randomUUID();
      return 'x_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 12);
    },
    debounce: function (fn, ms) {
      var t;
      return function () {
        var ctx = this, args = arguments;
        clearTimeout(t);
        t = setTimeout(function () { fn.apply(ctx, args); }, ms);
      };
    },
    deepClone: function (o) {
      return JSON.parse(JSON.stringify(o));
    },
    nowIso: function () {
      return new Date().toISOString();
    },
    pad2: function (n) {
      n = n | 0;
      return (n < 10 ? '0' : '') + n;
    },
    nowLocalLabel: function () {
      var d = new Date();
      var y = d.getFullYear();
      var m = ARQ.utils.pad2(d.getMonth() + 1);
      var day = ARQ.utils.pad2(d.getDate());
      var hh = ARQ.utils.pad2(d.getHours());
      var mm = ARQ.utils.pad2(d.getMinutes());
      return y + '-' + m + '-' + day + ' ' + hh + ':' + mm;
    },
    defaultProjectName: function () {
      return 'Proyecto ' + ARQ.utils.nowLocalLabel();
    },
    sheetById: function (project, id) {
      if (!project || !project.hojas) return null;
      for (var i = 0; i < project.hojas.length; i++) {
        if (project.hojas[i].id === id) return project.hojas[i];
      }
      return null;
    },
    activeSheet: function (project) {
      if (!project) return null;
      return ARQ.utils.sheetById(project, project.hoja_activa_id) || project.hojas[0] || null;
    },
    sortLayers: function (capas) {
      return (capas || []).slice().sort(function (a, b) {
        return (a.z_index || 0) - (b.z_index || 0);
      });
    },
  };
})(typeof window !== 'undefined' ? window : this);
