import { useState as A, useRef as E, useCallback as _, useEffect as w } from "react";
const N = () => window.__notificationSDK?.client, T = ({
  preferences: t,
  onPreferencesChange: f,
  onError: e
}) => {
  const n = N(), [c, i] = A(!1), [a, l] = A(null), h = E(), g = E({}), D = _(
    (m, S) => {
      try {
        l(null);
        const r = { ...t }, o = m.split(".");
        let p = r;
        for (let s = 0; s < o.length - 1; s++)
          p[o[s]] === void 0 && (p[o[s]] = {}), p = p[o[s]];
        p[o[o.length - 1]] = S, f(r), g.current[m] = S, h.current && clearTimeout(h.current), i(!0), h.current = setTimeout(async () => {
          try {
            if (!n)
              throw new Error("Notification client not available");
            const s = window.__notificationSDK?.config;
            if (!s)
              throw new Error("SDK configuration not available");
            const { subscriberId: u, tenantId: v, environmentId: y } = s;
            if (!u || !v || !y)
              throw new Error(
                "SubscriberId, TenantId or EnvironmentId not available in SDK configuration."
              );
            if (m.startsWith("deliverySchedule.")) {
              const d = {
                isEnabled: r.deliverySchedule.enabled || !1
              };
              r.deliverySchedule.weeklySchedule && (d.weeklySchedule = r.deliverySchedule.weeklySchedule), await n.preferences.updateSchedule(
                v,
                u,
                d,
                y
              );
            } else {
              const d = {
                emailEnabled: r.channels.email,
                pushEnabled: r.channels.push,
                inAppEnabled: r.channels.inApp,
                smsEnabled: r.channels.sms
              };
              r.subscriptions.length > 0 && (d.categories = {}, r.subscriptions.forEach((b) => {
                d.categories[b.workflowId] = {
                  emailEnabled: b.channels.email,
                  pushEnabled: b.channels.push,
                  inAppEnabled: b.channels.inApp,
                  smsEnabled: b.channels.sms
                };
              })), await n.preferences.update(v, u, d);
            }
            g.current = {}, l(null);
          } catch (s) {
            const u = s instanceof Error ? s : new Error("Failed to save preferences");
            process.env.NODE_ENV, l(u), e?.(u);
          } finally {
            i(!1);
          }
        }, 500);
      } catch (r) {
        const o = r instanceof Error ? r : new Error("Failed to update preference");
        l(o), e?.(o), i(!1);
      }
    },
    [t, f, n, e]
  );
  return w(() => () => {
    h.current && clearTimeout(h.current);
  }, []), {
    updatePreference: D,
    isSaving: c,
    error: a
  };
}, j = (t) => !(!t || typeof t != "object" || ["notificationId", "channel", "renderedContent", "read", "archived"].filter((n) => !(n in t)).length > 0 || typeof t.channel != "string" || typeof t.read != "boolean" || typeof t.archived != "boolean" || typeof t.renderedContent != "object" || t.renderedContent === null), R = (t, f, e) => ({
  type: "custom",
  label: t.label,
  icon: void 0,
  handler: async () => {
    try {
      if (t.url) {
        const n = t.target || "_self";
        window.open(t.url, n);
      }
      t.markAsReadOnClick;
    } catch (n) {
      throw n;
    }
  }
}), I = () => {
  const t = (e, n) => {
    if (!e || typeof e != "object")
      return { subject: "", body: "" };
    let c = "", i = "";
    return e.push ? (c = e.push.title || "", i = e.push.body || "") : e.email ? (c = e.email.subject || "", i = e.email.html || e.email.text || "") : e.in_app ? (c = e.in_app.title || "", i = e.in_app.message || "") : e.sms ? (c = "SMS", i = e.sms.message || "") : n === "in_app" ? (c = e.title || "", i = e.message || "") : (c = e.title || e.subject || "", i = e.message || e.body || e.text || ""), { subject: c, body: i };
  }, f = (e, n, c) => {
    if (!e) return [];
    const i = [];
    if (Array.isArray(e))
      return e.forEach((a) => {
        i.push(R(a, n || "", c));
      }), i;
    if (e.primary) {
      const a = e.primary;
      i.push({
        type: "custom",
        label: a.label || "Primary Action",
        icon: void 0,
        handler: async (l) => {
          a.url && window.open(a.url, "_self");
        }
      });
    }
    if (e.secondary) {
      const a = e.secondary;
      i.push({
        type: "custom",
        label: a.label || "Secondary Action",
        icon: void 0,
        handler: async (l) => {
          a.url && window.open(a.url, "_self");
        }
      });
    }
    return i;
  };
  return {
    toWidgetNotification(e) {
      const { subject: n, body: c } = t(
        e.renderedContent,
        e.channel
      );
      return {
        id: e.notificationId,
        subject: n || "Notification",
        body: c || "",
        isRead: e.read,
        isArchived: e.archived,
        timestamp: e.createdAt ? new Date(e.createdAt) : /* @__PURE__ */ new Date(),
        tags: [],
        actions: f(
          e.renderedContent?.actions || e.actions
        ),
        metadata: {
          channel: e.channel,
          renderedContent: e.renderedContent
        }
      };
    },
    toWidgetNotificationFromWebSocket(e) {
      if (!j(e)) {
        const i = e?.renderedContent && typeof e.renderedContent == "object" ? e.renderedContent : {}, { subject: a, body: l } = t(
          i,
          e?.channel
        );
        return {
          id: e?.notificationId || `notification-${Date.now()}`,
          subject: a || "Notification",
          body: l || "",
          isRead: e?.read || !1,
          isArchived: e?.archived || !1,
          timestamp: e?.createdAt ? new Date(e.createdAt) : /* @__PURE__ */ new Date(),
          tags: [],
          actions: [],
          metadata: {
            channel: e?.channel || "in_app",
            renderedContent: i
          }
        };
      }
      const { subject: n, body: c } = t(e.renderedContent, e.channel);
      return {
        id: e.notificationId,
        subject: n || "Notification",
        body: c || "",
        isRead: e.read || !1,
        isArchived: e.archived || !1,
        timestamp: e.createdAt ? new Date(e.createdAt) : /* @__PURE__ */ new Date(),
        tags: [],
        actions: f(
          e.renderedContent?.actions || e.actions,
          e.notificationId
        ),
        metadata: {
          channel: e.channel,
          renderedContent: e.renderedContent
        }
      };
    },
    validateWebSocketPayload: j
  };
};
export {
  I as c,
  T as u
};
//# sourceMappingURL=hooks-S0z2_-4B.js.map
