(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.materials = {
    init: function () {
      var self = this;
      $('#panel-materials').on('click', '.js-add-material', function () {
        self.addFromColor(ARQ.tools.color);
      });
      $('#panel-materials').on('click', '.js-export-mat', function () {
        self.exportJson();
      });
      $('#panel-materials').on('blur', '.js-mat-name', function () {
        var id = $(this).closest('.arq-material-row').data('id');
        var name = $(this).val();
        self.updateName(id, name);
      });
    },
    render: function () {
      var $p = $('#panel-materials');
      $p.empty();
      $p.append($('<button type="button" class="arq-btn arq-btn--secondary js-add-material"/>').text('Asociar color actual'));
      $p.append($('<button type="button" class="arq-btn arq-btn--ghost js-export-mat"/>').text('Exportar JSON'));
      var p = ARQ.store.getProject();
      if (!p) return;
      p.materiales = p.materiales || [];
      p.materiales.forEach(function (m) {
        var row = $('<div class="arq-material-row"/>').data('id', m.id);
        row.append($('<div class="arq-material-swatch"/>').css('background', m.hex || '#ccc'));
        row.append($('<input class="arq-input js-mat-name" type="text"/>').val(m.nombre_material || '').attr('placeholder', 'Material'));
        $p.append(row);
      });
    },
    addFromColor: function (hex) {
      var p = ARQ.store.getProject();
      if (!p) return;
      p.materiales = p.materiales || [];
      var id = ARQ.utils.uuid();
      p.materiales.push({
        id: id,
        hex: hex,
        rgba: null,
        nombre_material: 'Nuevo material',
        descripcion_material: '',
        tags: [],
      });
      ARQ.tools.colorMaterialId = id;
      ARQ.store.setDirty(true);
      this.render();
    },
    updateName: function (id, name) {
      var p = ARQ.store.getProject();
      if (!p || !p.materiales) return;
      var m = null;
      (p.materiales || []).forEach(function (x) { if (x.id === id) m = x; });
      if (m) {
        m.nombre_material = name;
        ARQ.store.setDirty(true);
      }
    },
    exportJson: function () {
      var p = ARQ.store.getProject();
      if (!p) return;
      var blob = new Blob([JSON.stringify(p.materiales || [], null, 2)], { type: 'application/json' });
      var a = global.document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = 'materiales_' + (p.id || 'proyecto') + '.json';
      a.click();
      URL.revokeObjectURL(a.href);
    },
  };
})(typeof window !== 'undefined' ? window : this);
