import { l as last_1, u as useWidgetsCore, j as jsxRuntimeExports, a as useFeatures, m as ms, w as workgridIcon, Q as QueryClient, I as I18nextProvider, i as i18n, b as QueryClientProvider, W as WidgetsCoreContextProvider, c as WidgetsLoggerContextProvider, F as FeaturesContextProvider } from "./root-CqOwVDsl.js";
import { r as reactExports } from "./index-BKyMaBlO.js";
import { E as ErrorBoundary, a as Error$1, L as Loader } from "./loader-5BGkTPnX.js";
import { h as _baseUnary, g as getDefaultExportFromCjs, l as _baseRest, aP as isArrayLikeObject_1, Q as z } from "./index-cxtq9t-h.js";
import { u as useQuery } from "./useQuery-Dh-llrQk.js";
import { a as _SetCache, b as _cacheHas, _ as _baseIteratee } from "./_baseIteratee-DoMi95p-.js";
import { _ as _arrayMap, b as _baseFlatten } from "./_flatRest-9_JfLX6J.js";
function baseFindIndex$1(array, predicate, fromIndex, fromRight) {
  var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
  while (fromRight ? index-- : ++index < length) {
    if (predicate(array[index], index, array)) {
      return index;
    }
  }
  return -1;
}
var _baseFindIndex = baseFindIndex$1;
function baseIsNaN$1(value) {
  return value !== value;
}
var _baseIsNaN = baseIsNaN$1;
function strictIndexOf$1(array, value, fromIndex) {
  var index = fromIndex - 1, length = array.length;
  while (++index < length) {
    if (array[index] === value) {
      return index;
    }
  }
  return -1;
}
var _strictIndexOf = strictIndexOf$1;
var baseFindIndex = _baseFindIndex, baseIsNaN = _baseIsNaN, strictIndexOf = _strictIndexOf;
function baseIndexOf$1(array, value, fromIndex) {
  return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
}
var _baseIndexOf = baseIndexOf$1;
var baseIndexOf = _baseIndexOf;
function arrayIncludes$1(array, value) {
  var length = array == null ? 0 : array.length;
  return !!length && baseIndexOf(array, value, 0) > -1;
}
var _arrayIncludes = arrayIncludes$1;
function arrayIncludesWith$1(array, value, comparator) {
  var index = -1, length = array == null ? 0 : array.length;
  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}
var _arrayIncludesWith = arrayIncludesWith$1;
var SetCache = _SetCache, arrayIncludes = _arrayIncludes, arrayIncludesWith = _arrayIncludesWith, arrayMap = _arrayMap, baseUnary = _baseUnary, cacheHas = _cacheHas;
var LARGE_ARRAY_SIZE = 200;
function baseDifference$1(array, values, iteratee, comparator) {
  var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length;
  if (!length) {
    return result;
  }
  if (iteratee) {
    values = arrayMap(values, baseUnary(iteratee));
  }
  if (comparator) {
    includes = arrayIncludesWith;
    isCommon = false;
  } else if (values.length >= LARGE_ARRAY_SIZE) {
    includes = cacheHas;
    isCommon = false;
    values = new SetCache(values);
  }
  outer:
    while (++index < length) {
      var value = array[index], computed = iteratee == null ? value : iteratee(value);
      value = comparator || value !== 0 ? value : 0;
      if (isCommon && computed === computed) {
        var valuesIndex = valuesLength;
        while (valuesIndex--) {
          if (values[valuesIndex] === computed) {
            continue outer;
          }
        }
        result.push(value);
      } else if (!includes(values, computed, comparator)) {
        result.push(value);
      }
    }
  return result;
}
var _baseDifference = baseDifference$1;
var baseDifference = _baseDifference, baseFlatten = _baseFlatten, baseIteratee = _baseIteratee, baseRest = _baseRest, isArrayLikeObject = isArrayLikeObject_1, last = last_1;
var differenceBy = baseRest(function(array, values) {
  var iteratee = last(values);
  if (isArrayLikeObject(iteratee)) {
    iteratee = void 0;
  }
  return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee)) : [];
});
var differenceBy_1 = differenceBy;
const differenceBy$1 = /* @__PURE__ */ getDefaultExportFromCjs(differenceBy_1);
const CurrentSpaceContext = reactExports.createContext(void 0);
function CurrentSpaceContextProvider(props) {
  const core = useWidgetsCore();
  const state = reactExports.useState(props.initialSpaceId);
  const [currentSpaceId, setCurrentSpaceId] = state;
  reactExports.useEffect(() => {
    core.emit("space", currentSpaceId);
  }, [currentSpaceId]);
  reactExports.useEffect(() => {
    core.on("space", setCurrentSpaceId);
    return () => {
      core.off("space", setCurrentSpaceId);
    };
  }, [core]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(CurrentSpaceContext.Provider, { value: state, children: props.children });
}
function useCurrentSpace() {
  const context = reactExports.useContext(CurrentSpaceContext);
  if (context === void 0) {
    throw new Error("useCurrentSpace must be used within a CurrentSpaceContext.Provider");
  }
  return context;
}
const BriefingContext = reactExports.createContext(void 0);
function BriefingProvider(props) {
  const core = useWidgetsCore();
  const features = useFeatures();
  const spaceId = useCurrentSpace()[0];
  const [currentNotifications, setCurrentNotifications] = reactExports.useState([]);
  const [fetchedNotifications, setFetchedNotifications] = reactExports.useState([]);
  const fetchedNotificationsRef = reactExports.useRef(fetchedNotifications);
  fetchedNotificationsRef.current = fetchedNotifications;
  const flushNotifications = reactExports.useCallback(() => {
    setCurrentNotifications(fetchedNotificationsRef.current);
  }, [setCurrentNotifications]);
  const setNotifications = reactExports.useCallback(
    (notifications) => {
      setCurrentNotifications(notifications);
      setFetchedNotifications(notifications);
    },
    [setCurrentNotifications, setFetchedNotifications]
  );
  const pendingNotifications = reactExports.useMemo(() => {
    return differenceBy$1(fetchedNotifications, currentNotifications, "metadata.id");
  }, [currentNotifications, fetchedNotifications]);
  const [instances, setInstances] = reactExports.useState([]);
  const unregister = reactExports.useCallback(
    (instanceId) => {
      setInstances((instances2) => {
        return instances2.includes(instanceId) ? instances2.filter((id) => id !== instanceId) : instances2;
      });
    },
    [setInstances]
  );
  const register = reactExports.useCallback(
    (instanceId) => {
      setInstances((instances2) => {
        return instances2.includes(instanceId) ? instances2 : [...instances2, instanceId];
      });
      return unregister.bind(null, instanceId);
    },
    [setInstances, unregister]
  );
  const value = reactExports.useMemo(
    () => ({
      currentNotifications,
      pendingNotifications,
      flushNotifications,
      setNotifications,
      unregister,
      register
    }),
    [currentNotifications, pendingNotifications, unregister, register]
  );
  const realTimeNotificationsEnabled = features["real-time-notifications"] !== false;
  const realTimeNotificationsInterval = ms(String(features["real-time-notifications-interval"] || "5 minutes"));
  const realTimeNotificationsStaleTime = Math.min(realTimeNotificationsInterval, ms("10 seconds"));
  useQuery({
    enabled: realTimeNotificationsEnabled && spaceId != null && instances.length > 0,
    queryKey: ["briefing-notifications", spaceId],
    queryFn: async () => {
      if (!spaceId) return;
      const [{ notifications: todo }, { notifications: toknow }] = await Promise.all([
        core.getNotifications({ spaceId, location: "todo" }),
        core.getNotifications({ spaceId, location: "toknow", viewed: false })
      ]);
      setFetchedNotifications([...todo, ...toknow]);
      return null;
    },
    refetchOnWindowFocus: true,
    refetchOnReconnect: true,
    // skip initial fetch
    initialData: () => currentNotifications,
    // poll for changes
    refetchInterval: realTimeNotificationsInterval,
    // defer fetching
    staleTime: realTimeNotificationsStaleTime
  });
  const notificationStateById = reactExports.useRef();
  notificationStateById.current ?? (notificationStateById.current = (() => {
    const store = /* @__PURE__ */ new Map();
    function get(...args) {
      return store.get(...args);
    }
    function set(...args) {
      store.set(...args);
      const unactioned = [...store.values()].filter((state) => state === "unactioned").length;
      const unviewed = [...store.values()].filter((state) => state === "unviewed").length;
      core.emit("badge", unactioned || !!unviewed);
    }
    function clear() {
      store.clear();
      core.emit("badge", false);
    }
    const viewNotification = core.viewNotification.bind(core);
    core.viewNotification = (options) => {
      if (store.get(options.notificationId) === "unviewed") {
        set(options.notificationId, "viewed");
      }
      return viewNotification(options);
    };
    const actionNotification = core.actionNotification.bind(core);
    core.actionNotification = (options) => {
      if (store.get(options.notificationId) === "unactioned") {
        set(options.notificationId, "actioned");
      }
      return actionNotification(options);
    };
    const deleteNotification = core.deleteNotification.bind(core);
    core.deleteNotification = (options) => {
      set(options.notificationId, "deleted");
      return deleteNotification(options);
    };
    return { get, set, clear };
  })());
  reactExports.useEffect(() => {
    var _a;
    setCurrentNotifications((currentNotifications2) => currentNotifications2.length > 0 ? [] : currentNotifications2);
    setFetchedNotifications((fetchedNotifications2) => fetchedNotifications2.length > 0 ? [] : fetchedNotifications2);
    setInstances((instances2) => instances2.length > 0 ? [] : instances2);
    (_a = notificationStateById.current) == null ? void 0 : _a.clear();
  }, [spaceId]);
  reactExports.useEffect(() => {
    var _a;
    if (instances.length === 0) {
      setCurrentNotifications((currentNotifications2) => currentNotifications2.length > 0 ? [] : currentNotifications2);
      setFetchedNotifications((fetchedNotifications2) => fetchedNotifications2.length > 0 ? [] : fetchedNotifications2);
      (_a = notificationStateById.current) == null ? void 0 : _a.clear();
    }
  }, [instances.length]);
  reactExports.useEffect(() => {
    var _a, _b;
    for (const notification of currentNotifications) {
      if (((_a = notificationStateById.current) == null ? void 0 : _a.get(notification.metadata.id)) != null) continue;
      const state = notification.metadata.location === "todo" ? "unactioned" : "unviewed";
      (_b = notificationStateById.current) == null ? void 0 : _b.set(notification.metadata.id, state);
    }
  }, [currentNotifications]);
  reactExports.useEffect(() => {
    var _a, _b;
    for (const notification of fetchedNotifications) {
      if (((_a = notificationStateById.current) == null ? void 0 : _a.get(notification.metadata.id)) != null) continue;
      const state = notification.metadata.location === "todo" ? "unactioned" : "unviewed";
      (_b = notificationStateById.current) == null ? void 0 : _b.set(notification.metadata.id, state);
    }
  }, [fetchedNotifications]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(BriefingContext.Provider, { value, children: props.children });
}
function useBriefing() {
  const context = reactExports.useContext(BriefingContext);
  if (context === void 0) {
    throw new Error("useBriefing must be used within a BriefingContext.Provider");
  }
  return context;
}
const Conversation = reactExports.lazy(() => import("./conversation-6NM6SWP2.js"));
function Root(props) {
  const { t } = i18n;
  const icon = z.string().trim().min(1).catch(workgridIcon).parse(props.config.icon);
  const prompt = z.string().trim().min(1).catch("Workgrid Daily Briefing").parse(props.config.prompt);
  const queryClient = reactExports.useRef();
  queryClient.current ?? (queryClient.current = new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: Infinity,
        // Queries should never be refetched
        // Failed queries are not subject to staleTime, disable refetch
        refetchOnReconnect: false,
        refetchOnWindowFocus: false
      }
    }
  }));
  return /* @__PURE__ */ jsxRuntimeExports.jsx(I18nextProvider, { i18n, children: /* @__PURE__ */ jsxRuntimeExports.jsx(QueryClientProvider, { client: queryClient.current, children: /* @__PURE__ */ jsxRuntimeExports.jsx(WidgetsCoreContextProvider, { core: props.core, children: /* @__PURE__ */ jsxRuntimeExports.jsx(WidgetsLoggerContextProvider, { logger: props.logger, children: /* @__PURE__ */ jsxRuntimeExports.jsx(FeaturesContextProvider, { features: props.config.features, children: /* @__PURE__ */ jsxRuntimeExports.jsx(CurrentSpaceContextProvider, { initialSpaceId: props.config.space, children: /* @__PURE__ */ jsxRuntimeExports.jsx(BriefingProvider, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    ErrorBoundary,
    {
      fallbackRender: ({ error, resetErrorBoundary }) => /* @__PURE__ */ jsxRuntimeExports.jsx(Error$1, { error, reset: resetErrorBoundary, supportUrl: props.config.supportUrl }),
      onReset: () => {
        var _a;
        return (_a = queryClient.current) == null ? void 0 : _a.clear();
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(reactExports.Suspense, { fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(Loader, { label: t("loading") }), children: /* @__PURE__ */ jsxRuntimeExports.jsx(Conversation, { icon, prompt }) })
    }
  ) }) }) }) }) }) }) });
}
const root = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Root
}, Symbol.toStringTag, { value: "Module" }));
export {
  _baseFindIndex as _,
  useCurrentSpace as a,
  root as r,
  useBriefing as u
};
//# sourceMappingURL=root-COIPhJRq.js.map
