'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-1894343a.js');
const utils = require('@sankhyalabs/ezui/dist/collection/utils');
const core = require('@sankhyalabs/core');
const sortable_esm = require('./sortable.esm-b87669ab.js');
const constants = require('./constants-6d82e405.js');
const FormConfigHelper = require('./FormConfigHelper-96a5ec2c.js');

const snkDynaformConfigHeaderCss = ".sc-snk-dynaform-config-header-h{display:flex;padding-top:var(--space--12, 12px);align-items:center;width:100%;justify-content:space-between}.left-group.sc-snk-dynaform-config-header{display:flex;gap:var(--space--8, 8px);align-items:center}.right-group.sc-snk-dynaform-config-header{display:flex}";

const SnkDynaformConfigHeader = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.configClose = index.createEvent(this, "configClose", 7);
    this.saveConfig = index.createEvent(this, "saveConfig", 7);
    this.isEditingGuide = false;
    this.isEditingGroup = false;
    this.configOptions = [];
    this.selectedConfig = undefined;
    this.messagesBuilder = undefined;
    this.hasChanges = false;
    this.optionConfigChanged = false;
  }
  handleIsEditingGuideName({ detail }) {
    this.isEditingGuide = detail;
  }
  handleIsEditingGroupName({ detail }) {
    this.isEditingGroup = detail;
  }
  saveFormConfig() {
    if (this.isEditingGuide || this.isEditingGroup) {
      const title = this.getMessage('snkFormConfig.confirm.title');
      const message = this.isEditingGuide
        ? this.getMessage('snkFormConfig.alert.titleGuideEditing')
        : this.getMessage('snkFormConfig.alert.titleGroupEditing');
      utils.ApplicationUtils.alert(title, message);
      return;
    }
    this.saveConfig.emit();
  }
  async closeFormConfig() {
    if (this.hasChanges) {
      const title = this.getMessage('snkFormConfig.confirm.title');
      const msg = this.getMessage('snkFormConfig.confirm.cancel');
      const confirm = await utils.ApplicationUtils.confirm(title, msg);
      if (!confirm)
        return;
    }
    this.configClose.emit();
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  openConfirmDialog(msg = '', title = this.getMessage('snkFormConfig.confirm.title')) {
    return utils.ApplicationUtils.confirm(title, msg);
  }
  async applyOptionConfig() {
    var _a, _b;
    const name = (_b = (_a = this.selectedConfig) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.getMessage('snkFormConfig.configs.selectedConfig');
    const msg = this.getMessage('snkFormConfig.confirm.apply').replace('{0}', name);
    const confirm = await this.openConfirmDialog(msg);
    if (confirm) {
      this.saveConfig.emit();
    }
  }
  renderSaveActions() {
    if (!this.hasChanges && !this.optionConfigChanged)
      return;
    if (this.hasChanges) {
      return (index.h("div", { class: "right-group" }, index.h("ez-button", { title: this.getMessage('snkFormConfig.actions.cancel'), label: this.getMessage('snkFormConfig.actions.cancel'), onClick: this.closeFormConfig.bind(this), size: "medium" }), index.h("ez-button", { title: this.getMessage('snkFormConfig.actions.save'), label: this.getMessage('snkFormConfig.actions.save'), class: 'ez-button--primary ez-padding-left--medium', onClick: () => this.saveFormConfig(), size: "medium" })));
    }
    return (index.h("div", { class: "right-group" }, index.h("ez-button", { title: this.getMessage('snkFormConfig.actions.cancel'), label: this.getMessage('snkFormConfig.actions.cancel'), onClick: this.closeFormConfig.bind(this), size: "medium" }), index.h("ez-button", { title: this.getMessage('snkFormConfig.actions.save'), label: this.getMessage('snkFormConfig.applyConfig'), class: 'ez-button--primary ez-padding-left--medium', onClick: async () => await this.applyOptionConfig(), size: "medium" })));
  }
  render() {
    return (index.h(index.Host, null, index.h("div", { class: 'left-group' }, index.h("ez-button", { mode: "icon", title: this.getMessage('snkFormConfig.goBackTitle'), iconName: "arrow_back", size: "small", onClick: this.closeFormConfig.bind(this), id: "formConfigToBack" }), index.h("h1", { class: "ez-title ez-title--primary ez-title--extra-large ez-padding--small" }, this.getMessage('snkFormConfig.title')), index.h("snk-dynaform-configs-button", { hasChanges: this.hasChanges, configOptions: this.configOptions, selectedConfig: this.selectedConfig, messagesBuilder: this.messagesBuilder })), this.renderSaveActions()));
  }
};
SnkDynaformConfigHeader.style = snkDynaformConfigHeaderCss;

const snkDynaformConfigsButtonCss = ".dropdown-container.sc-snk-dynaform-configs-button{font-family:'Roboto';font-size:12px;font-weight:400;display:flex;flex-direction:column;color:#2b3a54;width:200px}.main-item.sc-snk-dynaform-configs-button{padding:12px;font-size:14px;cursor:pointer;transition:all .2s ease-in-out;display:flex;flex-direction:row;gap:8px;align-items:center;justify-content:start}.main-item.sc-snk-dynaform-configs-button ez-icon.sc-snk-dynaform-configs-button{--ez-icon--color:#008561}.main-item.sc-snk-dynaform-configs-button:nth-of-type(1){padding-bottom:6px}.main-item.sc-snk-dynaform-configs-button:nth-of-type(2){padding-top:6px}.main-item.sc-snk-dynaform-configs-button:hover{background-color:#FAFCFF}.item-label.sc-snk-dynaform-configs-button{display:flex}";

const SnkDynaformConfigsButton = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.formConfigOptionSelected = index.createEvent(this, "formConfigOptionSelected", 7);
    this.configOptions = [];
    this.selectedConfig = undefined;
    this.hasChanges = false;
    this.messagesBuilder = undefined;
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  async showShareConfigOptions() {
    if (this._refOptionsPopover && this._refShareConfigBtn) {
      await this._refOptionsPopover.showUnder(this._refShareConfigBtn);
    }
  }
  async handleSelectOption(option) {
    if (core.ObjectUtils.equals(option, this.selectedConfig))
      return;
    if (this.hasChanges) {
      const title = this.getMessage('snkFormConfig.confirm.title');
      const msg = this.getMessage('snkFormConfig.confirm.cancel');
      const confirm = await utils.ApplicationUtils.confirm(title, msg);
      if (!confirm)
        return;
    }
    this.selectedConfig = option;
    this.formConfigOptionSelected.emit(option);
    await this._refOptionsPopover.hide();
  }
  getButtonLabel() {
    var _a, _b;
    return (_b = (_a = this.selectedConfig) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.getMessage('snkFormConfig.configs.buttonLabel');
  }
  renderConfigOptions() {
    return this.configOptions.map((option) => {
      return (index.h("div", { class: `main-item`, onClick: async () => await this.handleSelectOption(option) }, index.h("span", { class: 'item-label' }, " ", option.name), this.renderCheckIcon(option)));
    });
  }
  renderCheckIcon(option) {
    if (this.selectedConfig && this.selectedConfig.origin === option.origin)
      return index.h("ez-icon", { iconName: "check" });
  }
  render() {
    return (index.h(index.Host, null, index.h("ez-button", { ref: ref => this._refShareConfigBtn = ref, label: this.getButtonLabel(), onClick: async () => await this.showShareConfigOptions() }, index.h("ez-icon", { slot: "rightIcon", iconName: "chevron-down" })), index.h("ez-popover-plus", { ref: ref => this._refOptionsPopover = ref, autoClose: true, overlayType: "none" }, index.h("div", { class: 'dropdown-container' }, this.renderConfigOptions()))));
  }
};
SnkDynaformConfigsButton.style = snkDynaformConfigsButtonCss;

const snkDynaformFieldsLayoutCss = ".sc-snk-dynaform-fields-layout-h{display:flex;padding:12px;box-shadow:var(--shadow--small, 0 0 16px rgba(0, 38, 111, 0.07));border-radius:var(--border--radius-medium, 6px);height:var(--snk-form-config-container-height);flex-direction:column}.layout-container.sc-snk-dynaform-fields-layout{container-type:inline-size;display:flex;flex-direction:column;overflow:auto;height:calc(100vh - 225px)}.guide-header.sc-snk-dynaform-fields-layout{display:flex;width:100%;font-size:20px;border-bottom:1px solid #dce0e8;margin-bottom:6px;align-items:center;height:45px}.guide-header.sc-snk-dynaform-fields-layout ez-button.sc-snk-dynaform-fields-layout{transition:all 0.2s ease-in-out;visibility:hidden;opacity:0}.guide-header.sc-snk-dynaform-fields-layout:hover ez-button.sc-snk-dynaform-fields-layout{visibility:visible;opacity:1}.guide-header-label.sc-snk-dynaform-fields-layout{display:block;padding:10px 0}.group-config.sc-snk-dynaform-fields-layout{padding:12px 0;display:flex;flex-direction:column;width:100%}.group-content.sc-snk-dynaform-fields-layout{display:grid;gap:12px;min-height:65px;width:100%;padding:6px 0;grid-template-columns:repeat(auto-fill, minmax(250px, 1fr))}.group-content.empty-content.sc-snk-dynaform-fields-layout{position:relative}.group-content.empty-content.sc-snk-dynaform-fields-layout::before{content:var(--empty-content-message, \"Arraste e solte um campo aqui\");color:#cbcfd7;font-size:16px;font-weight:500;text-align:center;position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;transition:opacity 0.3s;height:100%;box-sizing:border-box;padding:10px;background:#f9f9f9;border:1px dashed #dce0e8;border-radius:6px}.no-group-container.sc-snk-dynaform-fields-layout{padding:12px 0;width:100%;border-bottom:1px solid #dce0e8}.no-group-container.sc-snk-dynaform-fields-layout::before{content:var(--no-group-message, \"Inclua estes campos nos grupos ou deixe-os separados no topo do formulário\");width:100%;display:block;font-size:16px;font-weight:400;color:#AFB6C0;padding-bottom:12px}.add-group-container.sc-snk-dynaform-fields-layout{display:flex;align-items:center;border-top:1px solid #dce0e8;padding-top:22px;padding-bottom:12px;gap:6px;cursor:pointer;justify-content:center;width:100%;height:55px}.no-guide-selected.sc-snk-dynaform-fields-layout{display:block;margin:auto;font-size:24px;color:#AFB6C0;font-weight:500}.message-container.sc-snk-dynaform-fields-layout{margin:auto;display:flex;flex-direction:column;justify-content:center;align-items:center}.message-config-detail.sc-snk-dynaform-fields-layout{display:block;margin:auto;font-size:var(--font-size--medium, 16px);color:#AFB6C0;font-weight:var(--font-weight--medium, 500)}.ghost.sc-snk-dynaform-fields-layout{opacity:.5;background:#c8fbe2}";

const SnkDynaformFieldsLayout = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.isEditingGuideName = index.createEvent(this, "isEditingGuideName", 7);
    this.isEditingGroupName = index.createEvent(this, "isEditingGroupName", 7);
    this.layoutChanged = index.createEvent(this, "layoutChanged", 7);
    this.setFieldListAsAvailable = index.createEvent(this, "setFieldListAsAvailable", 7);
    this.guideRenamed = index.createEvent(this, "guideRenamed", 7);
    this.ID_GROUPS = 'container-groups';
    this.ID_FIELDS = 'container-fields';
    this.reservedGuideNames = [constants.TAB_NAMES.main.toLowerCase(), constants.TAB_NAMES.general.toLocaleLowerCase()];
    this.groupsListMemory = [];
    this.groupsRefList = [];
    this.isEditGuideNameActive = false;
    this.selectedGuide = undefined;
    this.groupsList = [];
    this.guideNames = [];
    this.dataUnit = undefined;
    this.messagesBuilder = undefined;
  }
  onMessagesBuilderChange() {
    this.setCustomCSSProperties();
  }
  handleFieldConfigChanged({ detail: updatedField }) {
    const groupToUpdate = this.groupsListMemory.find(g => g.name === updatedField.group);
    if (!groupToUpdate)
      return;
    const updatedFields = groupToUpdate.fields.map(field => {
      return (field.name === updatedField.name) ? updatedField : field;
    });
    const updatedGroupList = this.groupsListMemory.map(group => {
      return (group.name === groupToUpdate.name)
        ? { name: group.name, fields: updatedFields }
        : group;
    });
    this.applyGroupUpdate(updatedGroupList);
  }
  observeSelectedGuide() {
    this.isEditGuideNameActive = false;
    index.forceUpdate(this);
    this.isEditingGroupName.emit(false);
  }
  observeGroupList(newValue) {
    this.groupsListMemory = [...newValue];
  }
  observeIsEditGuideNameActive(newValue) {
    this.isEditingGuideName.emit(newValue);
  }
  async addFieldToLayout(incomingField) {
    incomingField.group = constants.GROUP_NAMES.noGroup;
    incomingField.tab = this.selectedGuide.name;
    const fixedFieldsGroup = this.getFixedFieldsGroup();
    const newFixedFieldsGroup = {
      name: constants.GROUP_NAMES.noGroup,
      fields: fixedFieldsGroup ? [...fixedFieldsGroup.fields, incomingField] : [incomingField],
    };
    const updatedGroupListMemory = fixedFieldsGroup
      ? [newFixedFieldsGroup, ...this.groupsListMemory.slice(1)]
      : [newFixedFieldsGroup, ...this.groupsListMemory];
    this.applyGroupUpdate(updatedGroupListMemory);
  }
  getFixedFieldsGroup() {
    return this.groupsListMemory.find(g => g.name === constants.GROUP_NAMES.noGroup);
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  handleAddGroup() {
    const newGroup = { name: this.buildNewGroupName(), fields: [] };
    const updatedGroupsList = [...this.groupsListMemory, newGroup];
    this.applyGroupUpdate(updatedGroupsList);
  }
  buildNewGroupName() {
    var _a, _b;
    const newGroupMessage = this.getMessage('snkFormConfig.form.newGroup');
    const qtdWithNewGroupName = (_b = (_a = this.groupsListMemory.filter(g => g.name.includes(newGroupMessage))) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
    return qtdWithNewGroupName === 0 ? newGroupMessage : `${newGroupMessage} (${qtdWithNewGroupName})`;
  }
  makeDynamicFieldsContainersDraggable() {
    const draggableGroups = this.groupsList.filter((g) => g.name !== constants.GROUP_NAMES.noGroup);
    draggableGroups.forEach(group => {
      this.makeFieldContainerDraggable(this.getFieldsContainerId(group.name));
    });
  }
  getFieldsContainerId(groupName) {
    return `${this.ID_FIELDS}-${core.StringUtils.replaceBlankCharacters(groupName)}`;
  }
  handleSortGroups(evt) {
    var _a;
    const htmlStructure = (_a = evt.to) === null || _a === void 0 ? void 0 : _a.children;
    if (!htmlStructure)
      return;
    const groupsOrder = Array.from(htmlStructure).map(el => el.getAttribute('data-group-name'));
    const updatedOrderGroupsList = [];
    const fixedGroup = this.getFixedFieldsGroup();
    if (fixedGroup) {
      updatedOrderGroupsList.push(fixedGroup);
    }
    groupsOrder.forEach(groupName => {
      const group = this.groupsListMemory.find(g => g.name === groupName);
      if (group) {
        updatedOrderGroupsList.push(group);
      }
    });
    this.applyGroupUpdate(updatedOrderGroupsList);
  }
  handleFieldsChanged(evt) {
    let updatedGroupsList = [...this.groupsListMemory];
    updatedGroupsList = [...this.handleFieldsOnGroupUpdate(updatedGroupsList, evt, FormConfigHelper.SORTABLE_PATH.FROM)];
    updatedGroupsList = [...this.handleFieldsOnGroupUpdate(updatedGroupsList, evt, FormConfigHelper.SORTABLE_PATH.TO)];
    this.applyGroupUpdate(updatedGroupsList);
  }
  applyGroupUpdate(updatedGroupList) {
    var _a;
    (_a = this.groupsRefList) === null || _a === void 0 ? void 0 : _a.forEach((group) => group === null || group === void 0 ? void 0 : group.cancelEdition());
    if (core.ObjectUtils.equals(updatedGroupList, this.groupsListMemory)) {
      return false;
    }
    this.groupsListMemory = [...updatedGroupList];
    this.layoutChanged.emit(this.groupsListMemory);
    return true;
  }
  handleFieldsOnGroupUpdate(groupList, evt, path) {
    const element = evt[path];
    const isAvailableFields = element.id === FormConfigHelper.ID_AVAILABLE_FIELDS;
    return isAvailableFields ? groupList : this.updateGroupList(groupList, element, path, evt);
  }
  updateGroupList(groupList, element, path, evt) {
    const groupName = element.getAttribute('data-group-name');
    const updatedGroup = {
      name: groupName,
      fields: FormConfigHelper.getFieldsStructure(evt, path, groupName, this.selectedGuide.name),
    };
    return this.replaceGroup(groupList, updatedGroup);
  }
  replaceGroup(groupList, newGroup) {
    return groupList.map(group => group.name === newGroup.name ? newGroup : group);
  }
  makeGroupsDraggable() {
    try {
      const element = this.getContainerElement(this.ID_GROUPS);
      if (!element)
        return;
      new sortable_esm.Sortable(element, {
        group: 'groups',
        ghostClass: 'ghost',
        direction: 'horizontal',
        animation: 15,
        onSort: (evt) => this.handleSortGroups(evt),
      });
    }
    catch (e) {
      console.error(this.getMessage('snkFormConfig.errors.failMakeGroupsDraggable'), this.ID_GROUPS);
    }
  }
  makeFieldContainerDraggable(containerId) {
    try {
      const element = this.getContainerElement(containerId);
      if (!element)
        return;
      new sortable_esm.Sortable(element, {
        group: 'fields',
        ghostClass: 'ghost',
        direction: 'vertical',
        animation: 15,
        onAdd: (evt) => this.handleFieldsChanged(evt),
        onRemove: (evt) => this.handleFieldsChanged(evt),
        onSort: (evt) => this.handleFieldsChanged(evt),
      });
    }
    catch (e) {
      console.error(this.getMessage('snkFormConfig.errors.failMakeFieldContainerDraggable'), containerId);
    }
  }
  getContainerElement(id) {
    return this.el.querySelector(`[id="${id}"]`);
  }
  handleSetFieldAsAvailable(field) {
    var _a;
    const groupName = (_a = field.group) !== null && _a !== void 0 ? _a : constants.GROUP_NAMES.noGroup;
    const group = this.groupsListMemory.find(group => group.name === groupName);
    const fields = group.fields.filter(f => f.name !== field.name);
    const updatedGroup = { name: groupName, fields };
    const updatedList = [...this.replaceGroup(this.groupsListMemory, updatedGroup)];
    this.applyGroupUpdate(updatedList);
  }
  removeGroup(group) {
    var _a, _b;
    const groupFields = (_b = (_a = this.groupsListMemory.find(f => f.name === group.name)) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : [];
    const updatedGroupList = [...this.groupsListMemory.filter(g => g.name !== group.name)];
    if (this.applyGroupUpdate(updatedGroupList)) {
      this.setFieldListAsAvailable.emit(groupFields);
    }
  }
  handleRenameGroup(editDetails) {
    const { value: actualName, newValue: newGroupName } = editDetails.detail;
    const updatedGroupList = this.groupsListMemory.map(group => {
      if (group.name !== actualName)
        return Object.assign({}, group);
      const updatedFields = group.fields.map(f => {
        return Object.assign(Object.assign({}, f), { group: newGroupName });
      });
      return { name: newGroupName, fields: updatedFields };
    });
    this.applyGroupUpdate(updatedGroupList);
  }
  canSaveGroup(newLabel, index) {
    const hasOtherWithThisName = this.groupsList.some(group => {
      var _a;
      return ((_a = group.name) !== null && _a !== void 0 ? _a : '').toLocaleLowerCase() === (newLabel !== null && newLabel !== void 0 ? newLabel : '').toLocaleLowerCase();
    });
    if (!hasOtherWithThisName)
      return true;
    const title = this.getMessage('snkFormConfig.confirm.title');
    const message = this.buildDuplicatedGroupNameContent(newLabel);
    utils.ApplicationUtils.alert(title, message).then(() => { var _a; return (_a = this.groupsRefList[index]) === null || _a === void 0 ? void 0 : _a.applyFocusTextEdit(); });
    return false;
  }
  buildDuplicatedGroupNameContent(newLabel) {
    const tabName = this.selectedGuide.name;
    return `
        ${this.getMessage('snkFormConfig.alert.titleGroupExists')}
        <b>${newLabel}</b>
        ${this.getMessage('snkFormConfig.alert.inTab')}
        <b>${tabName === constants.TAB_NAMES.main ? this.getMessage('snkFormConfig.form.mainArea') : tabName}</b>.
        <br/><br/>
        ${this.getMessage('snkFormConfig.alert.infoValidTitle')}
      `;
  }
  buildDuplicatedTabNameContent(newLabel) {
    return `
        ${this.getMessage('snkFormConfig.alert.titleGuideExists')}
        <b>${newLabel}</b>.
        <br/><br/>
        ${this.getMessage('snkFormConfig.alert.infoValidTitle')}
      `;
  }
  buildReservedTabNameContent(newLabel) {
    return `
        ${this.getMessage('snkFormConfig.alert.titleGuideReservedName')}
        <br/><br/>
        <b>${newLabel}</b>.
        <br/><br/>
        ${this.getMessage('snkFormConfig.alert.infoValidTitle')}
      `;
  }
  renderFields(fields) {
    if (fields.length === 0)
      return;
    return fields.map(field => (index.h("snk-dynaform-field-item", { key: field.name, fieldConfig: field, onLayoutConfig: true, dataUnit: this.dataUnit, messagesBuilder: this.messagesBuilder, onSetFieldAsAvailable: (e) => this.handleSetFieldAsAvailable(e.detail) })));
  }
  renderDraggableGroups() {
    const draggableGroups = this.groupsList.filter(g => g.name !== constants.GROUP_NAMES.noGroup);
    return (draggableGroups.map((group, index$1) => {
      var _a;
      return (index.h("div", { key: group.name, class: 'group-config', "data-group-name": group.name }, index.h("ez-collapsible-box", { ref: ref => this.groupsRefList[index$1] = ref, label: group.name, headerSize: "large", editable: true, removable: true, "icon-placement": "left", onEzRemove: () => this.removeGroup(group), onEzSaveEditLabel: (event => this.handleRenameGroup(event)), onEzEditLabelMode: ({ detail }) => this.isEditingGroupName.emit(detail), conditionalSave: (newLabel) => this.canSaveGroup(newLabel, index$1) }, index.h("div", { id: this.getFieldsContainerId(group.name), class: `group-content ${!((_a = group.fields) === null || _a === void 0 ? void 0 : _a.length) ? 'empty-content' : ''}`, "data-group-name": group.name }, this.renderFields(group.fields)))));
    }));
  }
  renderFixedFields() {
    var _a, _b;
    const noGroupFields = (_b = (_a = this.groupsList.find(g => g.name === constants.GROUP_NAMES.noGroup)) === null || _a === void 0 ? void 0 : _a.fields) !== null && _b !== void 0 ? _b : [];
    return this.renderFields(noGroupFields);
  }
  handleRenameGuide(editDetails) {
    const { value: actualValue, newValue } = editDetails.detail;
    this.isEditGuideNameActive = false;
    if (newValue === actualValue) {
      return;
    }
    const duplicatedName = this.guideNames.includes(newValue.toLowerCase());
    const forbiddenName = this.reservedGuideNames.includes(newValue.toLowerCase());
    if (forbiddenName || duplicatedName) {
      const title = this.getMessage('snkFormConfig.confirm.title');
      const message = forbiddenName ? this.buildReservedTabNameContent(newValue) : this.buildDuplicatedTabNameContent(newValue);
      utils.ApplicationUtils.alert(title, message).then(() => this._refTextEdit.applyFocusSelect());
      return;
    }
    this.guideRenamed.emit(newValue);
  }
  cancelEditGuideName() {
    this.isEditGuideNameActive = false;
  }
  async startGuideNameEdition() {
    this.isEditGuideNameActive = true;
    setTimeout(async () => {
      await this._refTextEdit.applyFocusSelect();
    }, 200);
  }
  getTextEditStyle() {
    return {
      fontSize: '20px',
      fontWeight: '500',
      fontFamily: 'Roboto',
    };
  }
  renderGuideName() {
    var _a, _b;
    if (this.isEditGuideNameActive) {
      return (index.h("div", { class: 'guide-header' }, index.h("ez-text-edit", { class: "collapsible-box__text-edit", ref: ref => this._refTextEdit = ref, value: (_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.label, styled: this.getTextEditStyle(), onSaveEdition: (ev) => this.handleRenameGuide(ev), onCancelEdition: () => this.cancelEditGuideName() })));
    }
    return (index.h("div", { class: 'guide-header' }, index.h("span", { class: 'guide-header-label' }, (_b = this.selectedGuide) === null || _b === void 0 ? void 0 : _b.label), this.renderEditGuideNameButton()));
  }
  renderEditGuideNameButton() {
    var _a;
    if (((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name) === constants.TAB_NAMES.main)
      return;
    return (index.h("ez-button", { mode: "icon", class: "ez-button--tertiary", onClick: () => this.startGuideNameEdition(), size: "medium", iconName: 'edit', title: this.getMessage('snkFormConfig.buttons.rename') }));
  }
  setCustomCSSProperties() {
    document.documentElement.style.setProperty('--empty-content-message', `"${this.getMessage('snkFormConfig.form.labelDropField')}"`);
    document.documentElement.style.setProperty('--no-group-message', `"${this.getMessage('snkFormConfig.form.subTitleInfo')}"`);
  }
  componentDidRender() {
    this.makeGroupsDraggable();
    this.makeDynamicFieldsContainersDraggable();
    this.makeFieldContainerDraggable(constants.GROUP_NAMES.noGroup);
    this.setCustomCSSProperties();
  }
  render() {
    if (!this.selectedGuide) {
      return (index.h(index.Host, { class: 'ez-flex-item--auto ez-size-height--full ez-box ez-padding--medium content-container' }, index.h("span", { class: 'no-guide-selected' }, this.getMessage('snkFormConfig.form.noGuideSelected'))));
    }
    if (this.selectedGuide.isCustom || this.selectedGuide.isDetail) {
      return (index.h(index.Host, { class: 'ez-flex-item--auto ez-size-height--full ez-box ez-padding--medium content-container' }, index.h("div", { class: 'message-container' }, index.h("h1", { class: 'no-guide-selected' }, this.getMessage('snkFormConfig.form.canNotEditCustomGuide')), index.h("span", { class: 'message-config-detail' }, this.getMessage('snkFormConfig.form.canNotEditDetailGuide')))));
    }
    return (index.h(index.Host, { class: 'ez-flex-item--auto ez-size-height--full ez-box ez-padding--medium content-container' }, this.renderGuideName(), index.h("div", { class: 'layout-container' }, index.h("ez-scroller", { direction: 'vertical', activeShadow: true }, index.h("div", { class: 'no-group-container' }, index.h("div", { id: constants.GROUP_NAMES.noGroup, class: 'group-content', "data-group-name": constants.GROUP_NAMES.noGroup }, this.renderFixedFields())), index.h("hr", null), index.h("div", { id: this.ID_GROUPS, class: 'groups-container' }, this.renderDraggableGroups()))), index.h("div", { class: 'add-group-container', onClick: this.handleAddGroup.bind(this) }, index.h("ez-icon", { slot: "leftIcon", iconName: "plus" }), index.h("span", null, this.getMessage('snkFormConfig.form.createNewGroup')))));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "messagesBuilder": ["onMessagesBuilderChange"],
    "selectedGuide": ["observeSelectedGuide"],
    "groupsList": ["observeGroupList"],
    "isEditGuideNameActive": ["observeIsEditGuideNameActive"]
  }; }
};
SnkDynaformFieldsLayout.style = snkDynaformFieldsLayoutCss;

const snkDynaformFieldsSelectorCss = ".sc-snk-dynaform-fields-selector-h{width:33.33333%;display:flex;box-shadow:var(--shadow--small, 0 0 16px rgba(0, 38, 111, 0.07));border-radius:var(--border--radius-medium, 6px);height:var(--snk-form-config-container-height);max-width:260px}.fields-label.sc-snk-dynaform-fields-selector{display:block;font-size:16px;font-weight:500;width:100%}.fields-count.sc-snk-dynaform-fields-selector{display:block;color:#AFB6C0;font-size:14px;padding:12px 0;font-weight:400;width:100%}.fields-container.sc-snk-dynaform-fields-selector{display:flex;flex-direction:column;gap:12px;height:calc(100vh - 220px);width:100%}.ghost.sc-snk-dynaform-fields-selector{opacity:.5;background:#c8fbe2}.filter-input.sc-snk-dynaform-fields-selector{padding-right:var(--space--2xs, 8px)}";

const SnkDynaformFieldsSelector = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.fieldListChanged = index.createEvent(this, "fieldListChanged", 7);
    this.availableFields = [];
    this.dataUnit = undefined;
    this.filterTerm = '';
    this.messagesBuilder = undefined;
  }
  onAddField(evt) {
    const newIndex = evt.newIndex;
    const item = evt.item;
    const fieldConfig = item.fieldConfig;
    const updatedFields = this.addItemInPosition(newIndex, fieldConfig);
    this.fieldListChanged.emit(updatedFields);
  }
  addItemInPosition(newIndex, fieldConfig) {
    return [
      ...this.availableFields.slice(0, newIndex),
      fieldConfig,
      ...this.availableFields.slice(newIndex),
    ];
  }
  onRemoveField(evt) {
    const item = evt.item;
    const fieldName = item.fieldConfig.name;
    const updatedFields = [...this.availableFields.filter(f => f.name !== fieldName)];
    this.fieldListChanged.emit(updatedFields);
    requestAnimationFrame(() => item.remove());
    return;
  }
  renderFields() {
    const fieldsToShow = core.ArrayUtils.applyStringFilter(this.filterTerm, this.availableFields);
    return fieldsToShow.map(field => (index.h("snk-dynaform-field-item", { key: field.name, dataUnit: this.dataUnit, fieldConfig: field, messagesBuilder: this.messagesBuilder })));
  }
  getCountText() {
    if (!this.availableFields.length)
      return this.getMessage('snkFormConfig.availableFields.labelNoFields');
    if (this.availableFields.length === 1)
      return this.getMessage('snkFormConfig.availableFields.labelOneField');
    return `${this.availableFields.length} ${this.getMessage('snkFormConfig.availableFields.labelAvailableFields')}`;
  }
  initializeDraggableContainer() {
    new sortable_esm.Sortable(this.el.querySelector(`#${FormConfigHelper.ID_AVAILABLE_FIELDS}`), {
      group: 'fields',
      direction: 'vertical',
      ghostClass: 'ghost',
      animation: 15,
      onAdd: (evt) => this.onAddField(evt),
      onRemove: (evt) => this.onRemoveField(evt),
    });
  }
  getMessage(key, params) {
    var _a;
    return (_a = this.messagesBuilder) === null || _a === void 0 ? void 0 : _a.getMessage(key, params);
  }
  componentDidRender() {
    this.initializeDraggableContainer();
  }
  render() {
    return (index.h(index.Host, { class: 'ez-col ez-col--sd-4 ez-col--tb-4 ez-padding--medium' }, index.h("span", { class: 'fields-label ez-padding-bottom--small' }, this.getMessage('snkFormConfig.availableFields.title')), index.h("ez-filter-input", { class: 'filter-input', slot: "content", mode: "slim", label: this.getMessage('snkFormConfig.availableFields.labelSearchField'), onEzChange: evt => this.filterTerm = evt.detail }), index.h("span", { class: 'fields-count' }, this.getCountText()), index.h("ez-scroller", { direction: 'vertical', activeShadow: true }, index.h("div", { id: FormConfigHelper.ID_AVAILABLE_FIELDS, class: 'fields-container' }, this.renderFields()))));
  }
  get el() { return index.getElement(this); }
};
SnkDynaformFieldsSelector.style = snkDynaformFieldsSelectorCss;

const snkDynaformGuidesConfiguratorCss = ".guides-tab-configurator.sc-snk-dynaform-guides-configurator{display:flex;flex-direction:column;width:100%;gap:var(--spece--8, 8px)}.tab-bar-row.sc-snk-dynaform-guides-configurator{display:flex;flex-direction:row;align-items:center;gap:var(--space--12, 12px);width:100%}.guides-tabselector.sc-snk-dynaform-guides-configurator{flex:1;min-width:0}.tab-actions.sc-snk-dynaform-guides-configurator{display:inline-flex;align-items:center;gap:var(--space--2, 2px);margin-left:var(--space--6, 6px)}.tab-actions.sc-snk-dynaform-guides-configurator ez-button.sc-snk-dynaform-guides-configurator{width:var(--space--20, 20px);align-items:center;justify-content:center;display:flex}.hidden-guides-bar.sc-snk-dynaform-guides-configurator{display:flex;flex-direction:row;flex-wrap:wrap;align-items:center;gap:var(--space--8, 8px);padding:var(--space--8, 8px) 0;border-top:1px solid #dce0e8}.hidden-guides-label.sc-snk-dynaform-guides-configurator{font-size:var(--space--12, 12px);color:#afb6c0;white-space:nowrap}.hidden-guide-chip.sc-snk-dynaform-guides-configurator{display:flex;align-items:center;gap:4px;padding:2px var(--space--8, 8px);border:1px solid #dce0e8;border-radius:var(--space--12, 12px);background:#f5f7fa;transition:background 0.15s ease-in-out}.hidden-guide-chip.sc-snk-dynaform-guides-configurator:hover{background:#e2eaf4}.hidden-guide-chip.sc-snk-dynaform-guides-configurator ez-button.sc-snk-dynaform-guides-configurator{width:var(--space--20, 20px);align-items:center;justify-content:center;display:flex}.chip-label.sc-snk-dynaform-guides-configurator{font-size:13px;max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}";

const SnkDynaformGuidesConfigurator = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.guideSelected = index.createEvent(this, "guideSelected", 7);
    this.guideListChanged = index.createEvent(this, "guideListChanged", 7);
    this.guideDeleted = index.createEvent(this, "guideDeleted", 7);
    this.createNewGuide = index.createEvent(this, "createNewGuide", 7);
    this.sortLogic = (a, b) => {
      var _a, _b;
      const orderA = (_a = a.order) !== null && _a !== void 0 ? _a : Number.MAX_VALUE;
      const orderB = (_b = b.order) !== null && _b !== void 0 ? _b : Number.MAX_VALUE;
      return orderA - orderB;
    };
    this.handleAddGuide = () => {
      this.createNewGuide.emit();
    };
    this.mainGuide = undefined;
    this.visibleGuides = [];
    this.hiddenGuides = [];
    this.guidesList = [];
    this.selectedGuide = undefined;
    this.messagesBuilder = undefined;
  }
  observeGuidesList(newGuides) {
    this.initGuidesConfig(newGuides);
  }
  observeSelectedGuide(newGuide) {
    this.guideSelected.emit(newGuide);
  }
  componentWillLoad() {
    this.initGuidesConfig(this.guidesList);
  }
  getMessage(key, params) {
    return this.messagesBuilder.getMessage(key, params);
  }
  initGuidesConfig(newGuides) {
    const visibleAux = newGuides.filter(guide => guide.visible && guide.name !== constants.TAB_NAMES.main);
    const hiddenAux = newGuides.filter(guide => !guide.visible && guide.name !== constants.TAB_NAMES.main);
    this.visibleGuides = [...visibleAux].sort(this.sortLogic);
    this.hiddenGuides = [...hiddenAux].sort(this.sortLogic);
    this.mainGuide = newGuides.find(g => g.name === constants.TAB_NAMES.main);
  }
  handleSelectGuide(guide, evt) {
    evt.stopPropagation();
    this.selectedGuide = guide;
  }
  toggleGuideVisibility(guide, evt) {
    evt.stopPropagation();
    const updatedGuide = Object.assign(Object.assign({}, guide), { visible: !guide.visible });
    let visibleAux;
    let hiddenAux;
    if (guide.visible) {
      visibleAux = this.visibleGuides.filter(g => g.name !== guide.name);
      hiddenAux = [...this.hiddenGuides, updatedGuide];
    }
    else {
      visibleAux = [...this.visibleGuides, updatedGuide];
      hiddenAux = this.hiddenGuides.filter(g => g.name !== guide.name);
    }
    this.applyGuidesUpdate([...visibleAux, ...hiddenAux]);
  }
  adjustListOrder(guideList) {
    return guideList.map((g, index) => (Object.assign(Object.assign({}, g), { order: index })));
  }
  applyGuidesUpdate(updatedGuideList) {
    let newGuidesList = this.adjustListOrder(updatedGuideList);
    if (this.mainGuide) {
      newGuidesList = [this.mainGuide, ...newGuidesList];
    }
    if (!core.ObjectUtils.equals(newGuidesList, this.guidesList)) {
      this.guideListChanged.emit(newGuidesList);
    }
  }
  async handleDeleteGuide(guide, e) {
    e.stopPropagation();
    const title = this.getMessage('snkFormConfig.confirm.title');
    const message = this.getMessage('snkFormConfig.confirm.deleteGuide').replace('{0}', guide.label);
    const canRemove = await utils.ApplicationUtils.confirm(title, message);
    if (!canRemove)
      return;
    this.guideDeleted.emit(guide);
    const deletedMessage = this.getMessage('snkFormConfig.info.successfullyGuideDeleted').replace('{0}', guide.label);
    utils.ApplicationUtils.info(deletedMessage);
  }
  buildTabs() {
    const tabs = [];
    if (this.mainGuide) {
      tabs.push({ tabKey: this.mainGuide.name, label: this.mainGuide.label, index: 0 });
    }
    this.visibleGuides.forEach((guide, i) => {
      tabs.push({
        tabKey: guide.name,
        label: guide.label,
        index: (this.mainGuide ? 1 : 0) + i,
      });
    });
    return tabs;
  }
  handleTabChange(tab) {
    var _a;
    if (!tab)
      return;
    const guide = this.guidesList.find(g => g.name === tab.tabKey);
    if (guide && guide.name !== ((_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name)) {
      this.selectedGuide = guide;
    }
  }
  handleReorder(reorderedTabs) {
    // __main fica fixo no índice 0; se o usuário tentou movê-lo, recolocar
    const visibleReordered = reorderedTabs
      .filter(t => { var _a; return t.tabKey !== ((_a = this.mainGuide) === null || _a === void 0 ? void 0 : _a.name); })
      .map(t => this.visibleGuides.find(g => g.name === t.tabKey))
      .filter(Boolean);
    this.applyGuidesUpdate([...visibleReordered, ...this.hiddenGuides]);
  }
  renderTabActions() {
    return this.visibleGuides.map((guide, i) => {
      const slotIndex = (this.mainGuide ? 1 : 0) + i;
      const isProtected = guide.isCustom || guide.isDetail;
      return (index.h("div", { key: guide.name, slot: `tab${slotIndex}`, class: "tab-actions", onClick: (e) => e.stopPropagation() }, index.h("ez-button", { mode: "icon", class: "ez-button--tertiary tab-action-btn", size: "small", iconName: "eye-off", title: this.getMessage('snkFormConfig.guidesConfigurator.actions.hide'), onClick: (e) => this.toggleGuideVisibility(guide, e) }), index.h("ez-button", { mode: "icon", class: "ez-button--tertiary tab-action-btn", size: "small", iconName: "delete", isDisabled: isProtected, title: isProtected
          ? this.getMessage('snkFormConfig.guidesConfigurator.canNotDeleteCustomGuide')
          : this.getMessage('snkFormConfig.guidesConfigurator.actions.delete'), onClick: (e) => this.handleDeleteGuide(guide, e) })));
    });
  }
  renderHiddenGuidesBar() {
    if (this.hiddenGuides.length === 0)
      return null;
    return (index.h("div", { class: "hidden-guides-bar" }, index.h("span", { class: "hidden-guides-label" }, this.getMessage('snkFormConfig.guidesConfigurator.hiddenGuides'), ":"), this.hiddenGuides.map(guide => {
      const isProtected = guide.isCustom || guide.isDetail;
      return (index.h("div", { key: guide.name, class: "hidden-guide-chip", title: guide.label }, index.h("span", { class: "chip-label", onClick: (e) => this.handleSelectGuide(guide, e) }, guide.label), index.h("ez-button", { mode: "icon", class: "ez-button--tertiary", size: "small", iconName: "eye", title: this.getMessage('snkFormConfig.guidesConfigurator.actions.show'), onClick: (e) => this.toggleGuideVisibility(guide, e) }), index.h("ez-button", { mode: "icon", class: "ez-button--tertiary", size: "small", iconName: "delete", isDisabled: isProtected, title: isProtected
          ? this.getMessage('snkFormConfig.guidesConfigurator.canNotDeleteCustomGuide')
          : this.getMessage('snkFormConfig.guidesConfigurator.actions.delete'), onClick: (e) => this.handleDeleteGuide(guide, e) })));
    })));
  }
  render() {
    var _a;
    const tabs = this.buildTabs();
    return (index.h("div", { class: "guides-tab-configurator" }, index.h("div", { class: "tab-bar-row" }, index.h("ez-tabselector", { class: "guides-tabselector", tabs: tabs, selectedTab: (_a = this.selectedGuide) === null || _a === void 0 ? void 0 : _a.name, reorderable: true, onEzChange: (evt) => this.handleTabChange(evt.detail), onEzReorder: (evt) => this.handleReorder(evt.detail) }, this.renderTabActions()), index.h("ez-button", { label: this.getMessage('snkFormConfig.guidesConfigurator.createNewGuide'), variant: "secondary", size: "medium", leftIconName: "plus", onClick: this.handleAddGuide })), this.renderHiddenGuidesBar()));
  }
  static get watchers() { return {
    "guidesList": ["observeGuidesList"],
    "selectedGuide": ["observeSelectedGuide"]
  }; }
};
SnkDynaformGuidesConfigurator.style = snkDynaformGuidesConfiguratorCss;

exports.snk_dynaform_config_header = SnkDynaformConfigHeader;
exports.snk_dynaform_configs_button = SnkDynaformConfigsButton;
exports.snk_dynaform_fields_layout = SnkDynaformFieldsLayout;
exports.snk_dynaform_fields_selector = SnkDynaformFieldsSelector;
exports.snk_dynaform_guides_configurator = SnkDynaformGuidesConfigurator;
