import { useSessionCheck, AppErrorBoundary, SidebarProvider, ElevasisSystemsProvider, useElevasisSystems, AppShellContainer, Sidebar, AppShellRightSideContainer, AppShellRightSideOuterContainer, SystemShell, ElevasisUIProvider } from '../chunk-CPIQ5GXG.js';
import '../chunk-NZ2F5RQ4.js';
import '../chunk-OJJK27GC.js';
import '../chunk-ZTWA5H77.js';
import '../chunk-AUDNF2Q7.js';
import '../chunk-6M6OLGQY.js';
import '../chunk-MKH2KOAO.js';
import '../chunk-7Q5THR43.js';
import '../chunk-SJHM4WDG.js';
import '../chunk-GMXGDO3I.js';
import '../chunk-S3XR4II4.js';
import { useInitialization } from '../chunk-6DO4PE3O.js';
import '../chunk-DD3CCMCZ.js';
import '../chunk-M7WWRZ5Z.js';
import '../chunk-E6NSKXYN.js';
import { TanStackRouterBridge, ScrollToTop } from '../chunk-2IFYDILW.js';
import '../chunk-Q7DJKLEN.js';
import '../chunk-HENXLGVD.js';
import '../chunk-I3CFGE3N.js';
import '../chunk-RNP5R5I3.js';
import '../chunk-W2SFTXMT.js';
import { listAllSystems } from '../chunk-XOPLS4S6.js';
import '../chunk-FVOMKZ7S.js';
import '../chunk-KRWALB24.js';
import '../chunk-2FTX4WO2.js';
import '../chunk-MQZE7SUI.js';
import '../chunk-TVTSASST.js';
import '../chunk-BRJ3QZ4E.js';
import '../chunk-I2KLQ2HA.js';
import { useMemo, useCallback, useEffect } from 'react';
import { useLocation, Outlet, useNavigate, RouterProvider } from '@tanstack/react-router';
import { Notifications } from '@mantine/notifications';
import { useAuth } from '@workos-inc/authkit-react';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useComputedColorScheme } from '@mantine/core';

var DEFAULT_PRESET = "default";
var DEFAULT_COLOR_SCHEME = "dark";
function AppWithStore({ config }) {
  const themePreset = config.store?.useThemePreset() ?? DEFAULT_PRESET;
  const themeColorScheme = config.store?.useThemeColorScheme() ?? DEFAULT_COLOR_SCHEME;
  const handleApiError = useCallback(
    (endpoint, error, details) => {
      config.onApiError?.(endpoint, error, details);
    },
    [config.onApiError]
  );
  if (!config.auth.clientId) {
    if (config.MissingEnvNotice) {
      return /* @__PURE__ */ jsx(config.MissingEnvNotice, {});
    }
    return null;
  }
  const assembledTheme = {
    preset: themePreset,
    colorScheme: themeColorScheme,
    ...config.theme?.presets ? { presets: config.theme.presets } : {},
    ...config.theme?.background !== void 0 ? { background: config.theme.background } : {},
    ...config.theme?.loader !== void 0 ? { loader: config.theme.loader } : {}
  };
  return /* @__PURE__ */ jsx(
    ElevasisUIProvider,
    {
      theme: assembledTheme,
      auth: {
        mode: "authkit",
        clientId: config.auth.clientId,
        redirectUri: config.auth.redirectUri,
        apiHostname: config.auth.apiHostname,
        devMode: config.auth.devMode
      },
      queryClient: config.queryClient,
      apiUrl: config.apiUrl,
      onError: config.onApiError ? handleApiError : void 0,
      crmActions: config.crmActions,
      listActions: config.listActions,
      children: /* @__PURE__ */ jsx(AuthenticatedApp, { config })
    }
  );
}
function AuthenticatedApp({ config }) {
  const { user, getAccessToken } = useAuth();
  const setTheme = config.store?.useSetTheme();
  const { profile } = useInitialization();
  useEffect(() => {
    if (!config.onAuthTokenChange) return;
    if (user) {
      getAccessToken().then((token) => config.onAuthTokenChange(token)).catch(() => {
      });
    } else {
      config.onAuthTokenChange(void 0);
    }
  }, [user, getAccessToken, config.onAuthTokenChange]);
  useEffect(() => {
    if (!setTheme || !profile?.config) return;
    const cfg = profile.config;
    if (cfg.theme) {
      setTheme(cfg.theme);
    }
  }, [profile, setTheme]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(Notifications, {}),
    /* @__PURE__ */ jsx(RouterProvider, { router: config.router })
  ] });
}
function createElevasisApp(config) {
  function ElevasisApp() {
    return /* @__PURE__ */ jsx(AppWithStore, { config });
  }
  ElevasisApp.displayName = "ElevasisApp";
  return ElevasisApp;
}
function devOnlySubsectionPaths(organizationModel) {
  return listAllSystems(organizationModel).filter(({ system }) => system.devOnly && (system.ui?.path ?? system.path)).flatMap(({ system }) => {
    const path = system.ui?.path ?? system.path;
    return path ? [path] : [];
  });
}
function renderTopbar(topbar, context) {
  return typeof topbar === "function" ? topbar(context) : topbar;
}
function ElevasisAuthenticatedShell({
  systems,
  organizationModel,
  logos,
  topbar,
  children,
  fullScreenPaths = ["/login", "/auth-redirect"],
  fullScreenPathPrefixes = ["/public/", "/chat/"],
  readyMode = "organization",
  accountPath = "/settings/account",
  signOutReturnTo,
  appVersion,
  timeRange,
  operationsApiUrl,
  operationsSSEManager,
  deliveryApiUrl,
  deliverySSEManager,
  disabledSubsectionPaths,
  isDev = import.meta.env?.DEV ?? false,
  errorFallback,
  onError,
  sidebarLinks
}) {
  const computedColorScheme = useComputedColorScheme("dark");
  const { user, isLoading, signOut } = useAuth();
  const initialization = useInitialization();
  const location = useLocation();
  const isDark = computedColorScheme === "dark";
  useSessionCheck();
  const resolvedDisabledSubsectionPaths = useMemo(() => {
    if (isDev) return [...disabledSubsectionPaths ?? []];
    return [.../* @__PURE__ */ new Set([...devOnlySubsectionPaths(organizationModel), ...disabledSubsectionPaths ?? []])];
  }, [disabledSubsectionPaths, isDev, organizationModel]);
  const isFullScreenPage = fullScreenPaths.includes(location.pathname) || fullScreenPathPrefixes.some((prefix) => location.pathname.startsWith(prefix));
  const isReady = readyMode === "user" ? initialization.userReady : initialization.allReady;
  const shouldShowSidebar = Boolean(user && !isLoading && !isFullScreenPage && isReady);
  if (!shouldShowSidebar) {
    return /* @__PURE__ */ jsx(TanStackRouterBridge, { children: children ?? /* @__PURE__ */ jsx(Outlet, {}) });
  }
  return /* @__PURE__ */ jsx(TanStackRouterBridge, { children: /* @__PURE__ */ jsx(AppErrorBoundary, { fallback: errorFallback, onError, appVersion, children: /* @__PURE__ */ jsx(SidebarProvider, { children: /* @__PURE__ */ jsx(
    ElevasisSystemsProvider,
    {
      systems,
      organizationModel,
      timeRange,
      operationsApiUrl,
      operationsSSEManager,
      deliveryApiUrl,
      deliverySSEManager,
      disabledSubsectionPaths: resolvedDisabledSubsectionPaths,
      children: /* @__PURE__ */ jsx(
        AuthenticatedShellLayout,
        {
          accountPath,
          children,
          initialization,
          isDark,
          isDev,
          logos,
          sidebarLinks,
          signOutReturnTo,
          signOut,
          topbar,
          user
        }
      )
    }
  ) }) }) });
}
function AuthenticatedShellLayout({
  accountPath,
  children,
  initialization,
  isDark,
  isDev,
  logos,
  sidebarLinks,
  signOutReturnTo,
  signOut,
  topbar,
  user
}) {
  const navigate = useNavigate();
  const { getSidebarLinks } = useElevasisSystems();
  const isPlatformAdmin = Boolean(initialization.profile?.is_platform_admin);
  const projectedLinks = getSidebarLinks({ isPlatformAdmin, isDev });
  const visibleNavItems = sidebarLinks ? sidebarLinks(projectedLinks) : projectedLinks;
  const handleLogout = () => {
    if (signOutReturnTo) {
      signOut({ returnTo: signOutReturnTo });
    } else {
      signOut();
    }
  };
  return /* @__PURE__ */ jsxs(AppShellContainer, { children: [
    /* @__PURE__ */ jsx(
      Sidebar,
      {
        user: user ?? void 0,
        links: visibleNavItems,
        onLogout: handleLogout,
        onAccountClick: () => navigate({ to: accountPath }),
        logo: isDark ? logos?.dark : logos?.light
      }
    ),
    /* @__PURE__ */ jsxs(AppShellRightSideContainer, { children: [
      renderTopbar(topbar, { isDark, user, initialization }),
      /* @__PURE__ */ jsxs(AppShellRightSideOuterContainer, { children: [
        /* @__PURE__ */ jsx(ScrollToTop, {}),
        /* @__PURE__ */ jsx(SystemShell, { children: children ?? /* @__PURE__ */ jsx(Outlet, {}) })
      ] })
    ] })
  ] });
}

export { ElevasisAuthenticatedShell, createElevasisApp };
