document.addEventListener('DOMContentLoaded', function() {
  window.containerHtmlList = document.getElementById('html_list');
  window.containerTabList = document.getElementById('tab-info');
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

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

  const TOKEN = document.body.dataset.token;

  let moduleId = MODULE_KEYS;
  moduleId++;

  let moduleCounter = containerHtmlList.querySelectorAll('.js-module').length + 1;

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

  function addCkeditor(context) {
    context = context || document;
    var htmlList = context.querySelectorAll('.js-ckeditor');
    for (let i = 0; i < htmlList.length; i++) {
      var id = htmlList[i].getAttribute('id');

      CKEDITOR.replace(`${id}`, {
        filebrowserBrowseUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        filebrowserImageBrowseUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        filebrowserFlashBrowseUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        filebrowserUploadUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        filebrowserImageUploadUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=' + TOKEN,
        toolbar: [
          { name: 'document', items: ['Source', 'NewPage', 'Preview', 'Templates'] },
          { name: 'nav', items: ['Undo', 'Redo'] },
          { name: 'text', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
          { name: 'extras', items: ['Link', 'Unlink', 'NumberedList', 'BulletedList'] },
          { name: 'extras', items: ['NumberedList', 'BulletedList'] },
          { name: 'basicstyles', items: ['Table', 'Image', 'HorizontalRule'] },
        ],
      });
    }
  }

  addCkeditor();

  function initTabs(context) {
    context = context || document;
    var controlTabs = containerTabList.querySelectorAll('[data-tab-control]');
    for (let i = 0; i < controlTabs.length; i++) {
      controlTabs[i].click();
    }
  }

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

  iniRemoveModule();

  function removeModule() {
    const MODULE = this.closest('.js-module'),
      TAB_ID = this.closest('.js-module').getAttribute('data-tab');

    var tabs = document.querySelectorAll('.js-tab');

    for (let i = 0; i < tabs.length; i++) {
      const ELEMENT = tabs[i];
      const ID = ELEMENT.getAttribute('data-tab-control');

      if (ID == TAB_ID) {
        MODULE.remove();
        ELEMENT.remove();
        initTabs();
      }
    }
  }

  for (const key in MODULES) {
    addModule(MODULES[key]);
  }

  function addModule(module = { description: {} }) {
    const { description, layout_id, position, status, sort_order } = module;

    const MODULE_CONTAINER = document.createElement('div'),
      TAB_CONTAINER = document.createElement('span'),
      TAB = `Módulo ${moduleCounter}`,
      LAYOUTS = info.layouts,
      POSITIONS = Type_ModulePosition.getEnumList(),
      STATUS = Type_Status.getEnumList(),
      HTML = `
          <div class="col-xs-12 col-md-8">
          <div class="content-box bottom-padding-large">
            <div class="flex between-xs middle-xs">
              <span class="text-x-large text-dark">
                ${language.get('tab_module')} ${moduleCounter}
              </span>
              <button type="button" class="btn-default btn-medium btn-primary js-btn-remove">
                <span>Remover</span>
              </button>
            </div>
          </div>
          <div class="content-box">
            <div class="js-html-page">
              <textarea class="field-entry js-ckeditor" name="welcome_module[${moduleId}][description][${LANGUAGE_ID}]" id="js_ckeditor_${moduleId}">${typeof description !== 'undefined' ? description[LANGUAGE_ID] : ''}</textarea>
            </div>
          </div>
        </div>
        <div class="col-xs-12 col-md-4">
          <div class="content-box background-white shadow-small padding-large">
            <div class="row no-space-xs">
              <label class="field fiel-medium">
                <span class="field-label">${language.get('entry_layout')}</span>
                <select class="field-entry" name="welcome_module[${moduleId}][layout_id]">
                  ${LAYOUTS.map(
                    layout =>
                      `<option value="${layout.layout_id}" ${
                        layout_id == layout.layout_id ? 'selected="selected"' : ''
                      }>${layout.name}</option>`
                  ).join('')}
                </select>
              </label>
              <label class="field fiel-medium top-padding-large">
                <span class="field-label">${language.get('entry_position')}</span>
                <select class="field-entry" name="welcome_module[${moduleId}][position]">
                  ${Object.keys(POSITIONS)
                    .map(
                      key => `<option value="${key}" ${position == key ? 'selected' : ''}>${POSITIONS[key]}</option>`
                    )
                    .join('')}
                </select>
              </label>
              <label class="field fiel-medium top-padding-large">
                <span class="field-label">${language.get('entry_status')}</span>
                <select class="field-entry" name="welcome_module[${moduleId}][status]">
                  ${Object.keys(STATUS)
                    .map(key => `<option value="${key}" ${status == key ? 'selected' : ''}>${STATUS[key]}</option>`)
                    .join('')}
                </select>
              </label>
              <label class="field fiel-medium top-padding-large">
                <span class="field-label">${language.get('entry_sort_order')}</span>
                <input class="field-entry mask-number2" type="text" name="welcome_module[${moduleId}][sort_order]"
                  value="${typeof sort_order !== 'undefined' ? sort_order : ''}" size="3"
                >
              </label>
            </div>
          </div>
        </div>`;

    TAB_CONTAINER.setAttribute('data-tab-control', `tab-info-${moduleId}`);
    TAB_CONTAINER.setAttribute(
      'class',
      'text-small text-gray cursor-pointer horizontal-padding-medium vertical-padding-small tab js-tab'
    );
    TAB_CONTAINER.innerHTML = TAB;

    MODULE_CONTAINER.id = moduleId;
    MODULE_CONTAINER.setAttribute('class', 'row hidden js-module');
    MODULE_CONTAINER.setAttribute('data-tab', `tab-info-${moduleId}`);

    MODULE_CONTAINER.innerHTML = HTML;
    containerHtmlList.appendChild(MODULE_CONTAINER);
    containerTabList.appendChild(TAB_CONTAINER);

    initTabs(MODULE_CONTAINER);
    addCkeditor(MODULE_CONTAINER);
    iniRemoveModule(MODULE_CONTAINER);

    moduleId++;
    moduleCounter++;
  }
});
