import { r as registerInstance, h } from './index-55faf181.js';
import { D as DataModel } from './data-model-f5160369.js';
import './kimlikApi-7350588e.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { b as MentornityViewConfigViewName, e as InfoVisibility, c as createMentornityApiInstance, f as Config } from './instance-46ab1e99.js';
import { b as commonUserInfoFields, M as MentornityBridgeApi } from './mentorinty-bridge-api-946adc0d.js';
import { g as getSessionDetails, m as mentornityApiEndpoint } from './session-3ec0aa4c.js';
import { d as decodeFields, T as TableConfig } from './table-config-5c917348.js';
import { D as DetailViewConfig } from './detail-view-config-dafcc086.js';
import { A as AtamaMemberPairsOverviewViewConfig } from './atama-member-pairs-overview-view-config-1941a8d2.js';
import { p as pairConfig } from './pair-config-0a081c6a.js';
import { b as getPairConfigOptionsFromOrganisationConfig, g as getViewConfigForViewName, a as getAvailableMetadataFields, c as convertFieldsToFieldReferences } from './common-wrapper-util-36df331f.js';
import './BaseField-461b6d0c.js';
import './FieldModelGenerator-1ee7fda2.js';
import './index-6a1cf9c1.js';
import './index-403e215e.js';
import './date-ce777316.js';
import './index-083a6906.js';
import './index-fa1db470.js';
import './index-ebde6a66.js';
import './attachment-32decf79.js';
import './membership-61c4a2f7.js';
import './membership-config-a51a5232.js';
import './string-3065a411.js';
import './User-d2ee8b71.js';
import './CalendarConfig-184230a0.js';
import './UserSettings-7b80b841.js';
import './cookie-93ea205f.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './view-config-39fd369a.js';
import './pair-config-e51ec0c7.js';

const en = {
  view: {
    accept: 'Accept',
    fetchConfigurationError: 'Getting configuration failed.',
    fetchListError: 'Fetching list failed.',
    noPairsMessage: 'You don\'t have any pairs.',
    noReceivedRequests: 'There are no pending requests.',
    pairs: 'Pairs',
    receivedRequests: 'Received Requests',
    reject: 'Reject',
    selectionCardActionTint: 'secondary',
    selectionCardActionLabel: 'Go to selection page',
    selectionCardMessage: 'You can view all available users and send them requests.',
    selectionCardTint: 'primary',
    selectionCardTitle: 'Selection is on!',
    sentOnDateFormat: 'DD MMM YYYY, HH:mm',
    statusLabels: {
      accepted: 'Accepted',
      canceled: 'Canceled',
      completed: 'Completed',
      rejected: 'Rejected',
      requested: 'Requested',
    },
    viewAndMeet: 'View & Meet',
  },
};
const tr = {
  view: {
    accept: 'Kabul Et',
    fetchConfigurationError: 'Ayarlar alınırken hata oluştu.',
    fetchListError: 'Seçim listesi alınırken hata oluştu.',
    noPairsMessage: 'Eşleştiğiniz kimse yok.',
    noReceivedRequests: 'Onay bekleyen istek yok.',
    pairs: 'Eşleşmeler',
    receivedRequests: 'Alınan İstekler',
    reject: 'Reddet',
    selectionCardActionTint: 'secondary',
    selectionCardActionLabel: 'Seçim sayfasına git',
    selectionCardMessage: 'Müsait olan tüm kullanıcıları görüp onlara istek gönderebilirsiniz.',
    selectionCardTint: 'primary',
    selectionCardTitle: 'Seçim başladı!',
    sentOnDateFormat: 'DD MMM YYYY, HH:mm',
    statusLabels: {
      accepted: 'Onaylandı',
      canceled: 'Reddedildi',
      completed: 'Sonlandırıldı',
      rejected: 'Reddedildi',
      requested: 'Gönderildi',
    },
    viewAndMeet: 'Detay & Toplantılar',
  },
};

function getPairOverviewParameters(mentornityCookieContext) {
  const { role } = mentornityCookieContext;
  // if user is mentor, then the view config should say that the 'subscribed' is viewing the 'subscriber'
  // if user is mentee, then it should say otherwise
  const userRefFieldIdValue = role === 'mentor' ? 'subscribed' : 'subscriber';
  const memberToViewRefFieldIdValue = role === 'mentor' ? 'subscriber' : 'subscribed';
  return {
    memberToViewRefFieldId: memberToViewRefFieldIdValue,
    userRefFieldId: userRefFieldIdValue,
    viewIdToNavigateToSelectPair: 'pair-selection-page',
    viewIdToViewRequestSender: 'user-page',
  };
}
function getPairOverviewViewConfig(mentornityCookieContext, language, config, viewConfigs) {
  const i18n = language === 'tr' ? tr : en;
  const { role } = mentornityCookieContext;
  const viewingGroups = role === 'mentor' && config.menteeType === 'group';
  let cardBodyFields = [];
  const viewName = role === 'mentor'
    ? MentornityViewConfigViewName.MenteePairList
    : MentornityViewConfigViewName.MentorPairList;
  const viewConfig = getViewConfigForViewName(viewConfigs, viewName);
  if (viewConfig) {
    const pairOverviewConfig = viewConfig.dvnAppViewConfig;
    cardBodyFields = pairOverviewConfig.ui.main.cardViewConfig.body.fields;
  }
  else {
    const profileFieldVisibility = role === 'mentor' ? config.profileFieldVisibilities.mentee : config.profileFieldVisibilities.mentor;
    const defaultUserFields = ['title', 'bio', 'skills', 'imagePlaceholderValue'].filter(id => profileFieldVisibility[id]).map(id => ({ fieldId: id }));
    const defaultGroupFields = ['description', 'imagePlaceholderValue'].map(id => ({ fieldId: id }));
    const fields = viewingGroups ? [] : getAvailableMetadataFields(role, config);
    cardBodyFields = (viewingGroups ? defaultGroupFields : [...defaultUserFields, ...convertFieldsToFieldReferences(fields)])
      .slice(0, 3)
      .map(fieldConfig => (Object.assign(Object.assign({}, fieldConfig), { lines: 1 }))) // to trim long texts
      .filter(field => !['name', 'imageUrl', 'imagePlaceholderValue'].includes(field.fieldId));
  }
  return AtamaMemberPairsOverviewViewConfig.decode({
    _id: 'pair-overview-page',
    ui: {
      i18n: i18n.view,
      main: {
        cardViewConfig: {
          header: {
            cover: {
              size: 100,
            },
            image: {
              fieldId: 'imageUrl',
              placeholderFieldId: 'imagePlaceholderValue',
              shape: viewingGroups ? 'rounded' : undefined,
              size: 72,
            },
            title: {
              fieldId: viewingGroups ? 'title' : 'name',
            },
          },
          body: {
            fields: cardBodyFields,
          },
          footer: {
            actions: [
              {
                data: {
                  type: 'navigation',
                  direction: 'forward',
                  placement: 'view',
                  viewId: 'subscriptions',
                  params: {
                    conversionConfig: {
                      'item._id': 'memberToViewRefFieldValue',
                      'item.subscription._id': 'pairId',
                    }
                  }
                },
                ui: {
                  label: i18n.view.viewAndMeet || 'View & Meet',
                  name: 'open-pair-detail-view',
                  view: 'ghost',
                }
              }
            ]
          }
        },
      },
    },
    params: {},
    table: pairConfig(config, undefined, getPairConfigOptionsFromOrganisationConfig(config)),
  });
}
function getUserDetailDialogParams(actionData) {
  return {
    itemId: actionData.params.item._id,
  };
}
function getUserDetailDialogViewConfig(mentornityCookieContext, config) {
  if (!config) {
    return undefined;
  }
  const { organisationId, role } = mentornityCookieContext;
  const profileFieldVisibility = role === 'mentor' ? config.profileFieldVisibilities.mentee : config.profileFieldVisibilities.mentor;
  const defaultUserFields = ['title', 'bio', 'skills'].filter(id => profileFieldVisibility[id]).map(id => ({ fieldId: id }));
  const fields = getAvailableMetadataFields(role, config);
  const detailViewMembershipFields = decodeFields([...commonUserInfoFields, ...fields]);
  const detailViewCardFields = [...defaultUserFields, ...convertFieldsToFieldReferences(fields)]
    .filter(field => !['name', 'imageUrl'].includes(field.fieldId));
  const showMessageButton = [
    InfoVisibility.allMentees,
    InfoVisibility.everyone,
  ].includes(config.conversationPermissions.mentor);
  return DetailViewConfig.decode({
    table: TableConfig.decode({
      base: organisationId,
      name: 'mentees',
    }),
    ui: {
      fields: detailViewMembershipFields,
      cardConfig: {
        header: {
          title: {
            fieldId: 'name',
          },
          actions: showMessageButton ? [
            {
              ui: {
                label: 'Send Message',
                name: 'send-message',
              }
            }
          ] : [],
        },
        body: {
          fields: detailViewCardFields,
        }
      }
    },
  });
}

const MentornityPairsOverviewWrapper = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
  }
  onAction(event) {
    const action = event.detail;
    if (action.type === 'navigation') {
      const navigateAction = action;
      if (navigateAction.direction === 'forward') {
        const navigateForwardAction = action;
        if (navigateForwardAction.name === 'open-pair-detail-view') {
          const { memberToViewRefFieldValue, pairId } = navigateForwardAction.params;
          // called when mentor/mentee clicks the "View User & Meet" button on the user card
          window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-pair-detail', {
            detail: {
              userId: memberToViewRefFieldValue,
              pairId,
            }
          }));
        }
        if (navigateForwardAction.viewId === 'pair-selection-page') {
          // called when mentee clicks the "Go to mentor selection page" on the top announcement card
          window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-pair-selection-page', {}));
        }
        if (navigateForwardAction.viewId === 'user-page') {
          // called when mentor clicks the user information from the received requests list
          this.viewUserDetailDialogActionData = navigateForwardAction;
        }
      }
    }
    if (action.name === 'send-message') {
      // called when mentor clicks the "Send Message" button from the user detail dialog
      window.dispatchEvent(new CustomEvent('dvn.atama-pairs.send-message', {
        detail: {
          user: action.params.item.user,
        }
      }));
      this.viewUserDetailDialogActionData = undefined;
    }
  }
  async componentWillLoad() {
    const { language } = this;
    const { context, headers } = getSessionDetails();
    this.mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const getViewConfigsResponse = await mentornityApi.getViewConfigs(context.organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    const viewConfigs = getViewConfigsResponse.results;
    const config = await mentornityApi.getOrganisationConfig(context.organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = Config.decode(config);
    this.atamaMemberPairsOverviewViewConfig = getPairOverviewViewConfig(context, language, this.organisationConfig, viewConfigs);
  }
  render() {
    const { context } = getSessionDetails();
    const { mentornityBridgeApi, organisationConfig, viewUserDetailDialogActionData } = this;
    if (!this.atamaMemberPairsOverviewViewConfig) {
      return null;
    }
    return (h("mentornity-root-wrapper", null, h("dvn-app-view-atama-member-pairs-overview-view", { apiAtama: mentornityBridgeApi, apiUye: mentornityBridgeApi, membership: DataModel.decode({}), params: getPairOverviewParameters(context), view: this.atamaMemberPairsOverviewViewConfig }), viewUserDetailDialogActionData &&
      h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.viewUserDetailDialogActionData = undefined }, h("dvn-app-view-detail-view-card", { apiData: mentornityBridgeApi, id: "user-page", params: getUserDetailDialogParams(viewUserDetailDialogActionData), view: getUserDetailDialogViewConfig(context, organisationConfig) }))));
  }
};

export { MentornityPairsOverviewWrapper as mentornity_pairs_overview_wrapper };
