import { jsx as r, jsxs as s, Fragment as X } from "react/jsx-runtime";
import ee, { useState as h, useCallback as F, useEffect as ae, useMemo as H } from "react";
import { u as re, b as te, c as se, d as ne, e as le, f as oe, R as W, g as O, C as ie, h as ce, i as de, j as ue, k as _, l as R, m as me, n as fe, o as N } from "./index-CPyEi9gS.js";
import { a as S, L as G, P as he, b as pe, B as j, d as ge, e as V, f as ve } from "./switch-Dkx2qEOr.js";
import "./index-CuHybtft.js";
import { C as be } from "./chevrons-up-down-DSvLu4Ye.js";
function we(n = {}) {
  var C, A, E, L;
  const { authToken: c, tokenProps: e } = re(), p = n.enabled ?? !0, d = (c == null ? void 0 : c.accessToken) ?? null, u = (e == null ? void 0 : e.apiServiceUrl) ?? null, [I, k] = h(!1), [y, b] = h(!1), [m, g] = h(!1), [T, o] = h(null), [v, w] = h(null), P = v || {
    tz: ((A = (C = e == null ? void 0 : e.params) == null ? void 0 : C.calendarContext) == null ? void 0 : A.tz) || null,
    weekStart: ((L = (E = e == null ? void 0 : e.params) == null ? void 0 : E.calendarContext) == null ? void 0 : L.weekStart) ?? null
  }, f = F(async () => {
    if (!(!p || !d || !u)) {
      k(!0), o(null);
      try {
        const l = await fetch(`${u}/v1/user-preferences/calendar`, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${d}`
          }
        });
        if (!l.ok) {
          const i = await l.json().catch(() => ({}));
          throw new Error(i.error || "Failed to fetch preferences");
        }
        const t = await l.json();
        w({
          tz: t.tz,
          weekStart: t.weekStart,
          source: t.source,
          isInherited: t.isInherited,
          userHasPrefs: t.userHasPrefs,
          inherited: t.inherited
        });
      } catch (l) {
        const t = l instanceof Error ? l.message : "Unknown error";
        o(t);
      } finally {
        k(!1);
      }
    }
  }, [d, u, p]);
  ae(() => {
    p && f();
  }, [p, f]);
  const z = F(
    async (l) => {
      if (!d || !u)
        return o("Not authenticated"), !1;
      b(!0), o(null);
      try {
        const t = await fetch(`${u}/v1/user-preferences/calendar`, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${d}`
          },
          body: JSON.stringify(l)
        });
        if (!t.ok) {
          const i = await t.json().catch(() => ({}));
          throw new Error(i.error || "Failed to update preferences");
        }
        return await f(), !0;
      } catch (t) {
        const i = t instanceof Error ? t.message : "Unknown error";
        return o(i), !1;
      } finally {
        b(!1);
      }
    },
    [d, u, f]
  ), x = F(async () => {
    if (!d || !u)
      return o("Not authenticated"), !1;
    g(!0), o(null);
    try {
      const l = await fetch(`${u}/v1/user-preferences/calendar`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${d}`
        }
      });
      if (!l.ok) {
        const i = await l.json().catch(() => ({}));
        throw new Error(i.error || "Failed to clear preferences");
      }
      const t = await l.text();
      if (t)
        try {
          const i = JSON.parse(t);
          return w({
            tz: i.tz,
            weekStart: i.weekStart,
            source: i.source,
            isInherited: i.isInherited ?? !0,
            userHasPrefs: !1,
            inherited: i.inherited
          }), !0;
        } catch {
        }
      return await f(), !0;
    } catch (l) {
      const t = l instanceof Error ? l.message : "Unknown error";
      return o(t), !1;
    } finally {
      g(!1);
    }
  }, [d, u, f]);
  return {
    preferences: P,
    isLoading: I,
    isSaving: y,
    isClearing: m,
    error: T,
    updatePreferences: z,
    clearPreferences: x,
    refetch: f
  };
}
const D = [
  { value: "America/New_York", label: "Eastern Time (US & Canada)" },
  { value: "America/Chicago", label: "Central Time (US & Canada)" },
  { value: "America/Denver", label: "Mountain Time (US & Canada)" },
  { value: "America/Los_Angeles", label: "Pacific Time (US & Canada)" },
  { value: "America/Phoenix", label: "Arizona" },
  { value: "America/Anchorage", label: "Alaska" },
  { value: "Pacific/Honolulu", label: "Hawaii" },
  { value: "Europe/London", label: "London" },
  { value: "Europe/Paris", label: "Paris, Berlin, Rome" },
  { value: "Asia/Tokyo", label: "Tokyo" },
  { value: "Asia/Shanghai", label: "Beijing, Shanghai" },
  { value: "Asia/Kolkata", label: "Mumbai, New Delhi" },
  { value: "Australia/Sydney", label: "Sydney" },
  { value: "UTC", label: "UTC" }
], K = [
  { value: 0, label: "Sunday" },
  { value: 1, label: "Monday" },
  { value: 6, label: "Saturday" }
], Z = "text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";
function Se() {
  try {
    const n = Intl;
    if (n.supportedValuesOf)
      return n.supportedValuesOf("timeZone");
  } catch {
  }
  return D.map((n) => n.value);
}
function ye(n) {
  switch (n) {
    case "tenant":
      return "tenant";
    case "organization":
      return "organization";
    case "system":
      return "system";
    default:
      return "default";
  }
}
function J(n) {
  const c = D.find((e) => e.value === n);
  return c ? c.label : n;
}
function xe(n) {
  const c = K.find((e) => e.value === n);
  return c ? c.label : String(n);
}
function Ae({
  open: n,
  onOpenChange: c
}) {
  var $, B, M;
  const {
    preferences: e,
    isLoading: p,
    isSaving: d,
    isClearing: u,
    updatePreferences: I,
    clearPreferences: k
  } = we({ enabled: n }), y = e.tz || (($ = e.inherited) == null ? void 0 : $.tz) || Intl.DateTimeFormat().resolvedOptions().timeZone, b = e.weekStart ?? ((B = e.inherited) == null ? void 0 : B.weekStart) ?? 1, [m, g] = h(!e.userHasPrefs), [T, o] = h(!1), [v, w] = h(
    y
  ), [P, f] = h(
    b
  ), [z, x] = h(!1), C = H(() => Se(), []), A = H(
    () => C.filter(
      (a) => !D.some((Q) => Q.value === a)
    ),
    [C]
  ), E = H(() => J(v), [v]), L = e.inherited ? J(e.inherited.tz) : "UTC", l = e.inherited ? xe(e.inherited.weekStart) : "Monday", t = ye(
    (M = e.inherited) == null ? void 0 : M.source
  );
  ee.useEffect(() => {
    if (!n) {
      o(!1);
      return;
    }
    T || (e.userHasPrefs !== void 0 && g(!e.userHasPrefs), w(y), f(b));
  }, [
    n,
    T,
    e.userHasPrefs,
    y,
    b
  ]);
  const i = async () => {
    if (p) {
      N.error("Preferences are still loading. Please try again.");
      return;
    }
    m ? await k() ? (N.success(
      "Now using default settings. Please refresh the page to apply changes.",
      { duration: 5e3 }
    ), c(!1)) : N.error("Failed to save preferences. Please try again.") : await I({
      tz: v,
      weekStart: P
    }) ? (N.success(
      "Preferences saved. Please refresh the page to apply changes.",
      { duration: 5e3 }
    ), c(!1)) : N.error("Failed to save preferences. Please try again.");
  }, Y = () => {
    c(!1);
  }, U = d || u, q = U || p;
  return /* @__PURE__ */ r(te, { open: n, onOpenChange: c, children: /* @__PURE__ */ s(se, { className: "rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control", children: [
    /* @__PURE__ */ s(ne, { children: [
      /* @__PURE__ */ r(le, { className: "text-[15px]", children: "Calendar preferences" }),
      /* @__PURE__ */ r(oe, { className: "text-[13px] leading-5", children: "Set your timezone and week-start for date calculations and displays." })
    ] }),
    /* @__PURE__ */ s("div", { className: "space-y-4 py-1", children: [
      /* @__PURE__ */ s(
        W,
        {
          value: m ? "defaults" : "custom",
          onValueChange: (a) => {
            o(!0), g(a === "defaults");
          },
          className: "space-y-0.5",
          children: [
            /* @__PURE__ */ s(
              "label",
              {
                htmlFor: "mode-defaults",
                className: S(
                  "flex cursor-pointer items-start gap-2 rounded-control px-2 py-1.5 hover:bg-muted/50",
                  m && "bg-muted/50"
                ),
                onClick: () => {
                  o(!0), g(!0);
                },
                children: [
                  /* @__PURE__ */ r(
                    O,
                    {
                      value: "defaults",
                      id: "mode-defaults",
                      className: "mt-0.5"
                    }
                  ),
                  /* @__PURE__ */ s("div", { className: "flex-1 min-w-0", children: [
                    /* @__PURE__ */ s("p", { className: "text-[13px] font-medium text-foreground", children: [
                      "Use ",
                      t,
                      " defaults"
                    ] }),
                    /* @__PURE__ */ s("p", { className: "text-[12px] text-muted-foreground", children: [
                      L,
                      ", week starts ",
                      l
                    ] })
                  ] })
                ]
              }
            ),
            /* @__PURE__ */ s(
              "label",
              {
                htmlFor: "mode-custom",
                className: S(
                  "flex cursor-pointer items-start gap-2 rounded-control px-2 py-1.5 hover:bg-muted/50",
                  !m && "bg-muted/50"
                ),
                onClick: () => {
                  o(!0), g(!1);
                },
                children: [
                  /* @__PURE__ */ r(
                    O,
                    {
                      value: "custom",
                      id: "mode-custom",
                      className: "mt-0.5"
                    }
                  ),
                  /* @__PURE__ */ r("p", { className: "flex-1 text-[13px] font-medium text-foreground", children: "Use custom settings" })
                ]
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ s(
        "div",
        {
          className: S(
            "space-y-4 border-t border-border/60 pt-4 transition-opacity",
            m && "pointer-events-none opacity-50"
          ),
          children: [
            /* @__PURE__ */ s("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ r(G, { className: Z, children: "Timezone" }),
              /* @__PURE__ */ s(
                he,
                {
                  open: z,
                  onOpenChange: x,
                  modal: !0,
                  children: [
                    /* @__PURE__ */ r(pe, { asChild: !0, children: /* @__PURE__ */ s(
                      j,
                      {
                        variant: "outline",
                        size: "xs",
                        role: "combobox",
                        "aria-expanded": z,
                        className: "w-full justify-between text-[12px] font-normal",
                        disabled: m,
                        children: [
                          /* @__PURE__ */ r("span", { className: "truncate", children: E }),
                          /* @__PURE__ */ r(be, { className: "ml-2 h-3.5 w-3.5 shrink-0 opacity-50" })
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ r(
                      ge,
                      {
                        className: "z-50 w-[--radix-popover-trigger-width] p-0",
                        align: "start",
                        children: /* @__PURE__ */ s(ie, { className: "overflow-visible", children: [
                          /* @__PURE__ */ r(ce, { placeholder: "Search timezones…" }),
                          /* @__PURE__ */ s(de, { children: [
                            /* @__PURE__ */ r(ue, { children: "No timezone found." }),
                            /* @__PURE__ */ r(_, { heading: "Common", children: D.map((a) => /* @__PURE__ */ s(
                              R,
                              {
                                value: `${a.value} ${a.label}`,
                                onSelect: () => {
                                  o(!0), w(a.value), x(!1);
                                },
                                children: [
                                  /* @__PURE__ */ r(
                                    V,
                                    {
                                      className: S(
                                        "h-3.5 w-3.5",
                                        v === a.value ? "opacity-100" : "opacity-0"
                                      )
                                    }
                                  ),
                                  /* @__PURE__ */ r("span", { className: "flex-1", children: a.label }),
                                  /* @__PURE__ */ r("span", { className: "text-[11px] text-muted-foreground", children: a.value })
                                ]
                              },
                              a.value
                            )) }),
                            /* @__PURE__ */ r(me, {}),
                            /* @__PURE__ */ r(_, { heading: "All timezones", children: A.map((a) => /* @__PURE__ */ s(
                              R,
                              {
                                value: a,
                                onSelect: () => {
                                  o(!0), w(a), x(!1);
                                },
                                children: [
                                  /* @__PURE__ */ r(
                                    V,
                                    {
                                      className: S(
                                        "h-3.5 w-3.5",
                                        v === a ? "opacity-100" : "opacity-0"
                                      )
                                    }
                                  ),
                                  a
                                ]
                              },
                              a
                            )) })
                          ] })
                        ] })
                      }
                    )
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ s("div", { className: "space-y-1.5", children: [
              /* @__PURE__ */ r(G, { className: Z, children: "Week starts on" }),
              /* @__PURE__ */ r(
                W,
                {
                  value: String(P),
                  onValueChange: (a) => {
                    o(!0), f(Number(a));
                  },
                  className: "flex gap-4",
                  disabled: m,
                  children: K.map((a) => /* @__PURE__ */ s(
                    "label",
                    {
                      htmlFor: `week-start-${a.value}`,
                      className: S(
                        "flex cursor-pointer items-center gap-2 text-[13px]",
                        m && "cursor-not-allowed"
                      ),
                      children: [
                        /* @__PURE__ */ r(
                          O,
                          {
                            value: String(a.value),
                            id: `week-start-${a.value}`,
                            disabled: m
                          }
                        ),
                        a.label
                      ]
                    },
                    a.value
                  ))
                }
              )
            ] })
          ]
        }
      )
    ] }),
    /* @__PURE__ */ s(fe, { children: [
      /* @__PURE__ */ r(
        j,
        {
          variant: "outline",
          size: "xs",
          onClick: Y,
          disabled: U,
          children: "Cancel"
        }
      ),
      /* @__PURE__ */ r(j, { size: "xs", onClick: i, disabled: q, children: U ? /* @__PURE__ */ s(X, { children: [
        /* @__PURE__ */ r(ve, { className: "h-3.5 w-3.5 animate-spin" }),
        "Saving…"
      ] }) : "Save" })
    ] })
  ] }) });
}
export {
  Ae as C
};
