(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.editor = {
    init: function () {
      var canvas = document.getElementById('arq-main-canvas');
      var inner = document.getElementById('arq-viewport-inner');
      var stage = document.getElementById('arq-canvas-stage');
      ARQ.canvasEngine.init(canvas);
      ARQ.viewport.init({ innerEl: inner, canvas: canvas });
      ARQ.pointer.init(canvas);
      ARQ.gestures.init(document.getElementById('arq-canvas-wrap'), {
        rotateEnabled: (ARQ.storage.get(ARQ.STORAGE_KEYS.UI_PREFS) || {}).rotateGesture !== false,
      });
      ARQ.keyboard.init();
      ARQ.layers.init();
      ARQ.sheets.init();
      ARQ.assets.init();
      ARQ.materials.init();
      ARQ.selection.init();

      $('#btn-add-layer').on('click', function () { ARQ.layers.addLayer(); });
      $('#btn-del-layer').on('click', function () { ARQ.layers.removeActiveLayer(); });

      function syncToolAdvancedUi(t) {
        var show = ARQ.tools.showsToleranceUi && ARQ.tools.showsToleranceUi();
        $('#tool-advanced-wrap').attr('hidden', !show);
        $('#arq-canvas-wrap').css('cursor', t === 'mover' ? 'move' : '');
      }

      $('.arq-tool[data-tool]').on('click', function () {
        ARQ.tools.setTool($(this).data('tool'));
      });

      ARQ.bus.on(ARQ.EVENTS.TOOL_CHANGED, function (t) {
        $('.arq-tool[data-tool]').removeClass('arq-tool--active');
        $('.arq-tool[data-tool="' + t + '"]').addClass('arq-tool--active');
        syncToolAdvancedUi(t);
      });

      $('#tool-color').on('input change', function () { ARQ.tools.color = $(this).val(); });
      $('#tool-size').on('input change', function () { ARQ.tools.size = parseInt($(this).val(), 10) || 4; });
      $('#tool-opacity').on('input change', function () { ARQ.tools.opacity = (parseInt($(this).val(), 10) || 100) / 100; });
      $('#tool-smooth').on('input change', function () { ARQ.tools.smooth = parseInt($(this).val(), 10) || 0; });
      $('#tool-tolerance').on('input change', function () {
        ARQ.tools.syncFromDom && ARQ.tools.syncFromDom();
      });
      $('#tool-contiguous').on('change', function () {
        ARQ.tools.syncFromDom && ARQ.tools.syncFromDom();
      });
      $('#tool-crop-ratio').on('change', function () {
        ARQ.tools.syncFromDom && ARQ.tools.syncFromDom();
      });

      $('.arq-tab[data-tab]').on('click', function () {
        var tab = $(this).data('tab');
        $('.arq-tab[data-tab]').removeClass('arq-tab--active');
        $(this).addClass('arq-tab--active');
        $('.arq-tab-panel').attr('hidden', true).removeClass('arq-tab-panel--active');
        var $p = $('.arq-tab-panel[data-panel="' + tab + '"]');
        $p.attr('hidden', false).addClass('arq-tab-panel--active');
        if (tab === 'materials') ARQ.materials.render();
        if (tab === 'assets') ARQ.assets.renderThumbs();
      });

      $('#btn-toggle-panel').on('click', function () {
        $('#arq-panel-right').toggleClass('is-collapsed');
      });

      $('#prop-layer-opacity').on('input change', function () {
        var layer = ARQ.store.activeLayer();
        if (!layer) return;
        ARQ.history.pushUndo();
        layer.opacidad = (parseInt($(this).val(), 10) || 100) / 100;
        ARQ.store.setDirty(true);
        ARQ.canvasEngine.redraw();
      });

      $('#btn-undo').on('click', function () { ARQ.history.undo(); });
      $('#btn-redo').on('click', function () { ARQ.history.redo(); });
      $('#btn-export-menu').on('click', function () { ARQ.dialogExport.open(); });
      $('#btn-ai-global').on('click', function () {
        if (ARQ.aiGlobal && ARQ.aiGlobal.open) ARQ.aiGlobal.open();
      });
      if (ARQ.aiGate && ARQ.aiGate.refresh) {
        ARQ.aiGate.refresh().then(function () {
          if (ARQ.layers && ARQ.layers.renderPanel) ARQ.layers.renderPanel();
          if (ARQ.aiGlobal && ARQ.aiGlobal.syncUi) ARQ.aiGlobal.syncUi();
        });
      } else if (ARQ.aiGlobal && ARQ.aiGlobal.syncUi) {
        ARQ.aiGlobal.syncUi();
      }

      function resizeStage() {
        if (!stage || !ARQ.store.getProject()) return;
        var sh = ARQ.utils.activeSheet(ARQ.store.getProject());
        if (sh && stage.clientWidth > 0 && stage.clientHeight > 0) {
          ARQ.viewport.fitToView(sh, stage.clientWidth, stage.clientHeight);
        } else if (sh) {
          ARQ.viewport.syncFromSheet(sh);
        }
        ARQ.canvasEngine.requestRedraw();
      }
      global.addEventListener('resize', ARQ.utils.debounce(resizeStage, 150));

      ARQ.bus.on(ARQ.EVENTS.PROJECT_LOADED, function () {
        var p = ARQ.store.getProject();
        var sh = ARQ.utils.activeSheet(p);
        $('#editor-project-name').text((p && p.nombre) || '');
        ARQ.viewport.syncFromSheet(sh);
        if (stage) ARQ.viewport.fitToView(sh, stage.clientWidth, stage.clientHeight);
        ARQ.sheets.renderStrip();
        ARQ.layers.renderPanel();
        ARQ.assets.renderThumbs();
        ARQ.materials.render();
        ARQ.canvasEngine.redraw();
        var layer = ARQ.store.activeLayer();
        $('#prop-layer-opacity').val(layer && layer.opacidad != null ? Math.round(layer.opacidad * 100) : 100);
        if (ARQ.aiGlobal && ARQ.aiGlobal.syncUi) ARQ.aiGlobal.syncUi();
        syncToolAdvancedUi(ARQ.tools.currentTool());
      });

      function refitIfEditorVisible() {
        if (!stage || !ARQ.store.getProject()) return;
        var sh = ARQ.utils.activeSheet(ARQ.store.getProject());
        if (!sh) return;
        ARQ.viewport.fitToView(sh, stage.clientWidth, stage.clientHeight);
        ARQ.canvasEngine.requestRedraw();
      }

      ARQ.bus.on(ARQ.EVENTS.ROUTE, function (name) {
        if (name !== 'editor') return;
        syncToolAdvancedUi(ARQ.tools.currentTool());
        // Espera a que el layout esté pintado (la vista estaba oculta al cargar proyecto)
        requestAnimationFrame(function () {
          requestAnimationFrame(function () {
            refitIfEditorVisible();
          });
        });
      });

      ARQ.bus.on(ARQ.EVENTS.SHEET_CHANGED, function () {
        var sh = ARQ.utils.activeSheet(ARQ.store.getProject());
        if (sh) ARQ.viewport.syncFromSheet(sh);
        ARQ.layers.renderPanel();
        ARQ.canvasEngine.redraw();
      });
    },
    openProject: function (project) {
      project = ARQ.migrations.run(project);
      ARQ.store.setProject(project);
      ARQ.store.setDirty(false);
      ARQ.bus.emit(ARQ.EVENTS.PROJECT_LOADED, project);
    },
  };
})(typeof window !== 'undefined' ? window : this);
