import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-b7735e0d.js';
import { a as ResponsiveSize, R as ResponsiveUIHelper } from './ui-c7f31f6f.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-80ec23ef.js';
import { T as TextField } from './index-403101cb.js';
import { C as ConcealerConditional, E as Equal } from './Equal-8818d86d.js';
import { c as capitalize } from './string-3065a411.js';
import { U as User } from './User-1ef5a482.js';
import { a as iterateMonth, b as isBefore, c as iterateWeek, d as isAfter, e as isEqual, i as iterateMinutes, f as isBeforeOrEqual, g as isSameDay } from './date-utils-4805a4af.js';
import { A as Availability } from './Availability-d59034ec.js';
import './data-model-f7ccf826.js';
import './reference-field-0e7cd534.js';
import './index-7b119e61.js';
import './index-1d3efe49.js';
import './index-eb14fd2d.js';
import './index-4c39b6a6.js';
import { m as momentTimezone } from './index-3958847a.js';
import { z as zoneConfig } from './time-zones-cf1e6113.js';
import { C as CalendarUtils } from './calendar-67e174ec.js';
import { S as SozlukApi } from './index-1e9f4c53.js';
import { t as takvimAvailableTimePickerSelectedDayI18nDefault } from './i18n-f1ddd0c3.js';
import './BaseField-461b6d0c.js';
import './InterceptorHandler-6474bcf4.js';
import './date-ce777316.js';
import './_commonjsHelpers-27f122dd.js';
import './moment-6f6ab70c.js';
import './i18n-27a6b633.js';

const MAX_MONTH_FOR_RECURRENCE = 3;
const lastday = (date) => {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
};
/**
 * Generates the availabilities from the raw availability list by using their recurrence.
 * Recurring availabilities are populated for every week/month until the maxMonthForRecurrence is reached.
 * @param availabilities
 * @param maxMonthForRecurrence
 * @param startDate used for calculating the end month
 */
const generateAvailabilities = (availabilities, maxMonthForRecurrence = MAX_MONTH_FOR_RECURRENCE, startDate = new Date()) => {
  const maxDate = iterateMonth(startDate, maxMonthForRecurrence);
  maxDate.setDate(lastday(maxDate)); // last day is the end of the iterated month
  const now = new Date();
  const allAvailabilities = [];
  availabilities.forEach(availability => {
    if (availability.recurrence === 'weekly') {
      let baseStartDate = new Date(availability.startDate);
      let baseEndDate = new Date(availability.endDate);
      while (isBefore(baseStartDate, maxDate)) {
        allAvailabilities.push(Availability.decode(Object.assign(Object.assign({}, availability), { startDate: baseStartDate.toISOString(), endDate: baseEndDate.toISOString() })));
        baseStartDate = iterateWeek(baseStartDate, 1);
        baseEndDate = iterateWeek(baseEndDate, 1);
      }
    }
    else if (new Date(availability.endDate) >= now) {
      // single
      allAvailabilities.push(availability);
    }
  });
  return allAvailabilities;
};
/**
 * Returns the earliest start time and latest end time of the given availabilities.
 * @param availabilities
 */
const getTimeFrameOfAvailabilities = (availabilities) => {
  let startDate;
  let endDate;
  availabilities.forEach(availability => {
    if (!startDate || isBefore(new Date(availability.startDate), startDate)) {
      startDate = new Date(availability.startDate);
    }
    if (!endDate || isAfter(new Date(availability.endDate), endDate)) {
      endDate = new Date(availability.endDate);
    }
  });
  return { startDate, endDate };
};
const generateSlotsForAvailabilities = (availabilities = [], unavailabilitiesOfCurrentUser, unavailabilitiesOfOtherUser) => {
  const timeSlots = [];
  availabilities.forEach(availability => {
    const slots = generateSlotsForAvailability(availability);
    slots.forEach(slot => {
      if (new Date(slot.start) < new Date()) {
        return;
      }
      let hasIntersection = false;
      for (let i = 0; i < unavailabilitiesOfOtherUser.length; i++) {
        const unavailability = unavailabilitiesOfOtherUser[i];
        if (doTimesIntersect(slot.start, slot.end, new Date(unavailability.startDate), new Date(unavailability.endDate))) {
          hasIntersection = true;
          break;
        }
      }
      if (hasIntersection) {
        return;
      }
      for (let i = 0; i < unavailabilitiesOfCurrentUser.length; i++) {
        const unavailability = unavailabilitiesOfCurrentUser[i];
        if (doTimesIntersect(new Date(slot.start), new Date(slot.end), new Date(unavailability.startDate), new Date(unavailability.endDate))) {
          slot.sessionUserConflict = unavailability.reason;
          break;
        }
      }
      timeSlots.push(slot);
    });
  });
  return timeSlots;
};
const doTimesIntersect = (start1, end1, start2, end2) => {
  if (isEqual(start1, start2) || isEqual(end1, end2)) {
    return true;
  }
  // s1    e1
  //    s2    e2
  if (isBefore(start1, start2) && isBefore(start2, end1)) {
    return true;
  }
  //    s1    e1
  // s2    e2
  if (isBefore(start2, start1) && isBefore(start1, end2)) {
    return true;
  }
  //    s1  e1
  // s2        e2
  if (isBefore(start2, start1) && isBefore(end1, end2)) {
    return true;
  }
  // s1        e1
  //    s2  e2
  if (isBefore(start1, start2) && isBefore(end2, end1)) {
    return true;
  }
  return false;
};
const generateSlotsForAvailability = (availability) => {
  let slotStart = new Date(availability.startDate);
  let slotEnd = iterateMinutes(slotStart, availability.meetingDuration);
  const availabilityEnd = new Date(availability.endDate);
  const slots = [];
  do {
    slotStart.setSeconds(1);
    slots.push({
      availabilityId: availability._id,
      start: slotStart,
      end: slotEnd,
    });
    slotStart = iterateMinutes(slotEnd, availability.breakDuration || 0);
    slotEnd = iterateMinutes(slotStart, availability.meetingDuration);
  } while (isBeforeOrEqual(slotEnd, availabilityEnd));
  return slots;
};

const takvimAvailableTimePickerCss = "takvim-available-time-picker.mobile date-picker-container dvn-date-picker{margin-right:0 !important}takvim-available-time-picker.desktop dvn-date-picker{margin-right:1rem !important}";

const meetingLocationTypes = [
  {
    name: 'Custom',
    value: 'custom',
  },
  {
    name: 'Jitsi Meet',
    value: 'jitsi',
  },
  {
    name: 'Zoom',
    value: 'zoom',
  },
];
const formErrors = (error) => {
  if (!error)
    return [];
  // TODO show proper error messages from apiSozluk
  return [
    capitalize(`${error.data.message.split('-').join(' ')}.`, false),
  ];
};
const formFields = (meetingTypes = [], meetingsByMeetingTypes = {}, isCustom, authPlatforms) => {
  let maxFieldCount = isCustom ? 2 : 0;
  const fields = [];
  const availableMeetingTypes = meetingTypes
    .filter(meetingType => { var _a; return (((_a = meetingsByMeetingTypes[meetingType.id]) === null || _a === void 0 ? void 0 : _a.length) || 0) < meetingType.maxCount; });
  if (meetingTypes && meetingTypes.length > 0) {
    maxFieldCount += 1;
    fields.push(new SingleChoiceField('meetingType', 'Select a Session', availableMeetingTypes.map(meetingType => new SingleChoiceFieldOption(meetingType.name, meetingType.id)), '', 'select').setErrorTitle('Session').require());
  }
  fields.push(...[
    new SingleChoiceField('locationType', 'Location Type', meetingLocationTypes
      // filter out the location types if user doesn't have the corresponding auth platform (zoom)
      .filter(locationType => {
      if (locationType.value === 'custom' || locationType.value === 'jitsi') {
        return true;
      }
      return !!authPlatforms.some(authPlatform => authPlatform.id === locationType.value);
    })
      .map(locationType => new SingleChoiceFieldOption(locationType.name, locationType.value)), '', 'select').setValue('jitsi')
      .setVisibility(isCustom)
      .require(),
    new TextField('location', 'Location', 'Meeting location')
      .addInterceptor('onFormChange', new ConcealerConditional(new Equal('locationType', 'custom')))
      .require()
      .hide()
  ]);
  return { fields, maxFieldCount };
};
let TakvimAvailableTimePicker = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.createMeeting = createEvent(this, "createMeeting", 7);
    this.meetingsByMeetingTypes = {};
    /**
     * Raw availabilities fetched from the api.
     */
    this.availabilities = [];
    /**
     * Availabilities that are generated by the raw availabilities considering their recurrence.
     * MAX_MONTH_FOR_RECURRENCE is used to limit the availabilities for the future.
     */
    this.generatedAvailabilities = [];
    this.meetingLocationType = 'jitsi';
    this.meetingLocation = '';
    this.isProgressing = true;
    this.weekStartDay = 'monday';
    this.onSizeChange = (size) => {
      this.size = size;
      this.selectedTime = undefined;
      if (this.isMobileUI()) {
        // reset the date otherwise the slot list dialog will pop when switched to mobile
        this.selectedDate = undefined;
      }
      else {
        // set the date otherwise the slot list will keep showing progress
        this.selectedDate = new Date();
      }
    };
    this.isMobileUI = () => this.size < ResponsiveSize.Small;
    this.onSelectTime = async (e) => {
      this.selectedTime = e.detail;
      const showMeetingDetailsForm = !!this.selectedDate && !!this.selectedTime;
      if (showMeetingDetailsForm && !this.meetings && this.meetingTypes) {
        // get the meetings of the users to filter out the meeting types based on the number of meetings they have
        const { viewedUserId, calendarConfigId, userId } = this;
        this.isProgressing = true;
        const meetings = await this.apiTakvim.getMeetingsOfUser(calendarConfigId, [userId, viewedUserId]).catch(e => {
          this.error = e;
        }).finally(() => this.isProgressing = false);
        if (!meetings)
          return;
        this.meetings = meetings.results;
        const meetingsByMeetingTypes = {};
        this.meetings.forEach(meeting => {
          if (meetingsByMeetingTypes[meeting.meetingType]) {
            meetingsByMeetingTypes[meeting.meetingType].push(meeting);
          }
          else {
            meetingsByMeetingTypes[meeting.meetingType] = [meeting];
          }
        });
        this.meetingsByMeetingTypes = meetingsByMeetingTypes;
      }
    };
    this.onSubmitForm = async (event) => {
      const data = event.detail.values;
      const { location, locationType, meetingType } = data;
      const { startHour, endHour, availabilityId } = this.selectedTime;
      const meeting = {
        locations: [{
            address: location,
            type: locationType,
          }],
        meetingType,
        startDate: startHour.toISOString(),
        endDate: endHour.toISOString(),
        guests: [
          User.generateRef(this.viewedUserId),
          User.generateRef(this.userId),
        ],
        createdBy: User.generateRef(this.userId),
        status: 'active',
        calendar: { _ref: 'takvim-calendar-configs', _id: this.calendarConfigId },
      };
      if (availabilityId) {
        meeting.availability = {
          _ref: 'takvim-availabilities',
          _id: availabilityId
        };
      }
      this.createMeetingError = undefined;
      this.isProgressing = true;
      const createMeetingResponse = await this.apiTakvim.createMeeting(meeting).catch(e => {
        this.createMeetingError = e;
      }).finally(() => this.isProgressing = false);
      if (!createMeetingResponse)
        return;
      this.meetings = undefined;
      this.selectedTime = undefined;
      this.selectedDate = new Date(this.selectedDate.toISOString());
      this.createMeeting.emit(Object.assign(Object.assign({}, createMeetingResponse), meeting));
    };
  }
  async componentWillLoad() {
    this.uiHelper = new ResponsiveUIHelper(this.el, this.onSizeChange);
    this.size = ResponsiveUIHelper.getSize(this.el.parentElement.clientWidth);
  }
  async componentDidLoad() {
    const { viewedUserId, calendarConfigId } = this;
    const calenderConfig = await this.apiTakvim.getCalendarConfig(calendarConfigId).catch(e => {
      this.error = e;
    });
    if (!calenderConfig)
      return;
    this.calendarConfig = calenderConfig;
    const availabilities = await this.apiTakvim.getAvailabilitiesOfUser(calendarConfigId, viewedUserId).catch(e => {
      this.error = e;
    }).finally(() => this.isProgressing = false);
    if (!availabilities)
      return;
    this.availabilities = availabilities.results;
    this.generatedAvailabilities = generateAvailabilities(availabilities.results);
    if (!this.isMobileUI()) {
      // invoke onSelectDate for generating slots for today
      this.selectedDate = new Date();
    }
  }
  render() {
    const { calendarConfigId, calendarConfig, createMeetingError, generatedAvailabilities, isProgressing, meetingsByMeetingTypes, meetingTypes, selectedDate, selectedTime, strings, userId, membershipConfigId, viewedUserId, viewedUserMembershipConfigId, weekStartDay, } = this;
    const showMeetingDetailsForm = !!selectedDate && !!selectedTime;
    const { fields: meetingDetailsFormFields, maxFieldCount } = formFields(meetingTypes, meetingsByMeetingTypes, !(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.availabilityId), this.userSettings.authPlatforms);
    const minFormHeight = `${Math.max(maxFieldCount * 100, (meetingTypes === null || meetingTypes === void 0 ? void 0 : meetingTypes.length) > 0 ? 200 : 120)}px`;
    const timeZone = this.userSettings.timeZone;
    const dialogTitle = `${momentTimezone(selectedDate).tz(timeZone).format('DD MMMM')}, ${momentTimezone(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour).tz(timeZone).format('HH:mm')} - ${momentTimezone(selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour).tz(timeZone).format('HH:mm')}`;
    if (this.isMobileUI()) {
      return (h(Host, { class: "d-flex mobile" }, h("dvn-card", { class: "date-picker-container", bodyLeaned: true, leaned: true, elevation: 0, width: "100%" }, h("div", { class: "d-flex justify-content-center" }, h("dvn-date-picker", { embedded: true, leaned: true, value: generatedAvailabilities.map(ca => new Date(ca.startDate)), onChange: (e) => this.selectedDate = e.detail, strings: strings, weekStartDay: weekStartDay }))), h("dvn-dialog", { class: "confirmation-dialog", shown: !!selectedDate || showMeetingDetailsForm, onDismiss: (e) => {
          e.preventDefault();
          e.stopPropagation();
          this.createMeetingError = undefined;
          if (selectedTime) {
            this.selectedTime = undefined;
          }
          else {
            this.selectedDate = undefined;
          }
        }, raw: !!selectedDate && !showMeetingDetailsForm, title: dialogTitle }, (selectedDate && !showMeetingDetailsForm) &&
        h("takvim-available-time-picker-selected-day", { availabilities: this.generatedAvailabilities, calenderConfig: calendarConfig, selectedDate: selectedDate, userId: userId, membershipConfigId: membershipConfigId, userSettings: this.userSettings, viewedUserId: viewedUserId, viewedUserMembershipConfigId: viewedUserMembershipConfigId, calendarConfigId: calendarConfigId, apiTakvim: this.apiTakvim, onSelectTime: this.onSelectTime, strings: strings }), showMeetingDetailsForm &&
        h("div", { class: "ml-3 mr-3 mt-3 mb-2" }, h("div", null, strings.scheduleMeetingConfirmation, h("br", null), h("br", null)), h("doldurma-form", { key: `${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour}-${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour}`, fields: meetingDetailsFormFields, onSubmit: this.onSubmitForm, submitButtonLabel: strings.scheduleMeeting, progressing: isProgressing, formErrors: formErrors(createMeetingError), minHeight: minFormHeight, width: '100%' })))));
    }
    return (h(Host, { class: "d-flex desktop" }, h("dvn-date-picker", { embedded: true, leaned: true, value: generatedAvailabilities.map(ca => new Date(ca.startDate)), highlightedDay: this.selectedDate, onChange: (e) => this.selectedDate = e.detail, strings: strings, weekStartDay: weekStartDay }), h("takvim-available-time-picker-selected-day", { availabilities: this.generatedAvailabilities, calenderConfig: calendarConfig, selectedDate: selectedDate, userId: userId, membershipConfigId: membershipConfigId, userSettings: this.userSettings, viewedUserId: viewedUserId, viewedUserMembershipConfigId: viewedUserMembershipConfigId, calendarConfigId: calendarConfigId, apiTakvim: this.apiTakvim, onSelectTime: this.onSelectTime, strings: strings }), h("dvn-dialog", { class: "confirmation-dialog", shown: showMeetingDetailsForm, onDismiss: () => {
        this.selectedTime = undefined;
        this.createMeetingError = undefined;
      }, minHeight: '240px', title: dialogTitle }, h("div", null, strings.scheduleMeetingConfirmation, h("br", null), h("br", null)), h("doldurma-form", { key: `${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.startHour}-${selectedTime === null || selectedTime === void 0 ? void 0 : selectedTime.endHour}`, fields: meetingDetailsFormFields, onSubmit: this.onSubmitForm, submitButtonLabel: strings.scheduleMeeting, progressing: isProgressing, formErrors: formErrors(createMeetingError), minHeight: minFormHeight, width: '100%' }))));
  }
  get el() { return getElement(this); }
};
TakvimAvailableTimePicker.style = takvimAvailableTimePickerCss;

const takvimAvailableTimePickerSelectedDayCss = "takvim-available-time-picker-selected-day{-ms-flex:1;flex:1;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}takvim-available-time-picker-selected-day .selected-day-container{-ms-flex:1;flex:1;max-height:calc(var(--date-picker-body-height) + 75px)}@-webkit-keyframes fadeInOpacity{0%{opacity:0;margin-left:10px}100%{opacity:1;margin-left:0}}@keyframes fadeInOpacity{0%{opacity:0;margin-left:10px}100%{opacity:1;margin-left:0}}takvim-available-time-picker-selected-day .selected-day-container .day-title{-webkit-animation-name:fadeInOpacity;animation-name:fadeInOpacity;-webkit-animation-timing-function:ease-in-out;animation-timing-function:ease-in-out;-webkit-animation-duration:0.3s;animation-duration:0.3s}takvim-available-time-picker-selected-day .selected-day-container .progress-container{display:-ms-flexbox;display:flex;height:100%;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;padding-bottom:1rem}takvim-available-time-picker-selected-day .selected-day-container .selected-day-availabilities dvn-card{margin:0 0 0.5rem 0;text-align:center;font-size:0.9em}takvim-available-time-picker-selected-day .selected-day-container .no-availability-message{font-size:0.9em}takvim-available-time-picker-selected-day .selected-day-container .custom-time-picker{height:100%;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}takvim-available-time-picker-selected-day .selected-day-container .custom-time-picker table{-ms-flex:1;flex:1}takvim-available-time-picker-selected-day .selected-day-container .slots-container{height:100%;overflow:auto}";

const conflictSourceNames = {
  'google-calendar': 'Google Calendar',
  'microsoft-calendar': 'Microsoft Calendar',
};
let TakvimAvailableTimePickerSelectedDay = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.selectTime = createEvent(this, "selectTime", 7);
    /**
     * Availabilities filtered by the selected date.
     */
    this.availabilitiesForTheSelectedDate = [];
    /**
     * Duration options of the selected date. Used when there are multiple
     * availabilities for the same date with different durations.
     */
    this.durationForTheSelectedDate = [];
    /**
     * Time slots that are generated when duration (if needed)
     * and availabilities are selected.
     */
    this.timeSlots = [];
    /**
     * Custom time values.
     */
    this.isPickingCustomTime = false;
    this.customTime = { hour: 9, minute: 0 };
    this.customDuration = 30;
    /**
     * API related values.
     */
    this.isProgressing = false;
    this.availabilities = [];
    this.strings = takvimAvailableTimePickerSelectedDayI18nDefault;
    this.durations = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 75, 90, 105, 120];
    this.onSelectSlot = (slot) => {
      this.selectTime.emit({
        availabilityId: slot.availabilityId,
        startHour: slot.start,
        endHour: slot.end,
      });
    };
    this.onSelectCustomTime = () => {
      const timeZone = this.userSettings.timeZone;
      const date = this.selectedDate;
      const time = this.customTime;
      const timeString = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()} ${time.hour}:${time.minute}`;
      const startHour = momentTimezone.tz(timeString, 'D/M/YYYY h:mm', timeZone).toDate();
      const endHour = iterateMinutes(startHour, this.customDuration);
      this.selectTime.emit({ startHour, endHour });
    };
    this.onSelectDuration = async (duration) => {
      const { userId, viewedUserId, calendarConfigId } = this;
      this.selectedDurationAvailabilities = this.availabilitiesForTheSelectedDate.filter(a => a.meetingDuration === duration);
      // get the earliest start time and latest end time of the availabilities to fetch the unavailabilities for that time period
      const { startDate, endDate } = getTimeFrameOfAvailabilities(this.selectedDurationAvailabilities);
      this.isProgressing = true;
      const unavailabilitiesOfCurrentUser = await this.apiTakvim.getUnavailabilitiesOfUser(calendarConfigId, userId, startDate.toISOString(), endDate.toISOString()).catch(e => {
        this.error = e;
      });
      if (!unavailabilitiesOfCurrentUser)
        return;
      const unavailabilitiesOfOtherUser = await this.apiTakvim.getUnavailabilitiesOfUser(calendarConfigId, viewedUserId, startDate.toISOString(), endDate.toISOString()).catch(e => {
        this.error = e;
      }).finally(() => this.isProgressing = false);
      if (!unavailabilitiesOfOtherUser)
        return;
      this.timeSlots = generateSlotsForAvailabilities(this.selectedDurationAvailabilities, unavailabilitiesOfCurrentUser.results, unavailabilitiesOfOtherUser.results);
    };
  }
  componentWillLoad() {
    this.onSelectedDateChange(this.selectedDate);
  }
  onSelectedDateChange(selectedDate) {
    this.selectedDurationAvailabilities = undefined;
    this.timeSlots = [];
    this.isPickingCustomTime = false;
    if (!selectedDate) {
      return;
    }
    this.availabilitiesForTheSelectedDate = this.availabilities
      // filter based on the selected date
      .filter(ca => isSameDay(new Date(ca.startDate), selectedDate))
      // sort to show slots in order if there are multiple availabilities with the same duration
      .sort((a, b) => (isBeforeOrEqual(new Date(a.startDate), new Date(b.startDate)) ? -1 : 1));
    if (this.availabilitiesForTheSelectedDate.length === 1) {
      // select the first availability automatically
      this.onSelectDuration(this.availabilitiesForTheSelectedDate[0].meetingDuration);
      return;
    }
    const durationForTheSelectedDate = [];
    this.availabilitiesForTheSelectedDate.forEach(availability => {
      if (!durationForTheSelectedDate.includes(availability.meetingDuration)) {
        durationForTheSelectedDate.push(availability.meetingDuration);
      }
    });
    this.durationForTheSelectedDate = durationForTheSelectedDate;
  }
  ;
  render() {
    const { availabilitiesForTheSelectedDate, calenderConfig, durationForTheSelectedDate, isPickingCustomTime, isProgressing, selectedDate, selectedDurationAvailabilities, membershipConfigId, userSettings, viewedUserMembershipConfigId, timeSlots, strings, } = this;
    const isPickingOneOfAvailabilitiesOfTheSelectedDate = selectedDate && !selectedDurationAvailabilities
      && availabilitiesForTheSelectedDate.length > 1;
    const isPickingTimeSlot = !!selectedDurationAvailabilities;
    // get calendar preferences of the viewed user
    const calendarPreferences = calenderConfig === null || calenderConfig === void 0 ? void 0 : calenderConfig.membershipPreferences.find(preference => preference.membershipConfig._id === viewedUserMembershipConfigId);
    // check if the user membership is allowed to get custom time
    const eligibleMembershipsForCustomTime = (calendarPreferences === null || calendarPreferences === void 0 ? void 0 : calendarPreferences.eligibleMembershipsForCustomTime) || [];
    const canPickCustomTime = eligibleMembershipsForCustomTime
      .some(membershipConfig => membershipConfig._id === membershipConfigId);
    const { timeZone, dateFormat } = userSettings;
    let zoneName = '';
    zoneConfig.forEach(group => {
      group.zones.forEach(zone => {
        if (userSettings.timeZone === zone.value) {
          zoneName = zone.name;
        }
      });
    });
    let cardHeader = `${CalendarUtils.format(selectedDate, 'DD MMMM YYYY')}`;
    if (dateFormat === "MM/DD/YYYY") {
      cardHeader = `${CalendarUtils.format(selectedDate, 'MMMM DD YYYY')}`;
    }
    if (!selectedDate) {
      return (h(Host, null, h("dvn-card", { extraClass: "selected-day-container", elevation: 0, leaned: true }, h("dvn-card-header", { title: cardHeader, slot: "header", separated: false }), h("div", { class: "progress-container" }, h("dvn-progress", { indefinite: true, tint: "primary" })))));
    }
    return (h(Host, null, h("dvn-card", { extraClass: "selected-day-container", elevation: 0, leaned: true }, h("div", { slot: "header", class: "available-time-picker-date-header p-3 d-flex justify-content-between align-content-center" }, h("h4", { key: cardHeader, class: "mt-0 mb-0 day-title" }, cardHeader), h("span", { class: "text-neutral" }, h("i", { class: 'uil uil-clock' }), zoneName)), isProgressing &&
      h("div", { class: "progress-container" }, h("dvn-progress", { indefinite: true, tint: "primary" })), h("div", { class: "custom-time-picker", style: { display: isPickingCustomTime ? 'flex' : 'none' } }, h("table", null, h("tbody", null, h("tr", null, h("td", null, strings.time), h("td", null, h("dvn-time-picker", { hour: this.customTime.hour, minute: this.customTime.minute, optionsContainerMaxHeight: "132px", leaned: true, onChange: (e) => this.customTime = e.detail }))), h("tr", null, h("td", null, strings.duration), h("td", null, h("dvn-select", { width: "99px", hideCaret: true, hideCheck: true, hideScrollbar: true, value: `${this.customDuration}`, optionsContainerMaxHeight: "112px", leaned: true, onChange: (e) => this.customDuration = Number(e.detail), enableSearch: true }, this.durations.map(minute => (h("dvn-select-option", { value: `${minute}` }, `${minute} ${strings.min}`)))))))), h("div", { class: "d-flex justify-content-end mt-2" }, h("dvn-button", { tint: "primary", onClick: this.onSelectCustomTime }, strings.done), h("dvn-button", { tint: "neutral", onClick: () => this.isPickingCustomTime = false }, strings.cancel))), h("div", { class: "selected-day-availabilities", style: { display: isPickingCustomTime ? 'none' : 'block' } }, isPickingOneOfAvailabilitiesOfTheSelectedDate &&
      h("div", { class: "duration-options-container" }, durationForTheSelectedDate.map(duration => (h("dvn-card", { elevation: 0, outlined: true, selectable: true, onClick: () => this.onSelectDuration(duration) }, SozlukApi.build(strings.bookWithDuration, { duration }))))), isPickingTimeSlot &&
      h("div", { class: "slots-container" }, timeSlots.map(slot => (h("dvn-card", { key: `${slot.availabilityId}-${slot.start}`, extraClass: "time-slot", elevation: 0, outlined: true, selectable: true, onClick: () => this.onSelectSlot(slot), tint: slot.sessionUserConflict ? 'danger' : undefined }, momentTimezone(slot.start).tz(timeZone).format('HH:mm'), " - ", momentTimezone(slot.end).tz(timeZone).format('HH:mm'), slot.sessionUserConflict &&
        h("div", { class: "session-user-conflict-message mt-1" }, h("small", null, SozlukApi.build(strings.conflictsWithCalendar, {
          meetingName: slot.sessionUserConflict.name,
          calendarName: conflictSourceNames[slot.sessionUserConflict.source],
        }))))))), (!isPickingOneOfAvailabilitiesOfTheSelectedDate && !isProgressing) &&
      (canPickCustomTime
        ? h("dvn-card", { extraClass: "pick-custom-time-button", elevation: 0, outlined: true, selectable: true, onClick: () => this.isPickingCustomTime = true }, strings.pickCustomTime)
        : (timeSlots.length === 0 && h("div", { class: "no-availability-message text-centered mt-3" }, availabilitiesForTheSelectedDate.length
          ? strings.noAvailabilityLeftForDay
          : strings.noAvailabilityForDay)))))));
  }
  static get watchers() { return {
    "selectedDate": ["onSelectedDateChange"]
  }; }
};
TakvimAvailableTimePickerSelectedDay.style = takvimAvailableTimePickerSelectedDayCss;

export { TakvimAvailableTimePicker as takvim_available_time_picker, TakvimAvailableTimePickerSelectedDay as takvim_available_time_picker_selected_day };
