var FormeaCurrentEmailInput = "";

window.addEventListener('DOMContentLoaded', function () {
  var adminColumnApp = new AdminColumnDisplay(langCode, langText, selectedAdminColumn);

  var el = document.getElementsByTagName('joomla-tab');
  if (el !== undefined) {
    var formeaForm = document.getElementById('formea-form');
    if (el.length > 0) {
      for (var i = 0; i < el.length; i++) {
        el[i].addEventListener('joomla.tab.show', function () {
          window.dispatchEvent(new Event('resize'));
        });
      }
    }
  }

  window.addEventListener('FormeaGridReady', (evt) => {
    adminColumnApp.resetElements(evt.detail.items);
    resetPlaceholders(evt.detail.items);
  });
  window.addEventListener('FormeaAddElement', (evt) => {
    const item = JSON.parse(JSON.stringify(evt.detail.added_item));
    item.content = item.title;
    adminColumnApp.addGridElement(item);
    generatePlaceholders([item]);
  });
  window.addEventListener('FormeaEditElement', (evt) => {
    if (evt.detail !== undefined) {
      var elId = 0;
      var action = 'add';
      if (!evt.detail.isNew) {
        elId = evt.detail.element_id;
        action = 'edit';
      }
      var mdl = document.getElementById('modal-element');
      var iframeString = '<iframe class="iframe" name="test" title="test" height="100%" width="100%"';
      iframeString += ' src="index.php?option=com_formea&amp;task=element.edit&amp;type=' + evt.detail.type + '&amp;id=' + elId + '&amp;layout=modal&amp;tmpl=component"';
      iframeString += '></iframe>';

      mdl.setAttribute('data-url', elementUrl + '&id=' + elId + '&type=' + evt.detail.type);
      mdl.setAttribute('data-iframe', iframeString);

      var mdlTitle = mdl.querySelector('.modal-title');
      mdlTitle.innerHTML = evt.detail.type;
      const myModal = new bootstrap.Modal(document.getElementById('modal-element'), {});
      myModal.show();

      var elementIdInput = document.getElementById('edit_element_id');
      elementIdInput.setAttribute('data-detail', JSON.stringify(evt.detail));

      var cancel_edit_element = document.getElementById('cancel_edit_element');
      cancel_edit_element.setAttribute('data-action', action);

      var save_edit_element = document.getElementById('save_edit_element');
      save_edit_element.setAttribute('data-action', action);
    }

  });

  window.addEventListener('FormeaRemoveElement', (evt) => {
    const item = evt.detail.removed_item;
    const items = evt.detail.items;
    item.content = item.title;
    adminColumnApp.removeElement(item);
    removePlaceholders(item.id);
  });

  window.addEventListener('FormeaFormSettingChanged', (evt) => {
    if (evt.detail.formType !== undefined && evt.detail.formType !== null) {
      const formTypeEl = document.getElementById('jform_form_type');
      if (formTypeEl !== undefined) {
        formTypeEl.value = evt.detail.formType;
      }
    }
    if (evt.detail.renderer_id !== undefined && evt.detail.renderer_id !== null) {
      const renderIdEl = document.getElementById('jform_params_renderer_id');
      if (renderIdEl !== undefined) {
        renderIdEl.value = evt.detail.renderer_id;
      }
    }
    if (evt.detail.renderer_style_id !== undefined && evt.detail.renderer_style_id !== null) {
      const renderStyleIdEl = document.getElementById('jform_params_renderer_style_id');
      if (renderStyleIdEl !== undefined) {
        renderStyleIdEl.value = evt.detail.renderer_style_id;
      }
    }
  });

  var themeInput = document.getElementById('jform_themes_theme_id');
  FormeaPopulateThemeStyleId('jform_themes_style_id', themeInput);

  /*Updated for v1.1.1*/
  window.addEventListener('FormeaTriggerNotification', (evt) => {
    Joomla.renderMessages({"error":[evt.detail.message]});
  });

  var allEmailInput = document.querySelectorAll('[id^="jform_emails_"]');

  if(allEmailInput !== undefined && allEmailInput !== null){
    allEmailInput.forEach(function (emailInput) {
      emailInput.addEventListener('focus',function(){
        FormeaCurrentEmailInput = emailInput.getAttribute('id');
      });
    });
  }

});




var generatePlaceholders = function (items) {

  var ph = document.getElementById('key_placeholders');
  if (ph !== undefined && ph !== null) {
    var ttl = items.length;
    for (let i = 0; i < ttl; i++) {
      if (items[i].isGroup) {
        if (items[i].groupContent !== undefined && items[i].groupContent !== null) {
          const groupContent = items[i].groupContent;
          const ttlGroupedElements = groupContent.inputGroupItem.elements.length;
          for (let j = 0; j < ttlGroupedElements; j++) {
            let tempObj = {
              isGroup: true,
              group_id: groupContent.inputGroupItem.elements[j].group_id,
              id: groupContent.inputGroupItem.elements[j].element_id,
              alias: groupContent.inputGroupItem.elements[j].alias,
            }
            drawPlaceHolderList(tempObj).then(result => {
              ph.appendChild(result.list);
              ph.appendChild(result.listCaption);
              if(result.listLink !== undefined && result.listLink !== null){
                ph.appendChild(result.listLink);
              }
            }, error => {
              console.log('error');
            });
          }
        }else{
          let tempObj = {
            isGroup: true,
            group_id: items[i].group_id,
            id: items[i].element_id,
            alias: items[i].alias,
          }

          drawPlaceHolderList(tempObj).then(result => {
            ph.appendChild(result.list);
            ph.appendChild(result.listCaption);
            if(result.listLink !== undefined && result.listLink !== null){
              ph.appendChild(result.listLink);
            }
          }, error => {
            console.log('error');
          });

        }
      } else {
        drawPlaceHolderList(items[i]).then(result => {
          ph.appendChild(result.list);
          ph.appendChild(result.listCaption);
          if(result.listLink !== undefined && result.listLink !== null){
            ph.appendChild(result.listLink);
          }
        }, error => {
          console.log('error');
        });
      }

    }
  }
}

var drawPlaceHolderList = function (item) {
  return new Promise(resolve => {
    let ret = {
      list: null,
      listCaption: null,
      listLink: null,
    }
    let opener = '[';
    let openerId = '';
    let idType = '_'
    if (item.isGroup > 0) {
      opener = '[GP_' + item.group_id + '_';
      openerId = 'gp_' + item.group_id + '_';
      idType = '_gp_'
    }
    var _text = opener + (item.alias).toUpperCase();
    var list = document.createElement('li');
    var valueText =  _text+ ':VALUE]'
    list.setAttribute('id', 'placeholder' + idType + 'value_' + item.id);
    var cd = document.createElement('button');
    cd.setAttribute('type','button');
    cd.setAttribute('title',FsrGlobal.langText.copyToClipBoard);
    cd.setAttribute('onclick','FormeaCopyClipboard("'+valueText+'","placeholderClipboard")');
    cd.innerHTML = valueText;
    list.appendChild(cd);
    ret.list = list;

    var listCaption = document.createElement('li');
    listCaption.setAttribute('id', 'placeholder' + idType + 'caption_' + item.id);
    var captionText = _text + ':CAPTION]';
    var cdCaption = document.createElement('button');
    cdCaption.setAttribute('type','button');
    cdCaption.setAttribute('title',FsrGlobal.langText.copyToClipBoard);
    cdCaption.setAttribute('onclick','FormeaCopyClipboard("'+captionText+'","placeholderClipboard")');
    cdCaption.innerHTML = captionText;
    listCaption.appendChild(cdCaption);
    ret.listCaption = listCaption;

    if (parseInt(item.value_type) === 6) {
      var listLink = document.createElement('li');
      listLink.setAttribute('id', 'placeholder' + idType + 'link_' + item.id);
      var linkText = _text + ':LINK]';
      var cdLink = document.createElement('button');
      cdLink.setAttribute('type','button');
      cdLink.setAttribute('title',FsrGlobal.langText.copyToClipBoard);
      cdLink.setAttribute('onclick','FormeaCopyClipboard("'+linkText+'","placeholderClipboard")');
      cdLink.innerHTML = linkText;
      listLink.appendChild(cdLink);
      ret.listLink = listLink;
    }
    resolve(ret);
  });
}

var resetPlaceholders = function (items) {
  var ph = document.getElementById('key_placeholders');
  if (ph !== undefined && ph !== null) {
    var lists = ph.querySelectorAll('[id^="placeholder_"]');
    lists.forEach((element) => {
      element.remove();
    });
    generatePlaceholders(items);
  }

}

var removePlaceholders = function (id) {
  var targetValue = document.getElementById('placeholder_value_' + id);
  var targetCaption = document.getElementById('placeholder_caption_' + id);
  var targetLink = document.getElementById('placeholder_link_' + id);
  if (targetValue !== undefined && targetValue !== null) {
    targetValue.remove();
  }
  if (targetCaption !== undefined && targetCaption !== null) {
    targetCaption.remove();
  }
  if (targetLink !== undefined && targetLink !== null) {
    targetLink.remove();
  }
}


var formeaProcessModal = function (el) {
  var props = {
    'fieldPrefix': '',
    'action': '',
    'itemType': '',
    'task': '',
    'formId': '',
    'idFieldId': '',
    'titleFieldId': '',
  };
  Object.keys(props).forEach(function (key) {
    var t = el.getAttribute('data-' + key.toLowerCase());
    if (t !== undefined && t !== null) {
      props[key] = t;
    }
  });
  var elTask = el.getAttribute('data-task');
  //(element, fieldPrefix, action, itemType, task, formId, idFieldId, titleFieldId)
  window.processModalEdit(el, props.fieldPrefix, props.action, props.itemType, props.task, props.formId, props.idFieldId, props.titleFieldId);
  if (elTask !== undefined && elTask !== null) {
    if (elTask !== 'cancel') {
      setTimeout(function () {
        FormeaElementIdChange();
      }, 500)
    }
  }

  return false;
};

var FormeaElementIdChange = function () {
  var el = document.getElementById('edit_element_id');
  var element_id = el.value;
  if (element_id !== undefined && element_id !== null && !isNaN(element_id) && element_id !== '') {
    var detail = el.getAttribute('data-detail');
    if (detail !== undefined && detail !== null) {
      detail = JSON.parse(detail);
      detail['element_id'] = parseInt(element_id);
      var panel = document.querySelector('formea-layout');
      if (panel !== undefined) {
        panel.externalElementUpdate(detail);
      }
    }
  } else {
    setTimeout(function(){
      FormeaElementIdChange();
    },500);
  }
}

var FormeaPopulateThemeStyleId = function (target, el) {
  var joomlaScriptOptions = document.querySelector('.joomla-script-options');
  var scriptOption = JSON.parse(joomlaScriptOptions.innerHTML);
  var themeStyleInput = document.getElementById(target);

  if (parseInt(el.value) > 0) {

    var staticStyleInput = document.getElementById('static_style_id');
    var staticThemeInput = document.getElementById('static_theme_id');
    var staticStyleId = staticStyleInput.value;
    var staticThemeId = staticThemeInput.value;
    let hostUrl = window.location.origin;
    hostUrl += '/administrator/index.php?option=com_formea&task=theme.getStyles&id=' + el.value + '&' + scriptOption['csrf.token'] + '=1';
    fetch(hostUrl)
      .then(response => {
        return response.json();
      })
      .then(data => {
        if (data.success) {

          var styles = data.result.styles;
          while (themeStyleInput.options.length > 1) {
            themeStyleInput.remove(1);
          }
          styles.forEach(item => {
            const option = document.createElement('option');
            option.value = item.id; // Set the value attribute
            option.text = item.title;   // Set the visible text
            if (parseInt(item.id) === parseInt(staticStyleId) && parseInt(el.value) === parseInt(staticThemeId)) {
              option.selected = true;
            }
            themeStyleInput.appendChild(option);
          });
        }
      })
      .catch(error => console.error(error));
  }
}

var FormeaCopyClipboard = function(textVal,inputId){
  var _input = document.getElementById(inputId);
  _input.value = textVal;
  _input.select();
  navigator.clipboard.writeText(_input.value)
    .then(() => {
      //alert("Text copied to clipboard: " + copyText.value);
      if(FormeaCurrentEmailInput !== undefined && FormeaCurrentEmailInput !== null && FormeaCurrentEmailInput.length > 0){
        var readyValue = document.getElementById(FormeaCurrentEmailInput).value;
        if(readyValue.length > 0){
          document.getElementById(FormeaCurrentEmailInput).value += _input.value;
        }else{
          document.getElementById(FormeaCurrentEmailInput).value = _input.value;
        }
      }
    })
    .catch(err => {
      console.error('Failed to copy text: ', err);
    });
}
