import { ref as b, computed as B, watch as F, onMounted as V, openBlock as E, createBlock as G, unref as e, withCtx as k, createVNode as i, createElementVNode as M, toDisplayString as P, nextTick as N, createElementBlock as g, Fragment as x, renderList as Y, normalizeClass as q, createTextVNode as W, getCurrentInstance as j } from "vue";
import { DtIconChevronsLeft as J, DtIconChevronLeft as Q, DtIconChevronRight as Z, DtIconChevronsRight as ee } from "@dialpad/dialtone-icons/vue3";
import { getMonth as K, getYear as S, getDate as te, set as ae, addMonths as ne, subMonths as re } from "date-fns";
import { getCalendarDays as le, formatMonth as oe, getWeekDayNames as se, formatDate as ce, calculateNextFocusDate as ue, calculatePrevFocusDate as ie } from "./utils.js";
import { INTL_MONTH_FORMAT as U, WEEK_START as de } from "./datepicker-constants.js";
import { returnFirstEl as D, warnIfUnmounted as fe } from "../../common/utils/index.js";
import { DialtoneLocalization as z } from "../../localization/index.js";
import R from "../stack/stack.js";
import w from "../tooltip/tooltip.js";
import I from "../button/button.js";
function ve(d, o) {
  const s = b(K(d.selectedDate)), t = b(S(d.selectedDate)), n = b(null), r = b(0), m = b([]), v = new z(), T = B(() => le(s.value, t.value, n.value));
  F(s, () => {
    l(), o("calendar-days", T.value);
  }, { immediate: !0 }), F(t, () => {
    l(), o("calendar-days", T.value);
  }, { immediate: !0 });
  function _(a) {
    return oe(a, U, v.currentLocale);
  }
  function y(a) {
    m.value.includes(a) || m.value.push(a);
  }
  function h() {
    D(m.value[0].$el).focus();
  }
  function A(a) {
    switch (a.key) {
      case "ArrowLeft":
        a.preventDefault(), r.value === 0 ? (r.value = 3, D(m.value[r.value].$el).focus()) : (r.value--, D(m.value[r.value].$el).focus());
        break;
      case "ArrowRight":
        a.preventDefault(), r.value === 3 ? (r.value = 0, D(m.value[r.value].$el).focus()) : (r.value++, D(m.value[r.value].$el).focus());
        break;
      case "ArrowDown":
        a.preventDefault(), o("focus-first-day");
        break;
      case "Tab":
        a.preventDefault(), o("focus-first-day");
        break;
      case "Escape":
        o("close-datepicker");
        break;
    }
  }
  function l() {
    const a = S(d.selectedDate), L = K(d.selectedDate);
    a !== t.value || L !== s.value ? n.value = null : n.value = te(d.selectedDate);
  }
  function u(a) {
    (s.value === 0 && a === -1 || s.value === 11 && a === 1) && (t.value += a);
    const L = ae(d.selectedDate, { month: s.value, year: t.value }), X = a === 1 ? ne(L, 1) : re(L, 1);
    s.value = K(X);
  }
  function p(a) {
    t.value = t.value + a;
  }
  function f() {
    u(1);
  }
  function C() {
    u(-1);
  }
  function $() {
    return `${v.$t("DIALTONE_DATEPICKER_CHANGE_TO")} ${v.$t("DIALTONE_DATEPICKER_PREVIOUS_YEAR")} ${t.value - 1}`;
  }
  function O() {
    return `${v.$t("DIALTONE_DATEPICKER_CHANGE_TO")} ${v.$t("DIALTONE_DATEPICKER_PREVIOUS_MONTH")} ${_(s.value - 1)}`;
  }
  function H() {
    return `${v.$t("DIALTONE_DATEPICKER_CHANGE_TO")} ${v.$t("DIALTONE_DATEPICKER_NEXT_YEAR")} ${t.value + 1}`;
  }
  function c() {
    return `${v.$t("DIALTONE_DATEPICKER_CHANGE_TO")} ${v.$t("DIALTONE_DATEPICKER_NEXT_MONTH")} ${_(s.value + 1)}`;
  }
  return {
    selectMonth: s,
    selectYear: t,
    formattedMonth: _,
    setDayRef: y,
    focusMonthYearPicker: h,
    handleKeyDown: A,
    changeMonth: u,
    changeYear: p,
    goToNextMonth: f,
    goToPrevMonth: C,
    previousYearAriaLabel: $,
    previousMonthAriaLabel: O,
    nextYearAriaLabel: H,
    nextMonthAriaLabel: c
  };
}
const pe = {
  id: "calendar-heading",
  class: "d-datepicker__month-year-title"
}, De = {
  __name: "month-year-picker",
  props: {
    selectedDate: {
      type: Date,
      required: !0
    }
  },
  emits: [
    /**
       * Will retrieve the calendar days of the given date
       *
       * @event calendar-days
       * @type {Array}
       */
    "calendar-days",
    /**
       * Will focus first day in calendar
       *
       * @event focus-first-day
       */
    "focus-first-day",
    /**
       * Will focus last day in calendar
       *
       * @event focus-last-day
       */
    "focus-last-day",
    /**
       * Will close the datepicker
       *
       * @event close-datepicker
       */
    "close-datepicker"
  ],
  setup(d, { expose: o, emit: s }) {
    const t = d, n = s, r = new z(), {
      selectMonth: m,
      selectYear: v,
      formattedMonth: T,
      setDayRef: _,
      focusMonthYearPicker: y,
      handleKeyDown: h,
      changeMonth: A,
      changeYear: l,
      goToNextMonth: u,
      goToPrevMonth: p,
      previousYearAriaLabel: f,
      previousMonthAriaLabel: C,
      nextMonthAriaLabel: $,
      nextYearAriaLabel: O
    } = ve(t, n);
    return V(() => {
      y();
    }), o({
      focusMonthYearPicker: y,
      goToNextMonth: u,
      goToPrevMonth: p
    }), (H, c) => (E(), G(e(R), {
      class: "d-datepicker__month-year",
      direction: "row",
      gap: "300"
    }, {
      default: k(() => [
        i(e(R), {
          as: "nav",
          class: "d-datepicker__nav",
          direction: "row",
          gap: "200"
        }, {
          default: k(() => [
            i(e(w), {
              "fallback-placements": ["top-start", "auto"],
              message: e(r).$t("DIALTONE_DATEPICKER_PREVIOUS_YEAR"),
              placement: "top"
            }, {
              anchor: k(() => [
                i(e(I), {
                  id: "prevYearButton",
                  ref: (a) => {
                    a && e(_)(a);
                  },
                  "aria-label": e(f)(),
                  circle: !0,
                  class: "d-datepicker__nav-btn",
                  importance: "clear",
                  kind: "muted",
                  size: "xs",
                  type: "button",
                  onClick: c[0] || (c[0] = (a) => e(l)(-1)),
                  onKeydown: c[1] || (c[1] = (a) => e(h)(a))
                }, {
                  default: k(() => [
                    i(e(J), { size: "200" })
                  ]),
                  _: 1
                }, 8, ["aria-label"])
              ]),
              _: 1
            }, 8, ["message"]),
            i(e(w), {
              "fallback-placements": ["top-start", "auto"],
              message: e(r).$t("DIALTONE_DATEPICKER_PREVIOUS_MONTH"),
              placement: "top"
            }, {
              anchor: k(() => [
                i(e(I), {
                  id: "prevMonthButton",
                  ref: (a) => {
                    a && e(_)(a);
                  },
                  "aria-label": e(C)(),
                  circle: !0,
                  class: "d-datepicker__nav-btn",
                  importance: "clear",
                  kind: "muted",
                  size: "xs",
                  type: "button",
                  onClick: c[2] || (c[2] = (a) => e(A)(-1)),
                  onKeydown: c[3] || (c[3] = (a) => e(h)(a))
                }, {
                  default: k(() => [
                    i(e(Q), { size: "200" })
                  ]),
                  _: 1
                }, 8, ["aria-label"])
              ]),
              _: 1
            }, 8, ["message"])
          ]),
          _: 1
        }),
        M("div", pe, P(e(T)(e(m))) + " " + P(e(v)), 1),
        i(e(R), {
          as: "nav",
          class: "d-datepicker__nav",
          direction: "row",
          gap: "200"
        }, {
          default: k(() => [
            i(e(w), {
              "fallback-placements": ["top-end", "auto"],
              message: e(r).$t("DIALTONE_DATEPICKER_NEXT_MONTH"),
              placement: "top"
            }, {
              anchor: k(() => [
                i(e(I), {
                  id: "nextMonthButton",
                  ref: (a) => {
                    a && e(_)(a);
                  },
                  "aria-label": e($)(),
                  circle: !0,
                  class: "d-datepicker__nav-btn",
                  importance: "clear",
                  kind: "muted",
                  size: "xs",
                  type: "button",
                  onClick: c[4] || (c[4] = (a) => e(A)(1)),
                  onKeydown: c[5] || (c[5] = (a) => e(h)(a))
                }, {
                  default: k(() => [
                    i(e(Z), { size: "200" })
                  ]),
                  _: 1
                }, 8, ["aria-label"])
              ]),
              _: 1
            }, 8, ["message"]),
            i(e(w), {
              "fallback-placements": ["top-end", "auto"],
              message: e(r).$t("DIALTONE_DATEPICKER_NEXT_YEAR"),
              placement: "top"
            }, {
              anchor: k(() => [
                i(e(I), {
                  id: "nextYearButton",
                  ref: (a) => {
                    a && e(_)(a);
                  },
                  "aria-label": e(O)(),
                  circle: !0,
                  class: "d-datepicker__nav-btn",
                  importance: "clear",
                  kind: "muted",
                  size: "xs",
                  type: "button",
                  onClick: c[6] || (c[6] = (a) => e(l)(1)),
                  onKeydown: c[7] || (c[7] = (a) => e(h)(a))
                }, {
                  default: k(() => [
                    i(e(ee), { size: "200" })
                  ]),
                  _: 1
                }, 8, ["aria-label"])
              ]),
              _: 1
            }, 8, ["message"])
          ]),
          _: 1
        })
      ]),
      _: 1
    }));
  }
};
function me(d, o) {
  const s = b(null), t = b(0), n = b([]), r = new z(), m = B(() => se(d.locale, de));
  F(() => d.calendarDays, () => {
    t.value = 0, n.value = [], s.value = null;
  });
  function v(l) {
    return r.$t("DIALTONE_DATEPICKER_SELECT_DAY") + ` ${ce(l.value, U, r.currentLocale)}`;
  }
  function T(l, u) {
    !n.value.some((p) => p.el === l) && u.currentMonth && n.value.push({ el: l, day: u });
  }
  function _(l) {
    switch (l.key) {
      case "ArrowUp":
        l.preventDefault(), t.value -= 7;
        try {
          D(n.value[t.value].el.$el).focus();
        } catch {
          const p = ie(n.value[t.value + 7].day.value);
          o("go-to-prev-month"), N(() => {
            D(n.value[p - 1].el.$el).focus(), t.value += p - 1;
          });
        }
        break;
      case "ArrowDown":
        l.preventDefault(), t.value += 7;
        try {
          D(n.value[t.value].el.$el).focus();
        } catch {
          const p = ue(n.value[t.value - 7].day.value);
          o("go-to-next-month"), N(() => {
            D(n.value[p - 1].el.$el).focus(), t.value += p - 1;
          });
        }
        break;
      case "ArrowLeft":
        l.preventDefault(), t.value > 0 ? (t.value -= 1, D(n.value[t.value].el.$el).focus()) : (o("go-to-prev-month"), h());
        break;
      case "ArrowRight":
        l.preventDefault(), t.value < n.value.length - 1 ? (t.value += 1, D(n.value[t.value].el.$el).focus()) : (o("go-to-next-month"), y());
        break;
      case "Tab":
        l.preventDefault(), o("focus-month-year-picker");
        break;
      case "Escape":
        o("close-datepicker");
        break;
    }
  }
  function y() {
    t.value = 0, N(() => {
      D(n.value[t.value].el.$el).focus();
    });
  }
  function h() {
    N(() => {
      t.value = n.value.length - 1, D(n.value[t.value].el.$el).focus();
    });
  }
  function A(l) {
    l.currentMonth && (s.value = l.text, o("select-date", l.value));
  }
  return {
    selectedDay: s,
    weekDays: m,
    dayAriaLabel: v,
    setDayRef: T,
    handleKeyDown: _,
    focusFirstDay: y,
    selectDay: A
  };
}
const ke = {
  class: "d-datepicker__calendar",
  "aria-labelledby": "calendar-heading"
}, _e = ["title", "aria-label"], he = {
  __name: "calendar",
  props: {
    calendarDays: {
      type: Array,
      required: !0
    }
  },
  emits: [
    /**
       * Event fired when a date is selected
       *
       * @event select-date
       * @type {Date}
       */
    "select-date",
    /**
       * Will focus the month and year picker
       *
       * @event focus-month-year-picker
       */
    "focus-month-year-picker",
    /**
       * Will close the datepicker
       *
       * @event close-datepicker
       */
    "close-datepicker",
    /**
       * Will go to the next month
       *
       * @event go-to-next-month
       */
    "go-to-next-month",
    /**
       * Will go to the previous month
       *
       * @event go-to-prev-month
       */
    "go-to-prev-month"
  ],
  setup(d, { expose: o, emit: s }) {
    const t = d, n = s, {
      selectedDay: r,
      weekDays: m,
      dayAriaLabel: v,
      setDayRef: T,
      handleKeyDown: _,
      focusFirstDay: y,
      selectDay: h
    } = me(t, n);
    return o({
      focusFirstDay: y
    }), (A, l) => (E(), g("table", ke, [
      M("thead", null, [
        M("tr", null, [
          (E(!0), g(x, null, Y(e(m), (u) => (E(), g("th", {
            key: u,
            scope: "col",
            class: "d-datepicker__cell d-datepicker__cell--header"
          }, [
            M("span", {
              class: "d-datepicker__weekday",
              title: u,
              "aria-label": u
            }, P(u), 9, _e)
          ]))), 128))
        ])
      ]),
      M("tbody", null, [
        (E(!0), g(x, null, Y(d.calendarDays, (u, p) => (E(), g("tr", { key: p }, [
          (E(!0), g(x, null, Y(u.days, (f, C) => (E(), g("td", {
            key: p + C,
            class: "d-datepicker__cell",
            role: "listbox"
          }, [
            i(e(I), {
              ref_for: !0,
              ref: ($) => {
                $ && e(T)($, f);
              },
              class: q(["d-datepicker__day", {
                "d-datepicker__day--disabled": !f.currentMonth,
                "d-datepicker__day--selected": e(r) ? f.text === e(r) && f.currentMonth : f.selected
              }]),
              circle: !0,
              size: "sm",
              importance: "clear",
              disabled: !f.currentMonth,
              type: "button",
              "aria-selected": e(r) ? f.text === e(r) && f.currentMonth : f.selected,
              "aria-label": e(v)(f),
              role: "option",
              onClick: ($) => e(h)(f),
              onKeydown: l[0] || (l[0] = ($) => e(_)($))
            }, {
              default: k(() => [
                W(P(f.text), 1)
              ]),
              _: 2
            }, 1032, ["disabled", "class", "aria-selected", "aria-label", "onClick"])
          ]))), 128))
        ]))), 128))
      ])
    ]));
  }
}, ye = { class: "d-datepicker__hd" }, $e = { class: "d-datepicker__bd" }, we = {
  __name: "datepicker",
  props: {
    /**
       * Selected date
       *
       * @type {Date}
       */
    selectedDate: {
      type: Date,
      default: () => /* @__PURE__ */ new Date()
    }
  },
  emits: [
    /**
       * Event fired when a date is selected
       *
       * @event selected-date
       * @type {Date}
       */
    "selected-date",
    /**
       * Event fired when user presses the esc key
       *
       * @event close-datepicker
       */
    "close-datepicker"
  ],
  setup(d) {
    const o = b([]);
    function s(t) {
      o.value = t;
    }
    return V(() => {
      const t = j();
      fe(D(t.proxy.$el), "datepicker");
    }), (t, n) => (E(), G(e(R), {
      class: "d-datepicker",
      gap: "400"
    }, {
      default: k(() => [
        M("div", ye, [
          i(De, {
            ref: "monthYearPicker",
            "selected-date": d.selectedDate,
            onCalendarDays: s,
            onFocusFirstDay: n[0] || (n[0] = (r) => t.$refs.calendar.focusFirstDay()),
            onFocusLastDay: n[1] || (n[1] = (r) => t.$refs.calendar.focusLastDay()),
            onCloseDatepicker: n[2] || (n[2] = (r) => t.$emit("close-datepicker"))
          }, null, 8, ["selected-date"])
        ]),
        M("div", $e, [
          i(he, {
            ref: "calendar",
            "calendar-days": o.value,
            onSelectDate: n[3] || (n[3] = (r) => t.$emit("selected-date", r)),
            onFocusMonthYearPicker: n[4] || (n[4] = (r) => t.$refs.monthYearPicker.focusMonthYearPicker()),
            onCloseDatepicker: n[5] || (n[5] = (r) => t.$emit("close-datepicker")),
            onGoToNextMonth: n[6] || (n[6] = (r) => t.$refs.monthYearPicker.goToNextMonth()),
            onGoToPrevMonth: n[7] || (n[7] = (r) => t.$refs.monthYearPicker.goToPrevMonth())
          }, null, 8, ["calendar-days"])
        ])
      ]),
      _: 1
    }));
  }
};
export {
  we as default
};
//# sourceMappingURL=datepicker.js.map
