(function (global) {
  global.ARQ = global.ARQ || {};
  var $strip = null;

  function normName(s) {
    return String(s || '').trim();
  }

  function uniqueSiblingName(desired, allNames) {
    desired = normName(desired) || 'Hoja';
    var set = {};
    (allNames || []).forEach(function (n) {
      n = normName(n);
      if (!n) return;
      set[n.toLowerCase()] = true;
    });
    if (!set[desired.toLowerCase()]) return desired;

    var base = desired;
    var maxN = 0;
    (allNames || []).forEach(function (n) {
      n = normName(n);
      if (!n) return;
      var m = n.match(/^(.+?)\s*\((\d+)\)$/);
      if (!m) return;
      var b = normName(m[1]);
      var k = parseInt(m[2], 10);
      if (b.toLowerCase() === base.toLowerCase() && k > maxN) maxN = k;
    });
    return base + ' (' + (maxN + 1) + ')';
  }

  ARQ.sheets = {
    init: function () {
      $strip = $('#sheets-strip');
      $strip.attr('role', 'list');
      var self = this;
      var dragOverEl = null;
      $('#btn-add-sheet').on('click', function () { self.addSheet(); });
      $strip.on('click', '.arq-sheet-tab-wrap', function (e) {
        if ($(e.target).closest('.js-sheet-name, .js-sheet-del, .js-sheet-drag').length) return;
        var id = $(this).data('sheet-id');
        var p = ARQ.store.getProject();
        if (!p) return;
        if (String(id) === String(p.hoja_activa_id)) return;
        self.activate(id);
      });
      $strip.on('mousedown', '.js-sheet-name', function (e) {
        e.stopPropagation();
      });
      $strip.on('click', '.js-sheet-name', function (e) {
        e.stopPropagation();
        var id = $(this).closest('.arq-sheet-tab-wrap').data('sheet-id');
        var p = ARQ.store.getProject();
        if (!p) return;
        if (String(id) !== String(p.hoja_activa_id)) {
          self.activate(id);
          var sid = String(id);
          setTimeout(function () {
            $strip.find('.arq-sheet-tab-wrap').each(function () {
              if (String($(this).data('sheet-id')) === sid) {
                $(this).find('.js-sheet-name').trigger('focus');
              }
            });
          }, 0);
        }
      });
      $strip.on('contextmenu', '.arq-sheet-tab', function (e) {
        e.preventDefault();
        var id = $(this).closest('.arq-sheet-tab-wrap').data('sheet-id');
        ARQ.dialog.confirm('¿Duplicar esta hoja?').then(function (ok) {
          if (ok) self.duplicateSheet(id);
        });
      });

      $strip.on('click', '.js-sheet-del', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var id = $(this).closest('.arq-sheet-tab-wrap').data('sheet-id');
        var p = ARQ.store.getProject();
        if (!p || !p.hojas) return;
        if (p.hojas.length <= 1) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Debe existir al menos una hoja');
          return;
        }
        var sh = ARQ.utils.sheetById(p, id);
        if (!sh) return;
        ARQ.dialog.confirm('¿Eliminar la hoja "' + (sh.nombre || 'Hoja') + '"?').then(function (ok) {
          if (ok) self.removeSheetById(id);
        });
      });

      $strip.on('keydown', '.js-sheet-name', function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          this.blur();
        } else if (e.key === 'Escape') {
          e.preventDefault();
          $(this).val($(this).data('original') || '');
          this.blur();
        }
      });

      $strip.on('focus', '.js-sheet-name', function () {
        $(this).data('original', $(this).val() || '');
        try { this.select(); } catch (e) {}
      });

      $strip.on('blur', '.js-sheet-name', function () {
        var id = $(this).closest('.arq-sheet-tab-wrap').data('sheet-id');
        self.renameSheetById(id, $(this).val());
      });

      $('#editor-sheet-name').on('keydown', function (e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          this.blur();
        } else if (e.key === 'Escape') {
          e.preventDefault();
          var p = ARQ.store.getProject();
          var sh = ARQ.utils.activeSheet(p);
          $(this).val((sh && sh.nombre) || '');
          this.blur();
        }
      });

      $('#editor-sheet-name').on('focus', function () {
        try { this.select(); } catch (e) {}
      });

      $('#editor-sheet-name').on('blur', function () {
        var p = ARQ.store.getProject();
        if (!p) return;
        self.renameSheetById(p.hoja_activa_id, $(this).val());
      });

      $strip.on('click', '.js-sheet-drag', function (e) {
        e.stopPropagation();
      });
      $strip.on('dragstart', '.js-sheet-drag', function (e) {
        var ev = e.originalEvent;
        var id = $(this).closest('.arq-sheet-tab-wrap').data('sheet-id');
        if (ev.dataTransfer) {
          ev.dataTransfer.setData('text/plain', String(id));
          ev.dataTransfer.effectAllowed = 'move';
        }
        $(this).closest('.arq-sheet-tab-wrap').addClass('arq-sheet-tab-wrap--dragging');
      });
      $strip.on('dragend', '.js-sheet-drag', function () {
        $(this).closest('.arq-sheet-tab-wrap').removeClass('arq-sheet-tab-wrap--dragging');
        $strip.find('.arq-sheet-tab-wrap').removeClass('arq-sheet-tab-wrap--drag-over');
        dragOverEl = null;
      });
      $strip.on('dragover', '.arq-sheet-tab-wrap', function (e) {
        e.preventDefault();
        var ev = e.originalEvent;
        if (ev.dataTransfer) ev.dataTransfer.dropEffect = 'move';
        var el = this;
        if (dragOverEl && dragOverEl !== el) $(dragOverEl).removeClass('arq-sheet-tab-wrap--drag-over');
        dragOverEl = el;
        $(el).addClass('arq-sheet-tab-wrap--drag-over');
      });
      $strip.on('drop', '.arq-sheet-tab-wrap', function (e) {
        e.preventDefault();
        $strip.find('.arq-sheet-tab-wrap').removeClass('arq-sheet-tab-wrap--drag-over');
        dragOverEl = null;
        var targetId = $(this).data('sheet-id');
        var sourceId = e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.getData('text/plain');
        if (sourceId && targetId && String(sourceId) !== String(targetId)) {
          self.reorderSheets(sourceId, targetId);
        }
      });
    },
    renderStrip: function () {
      if (!$strip || !$strip.length) return;
      var p = ARQ.store.getProject();
      $strip.empty();
      if (!p || !p.hojas) return;
      var sorted = p.hojas.slice().sort(function (a, b) { return (a.orden || 0) - (b.orden || 0); });
      sorted.forEach(function (sh) {
        var $wrap = $('<div class="arq-sheet-tab-wrap" role="listitem" tabindex="0"/>').data('sheet-id', sh.id);
        var $tab = $('<div class="arq-sheet-tab"/>');
        if (sh.id === p.hoja_activa_id) $wrap.addClass('arq-sheet-tab--active');

        var $drag = $('<div class="js-sheet-drag" draggable="true" title="Arrastrar para reordenar" aria-label="Reordenar hoja"/>').text('⋮⋮');
        var $name = $('<input type="text" class="js-sheet-name arq-sheet-name-input" autocomplete="off" spellcheck="false"/>')
          .val(sh.nombre || 'Hoja');

        var $del = $('<button type="button" class="js-sheet-del arq-sheet-del" aria-label="Eliminar hoja" title="Eliminar"/>').text('🗑');
        $tab.append($drag, $name, $del);
        $wrap.append($tab);
        $strip.append($wrap);
      });
      var sn = '';
      sorted.forEach(function (s) { if (s.id === p.hoja_activa_id) sn = s.nombre || ''; });
      $('#editor-sheet-name').val(sn);
    },
    /**
     * Reordena hojas en la barra (actualiza campo orden).
     */
    reorderSheets: function (sourceId, targetId) {
      var p = ARQ.store.getProject();
      if (!p || !p.hojas || p.hojas.length < 2) return;
      var sorted = p.hojas.slice().sort(function (a, b) { return (a.orden || 0) - (b.orden || 0); });
      var from = -1;
      var to = -1;
      var i;
      for (i = 0; i < sorted.length; i++) {
        if (String(sorted[i].id) === String(sourceId)) from = i;
        if (String(sorted[i].id) === String(targetId)) to = i;
      }
      if (from < 0 || to < 0 || from === to) return;
      ARQ.history.pushUndo();
      var moved = sorted.splice(from, 1)[0];
      sorted.splice(to, 0, moved);
      for (i = 0; i < sorted.length; i++) {
        sorted[i].orden = i + 1;
      }
      ARQ.store.setDirty(true);
      this.renderStrip();
      ARQ.canvasEngine.redraw();
      ARQ.history.pushDescription('Reordenar hojas');
    },

    activate: function (sheetId) {
      var p = ARQ.store.getProject();
      if (!p) return;
      p.hoja_activa_id = sheetId;
      var sh = ARQ.utils.sheetById(p, sheetId);
      if (sh && sh.capas && sh.capas.length) {
        var sorted = ARQ.utils.sortLayers(sh.capas);
        ARQ.store.setActiveLayerId(sorted[sorted.length - 1].id);
      }
      var stage = global.document && global.document.getElementById('arq-canvas-stage');
      if (sh && stage && stage.clientWidth > 0 && stage.clientHeight > 0) {
        ARQ.viewport.fitToView(sh, stage.clientWidth, stage.clientHeight);
      } else if (sh) {
        ARQ.viewport.syncFromSheet(sh);
      }
      this.renderStrip();
      ARQ.layers.renderPanel();
      ARQ.canvasEngine.redraw();
      ARQ.bus.emit(ARQ.EVENTS.SHEET_CHANGED, sh);
    },
    addSheet: function () {
      var p = ARQ.store.getProject();
      if (!p) return;
      var maxO = 0;
      p.hojas.forEach(function (h) { maxO = Math.max(maxO, h.orden || 0); });
      var nid = ARQ.utils.uuid();
      var lid = ARQ.utils.uuid();
      p.hojas.push({
        id: nid,
        nombre: 'Hoja ' + (p.hojas.length + 1),
        orden: maxO + 1,
        ancho: 1920,
        alto: 1080,
        fondo: '#f4f4f5',
        zoom_actual: 1,
        rotacion_actual: 0,
        pan_actual: { x: 0, y: 0 },
        capas: [{
          id: lid,
          nombre: 'Capa base',
          tipo: 'vector',
          visible: true,
          bloqueada: false,
          opacidad: 1,
          blend_mode: 'normal',
          z_index: 0,
          es_capa_base: true,
          contenido: { strokes: [], texts: [], shapes: [] },
          metadatos: {},
        }],
        historial: { undo: [], redo: [] },
        miniatura: '',
        timestamp_ultima_edicion: Date.now(),
      });
      p.hoja_activa_id = nid;
      ARQ.store.setDirty(true);
      this.activate(nid);
      ARQ.history.pushDescription('Nueva hoja');
    },
    applyCropRect: function (sheet, rx, ry, rw, rh) {
      if (!sheet || rw < 1 || rh < 1) return false;
      var ow = sheet.ancho || 1920;
      var oh = sheet.alto || 1080;
      rx = Math.max(0, Math.min(Math.floor(rx), ow - 1));
      ry = Math.max(0, Math.min(Math.floor(ry), oh - 1));
      rw = Math.max(1, Math.min(Math.round(rw), ow - rx));
      rh = Math.max(1, Math.min(Math.round(rh), oh - ry));
      ARQ.history.pushUndo();
      (sheet.capas || []).forEach(function (l) {
        ARQ.layers.shiftLayerContent(l, -rx, -ry);
      });
      sheet.ancho = rw;
      sheet.alto = rh;
      if (ARQ.selection && ARQ.selection.clear) ARQ.selection.clear(sheet);
      if (ARQ.transform && ARQ.transform.deactivate) ARQ.transform.deactivate();
      ARQ.store.setDirty(true);
      ARQ.canvasEngine.redraw();
      if (ARQ.layers && ARQ.layers.renderPanel) ARQ.layers.renderPanel();
      ARQ.bus.emit(ARQ.EVENTS.SHEET_CHANGED);
      if (ARQ.history.pushDescription) ARQ.history.pushDescription('Recortar hoja');
      if (ARQ.actionLog && ARQ.actionLog.append) {
        ARQ.actionLog.append(sheet, 'crop', null, { x: rx, y: ry, w: rw, h: rh });
      }
      return true;
    },

    duplicateSheet: function (sheetId) {
      var p = ARQ.store.getProject();
      if (!p) return;
      var src = ARQ.utils.sheetById(p, sheetId);
      if (!src) return;
      var copy = ARQ.utils.deepClone(src);
      copy.id = ARQ.utils.uuid();
      copy.nombre = (copy.nombre || 'Hoja') + ' copia';
      copy.orden = (p.hojas.length ? Math.max.apply(null, p.hojas.map(function (h) { return h.orden || 0; })) : 0) + 1;
      (copy.capas || []).forEach(function (l) { l.id = ARQ.utils.uuid(); });
      p.hojas.push(copy);
      p.hoja_activa_id = copy.id;
      ARQ.store.setDirty(true);
      this.activate(copy.id);
    },
    renameSheetById: function (sheetId, desiredName) {
      var p = ARQ.store.getProject();
      if (!p) return;
      var sh = ARQ.utils.sheetById(p, sheetId);
      if (!sh) return;
      var all = (p.hojas || []).filter(function (h) { return h.id !== sheetId; }).map(function (h) { return h.nombre || ''; });
      var n = uniqueSiblingName(desiredName, all);
      if (n === sh.nombre) {
        this.renderStrip();
        return;
      }
      sh.nombre = n;
      sh.timestamp_ultima_edicion = Date.now();
      ARQ.store.setDirty(true);
      this.renderStrip();
      ARQ.history && ARQ.history.pushDescription && ARQ.history.pushDescription('Renombrar hoja');
    },
    removeSheetById: function (sheetId) {
      var p = ARQ.store.getProject();
      if (!p || !p.hojas) return;
      if (p.hojas.length <= 1) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Debe existir al menos una hoja');
        return;
      }
      var sh = ARQ.utils.sheetById(p, sheetId);
      if (!sh) return;
      p.hojas = p.hojas.filter(function (h) { return h.id !== sheetId; });
      if (p.hoja_activa_id === sheetId) {
        var sorted = p.hojas.slice().sort(function (a, b) { return (a.orden || 0) - (b.orden || 0); });
        p.hoja_activa_id = sorted.length ? sorted[0].id : null;
      }
      ARQ.store.setDirty(true);
      this.activate(p.hoja_activa_id);
      ARQ.history && ARQ.history.pushDescription && ARQ.history.pushDescription('Eliminar hoja');
    },
  };
})(typeof window !== 'undefined' ? window : this);
