if (document.readyState === 'complete') {
  init();
} else {
  document.addEventListener('DOMContentLoaded', function() {
    init();
  });
}

function init() {
  window.moduleContainerList = document.getElementById('module_container');
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

  window.language.add(window.info.languagesJS);
  window.language.load('module/bestseller');

  const MODULES = window.info.modules;
  for (const key in MODULES) {
    addModule(MODULES[key]);
  }

  document.getElementById('add_module').onclick = addModule;
}

let moduleId = '';
moduleId++;

function initRemoveModule(context) {
  context = context || document;
  let removeButtons = context.querySelectorAll('.js-remove-module');
  for (let i = 0; i < removeButtons.length; i++) {
    removeButtons[i].onclick = removeModule;
  }
}

function removeModule() {
  this.closest('.js-bestseller').remove();
}

function controlGrid(context) {
  context = context || document;
  let gridEntries = context.querySelectorAll('.js-control-grid');
  for (let i = 0; i < gridEntries.length; i++) {
    const GRID = gridEntries[i];
    GRID.dispatchEvent(new Event('change', { bubbles: true }));
  }
}

function addModule(module = {}) {
  const { layout_id, position, status, sort_order, entry_type, limit } = module;

  const MODULE_CONTAINER = document.createElement('div'),
    POSITIONS = window.info.positions,
    TYPES = Type_DsimDnao.getEnumList(),
    LAYOUTS = info.layouts,
    STATUS = Type_Status.getEnumList(),
    ERROR_LIMIT = info.error_limit,
    ERROR_GRID = info.error_grid_limit,
    ERROR_SORT_ORDER = info.error_sort_order,
    HTML = `
  <div class="row x-small-space-xs">
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_position')}</span>
        <select class="field-entry js-control-position" name="bestseller_module[${moduleId}][position]">
        ${Object.keys(POSITIONS)
          .map(key => `<option value="${key}" ${position == key ? 'selected' : ''}>${POSITIONS[key]}</option>`)
          .join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('text_type')}</span>
        <select class="field-entry js-control-grid" name="bestseller_module[${moduleId}][entry_type]"
          ${typeof position !== 'undefined' && position == Type_ModulePosition.Tp_ColumnLeft ? 'disabled=true' : ''}>
          ${Object.keys(TYPES)
            .map(key => `<option value="${key}" ${key == entry_type ? 'selected' : ''}>${TYPES[key]}</option>`)
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_limit')}</span>
        <input type="text" class="field-entry js-control-limit mask-number2" name="bestseller_module[${moduleId}][limit]"
          value="${typeof limit !== 'undefined' ? limit : Type_DefaultValues.Tp_LimitModules24}" size="1"
          ${entry_type == 0 && position !== Type_ModulePosition.Tp_ColumnLeft ? 'disabled=true' : ''}>
        ${ERROR_LIMIT[moduleId] ? `<span class="text-error text-x-small">${ERROR_LIMIT[moduleId]}</span>` : ''}
        ${ERROR_GRID[moduleId] ? `<span class="text-error text-x-small">${ERROR_GRID[moduleId]}</span>` : ''}
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_layout')}</span>
        <select class="field-entry" name="bestseller_module[${moduleId}][layout_id]">
          ${LAYOUTS.map(
            layout =>
              `<option value="${layout.layout_id}" ${layout.layout_id == layout_id ? 'selected' : ''}>${
                layout.name
              }</option>`
          ).join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_status')}</span>
        <select class="field-entry" name="bestseller_module[${moduleId}][status]">
          ${Object.keys(STATUS)
            .map(key => `<option value="${key}" ${status == key ? 'selected' : ''}>${STATUS[key]}</option>`)
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${language.get('entry_sort_order')}</span>
        <input type="text" name="bestseller_module[${moduleId}][sort_order]"
        value="${typeof sort_order !== 'undefined' ? sort_order : 0}" size="1" class="field-entry mask-number2">
        ${
          ERROR_SORT_ORDER[moduleId] ? `<span class="text-error text-x-small">${ERROR_SORT_ORDER[moduleId]}</span>` : ''
        }
      </label>
    </div>
    <div class="col-xs-12 col-md-width-auto">
      <div class="padding-medium cursor-pointer top-margin-medium js-remove-module"
      data-tooltip="${language.get('button_remove')}"
      >
        <i class="fas fa-trash text-gray"></i>
      </div>
    </div>
  </div>`;

  MODULE_CONTAINER.setAttribute(
    'class',
    'background-white padding-large bottom-margin-medium shadow-small adm-focus-within js-bestseller'
  );
  MODULE_CONTAINER.innerHTML = HTML;
  window.moduleContainerList.prepend(MODULE_CONTAINER);
  initRemoveModule(MODULE_CONTAINER);
  controlGrid(MODULE_CONTAINER);

  moduleId++;
}
