import { r as registerInstance, h, H as Host } from './index-b7735e0d.js';
import { i as injectNotifier } from './index-94b34cb1.js';
import './apiBase-d573f009.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { c as createMentornityApiInstance, F as FormStatus } from './instance-7b02ef1d.js';
import { m as mentornityApiEndpoint } from './env-4ec3c807.js';
import { g as getSessionDetails } from './session-b16a440c.js';
import './state-tunnel-04c0b67a.js';
import './BaseField-461b6d0c.js';
import './FieldModelGenerator-020f4a04.js';
import './reference-field-0e7cd534.js';
import './index-7b119e61.js';
import './index-403101cb.js';
import './date-ce777316.js';
import './index-1d3efe49.js';
import './index-eb14fd2d.js';
import './index-80ec23ef.js';
import './index-4c39b6a6.js';
import './membership-e92743d1.js';
import './data-model-f7ccf826.js';
import './table-config-0c06fb1f.js';
import './string-3065a411.js';
import './User-1ef5a482.js';
import './UserSettings-27df01e6.js';
import './cookie-1686830b.js';
import './kimlikApi-0d7e6ce7.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';

const mentornityMembershipApplicationSettingsWrapperCss = "mentornity-membership-application-settings-wrapper{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;overflow:hidden;height:100%}mentornity-membership-application-settings-wrapper .columns-container{height:100%}mentornity-membership-application-settings-wrapper .columns-container .controls-container{-ms-flex:3;flex:3}mentornity-membership-application-settings-wrapper .columns-container .controls-container .form-controls-container{background:var(--color-elevated-item-background);-ms-flex:1;flex:1;overflow:auto}mentornity-membership-application-settings-wrapper .columns-container .controls-container .controls-footer{background:var(--color-background-secondary);text-align:right}mentornity-membership-application-settings-wrapper .columns-container .controls-container .controls-footer dvn-button{vertical-align:bottom}mentornity-membership-application-settings-wrapper .columns-container .preview-container{-ms-flex:5;flex:5;height:100%;overflow:auto}";

// removes the HTML entities like &nbsp; from the input
const htmlDecode = (input) => new DOMParser().parseFromString(input, 'text/html').documentElement.textContent;
function getFormDataForCreation(organisationId, formTarget) {
  return {
    title: 'Application Form',
    description: 'Application form for new members.',
    target: formTarget,
    type: 'application',
    form: {
      'fields': [],
      'version': 0.1
    },
    organisation: {
      '_id': organisationId,
      '_class': 'organisations',
      '_type': 'reference'
    },
    status: FormStatus.Unpublished,
  };
}
let MentornityMembershipApplicationSettingsWrapper = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.step = 'description';
    this.editorValue = [
      {
        type: 'h3',
        id: 'form-title',
        value: {
          placeholder: 'Form title',
          text: '',
        },
      },
      {
        type: 'text',
        id: 'form-content',
        value: {
          placeholder: 'Form description',
          text: '',
        },
      },
    ];
    this.setApplicationForm = (form) => {
      this.applicationForm = form;
      // @ts-ignore
      this.applicationForm.description = new showdown.Converter().makeHtml(form.description);
      const editorValue = JSON.parse(JSON.stringify(this.editorValue));
      editorValue[0].value.text = this.applicationForm.title;
      editorValue[1].value.text = this.applicationForm.description;
      this.editorValue = editorValue;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail.filter(f => !['email', 'firstName', 'lastName'].includes(f));
      const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
      applicationForm.form.fields = selectedFields.map(sfid => this.availableFields.find(af => af.id === sfid));
      this.applicationForm = applicationForm;
    };
    this.getApplicationLink = () => {
      const { organisationDomain, wlDomain } = this;
      const domain = wlDomain || 'mentornity.com';
      const rootUrl = `https://${domain}/${organisationDomain}/`;
      return this.formTarget === 'mentee' ? `${rootUrl}/mentees/application` : `${rootUrl}/mentors/application`;
    };
    this.onClickSaveChanges = () => {
      const { status, form: { fields: applicationFormFields }, title, description } = this.applicationForm;
      const fields = applicationFormFields.map(f => ({ id: f.id }));
      const data = { form: { fields }, status, title, description };
      this.api.update('forms', this.applicationForm._id, data)
        .then(() => this.notifier.congratulate('Changes are saved.'))
        .catch(() => this.notifier.alert('Saving changes failed.'));
    };
  }
  async componentWillLoad() {
    const { formTarget, organisationId } = this;
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = config.metadatas[formTarget];
    const collection = formTarget === 'mentor' ? 'mentors' : 'mentees';
    this.api.getMembershipApplicationForm(organisationId, collection)
      .then(form => this.setApplicationForm(form))
      .catch(error => {
      if (error.status === 404) {
        const formData = getFormDataForCreation(organisationId, formTarget);
        this.api.createForm(formData)
          .then(createFormResponse => this.setApplicationForm(Object.assign(Object.assign({}, formData), createFormResponse)))
          .catch(error => this.error = error);
      }
      else {
        this.error = error;
      }
    });
  }
  render() {
    const { applicationForm, availableFields, organisationConfig, organisationId, step, } = this;
    if (!organisationConfig || !applicationForm) {
      return (h("div", { class: "d-flex justify-content-center pt-3" }, h("dvn-progress", { indefinite: true })));
    }
    const selectedFields = ['firstName', 'lastName', 'email', ...applicationForm.form.fields.map(field => field.id)];
    const options = [
      { label: 'First name', value: 'firstName', disabled: true },
      { label: 'Last name', value: 'lastName', disabled: true },
      { label: 'Email', value: 'email', disabled: true },
      ...(availableFields).map(field => ({
        label: field.title,
        value: field.id,
      }))
    ];
    return (h(Host, null, h("mentornity-root-wrapper", null, h("div", { class: "columns-container d-flex" }, h("div", { class: "controls-container d-flex flex-column" }, h("div", { class: "form-controls-container" }, h("div", { class: "d-flex flex-column p-3" }, h("dvn-alert", { message: "The preview on the right will be updated when there is a change on the controls." }), h("dvn-card", { outlined: true, reverseTint: true, leaned: true }, h("div", { class: "d-flex align-items-center" }, h("dvn-switch", { scale: "small", shape: "rounded", checked: applicationForm.status === 'published', onChange: () => {
        const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
        applicationForm.status = applicationForm.status === 'published' ? 'unpublished' : 'published';
        this.applicationForm = applicationForm;
      } }), h("div", { class: "ml-3" }, applicationForm.status === 'published'
      ? h("span", null, "Applications are open and accessible ", h("a", { href: this.getApplicationLink(), target: "_blank" }, "on this URL"), ".")
      : 'Applications are closed.'))), h("div", { class: "mt-3" }, h("dvn-content-switcher", { options: [
        {
          label: 'Description',
          value: 'description',
        },
        {
          label: 'Fields',
          value: 'fields',
        },
      ], onChange: e => this.step = e.detail, value: step, shape: "rounded", leaned: true })), step === 'description' &&
      h("div", { class: "ml-2 mr-2" }, h("dvn-rich-editor", { key: "editor", onChange: (e) => {
          var _a, _b;
          const editorValue = e.detail;
          const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
          applicationForm.title = htmlDecode((_a = editorValue[0]) === null || _a === void 0 ? void 0 : _a.value.text);
          applicationForm.description = (_b = editorValue[1]) === null || _b === void 0 ? void 0 : _b.value.text;
          this.applicationForm = applicationForm;
          this.editorValue = editorValue;
        }, editorSettings: {
          enableDrag: false,
          enableBlockCreation: false,
          enableBlockDeletion: false,
          hideDragControls: true,
          blockTypes: [],
          blockSettings: {
            text: {
              textSelectionOptions: ['bold', 'link']
            }
          }
        }, value: this.editorValue })), step === 'fields' &&
      h("div", { class: "mt-3" }, h("dvn-checkbox-group", { options: options, value: selectedFields, onChange: this.onSelectedFieldsChange })))), h("div", { class: "controls-footer p-3" }, h("dvn-button", { leaned: true, tint: "primary", onClick: this.onClickSaveChanges }, "Save Changes"))), h("div", { class: "preview-container d-flex justify-content-center" }, h("mentornity-membership-application-wrapper", { formFromEditor: applicationForm, configFromEditor: organisationConfig, formTarget: this.formTarget, organisationId: organisationId, onAction: () => this.notifier.warn('Action unavailable in preview.', 'Preview Mode') }))))));
  }
};
injectNotifier(MentornityMembershipApplicationSettingsWrapper);
MentornityMembershipApplicationSettingsWrapper.style = mentornityMembershipApplicationSettingsWrapperCss;

export { MentornityMembershipApplicationSettingsWrapper as mentornity_membership_application_settings_wrapper };
