'use client';
import {
  en_default
} from "./chunk-HVMAGUFA.mjs";
import {
  __glob
} from "./chunk-D4GAAQMM.mjs";

// src/contexts/knowledge-base-session/storage.ts
var SESSION_PREFIX = "semiont.session.";
var STORAGE_KEY = "semiont.knowledgeBases";
var ACTIVE_KEY = "semiont.activeKnowledgeBaseId";
var REFRESH_BEFORE_EXP_MS = 5 * 60 * 1e3;
function sessionKey(kbId) {
  return `${SESSION_PREFIX}${kbId}`;
}
function getStoredSession(kbId) {
  const raw = localStorage.getItem(sessionKey(kbId));
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed.access === "string" && typeof parsed.refresh === "string") {
      return { access: parsed.access, refresh: parsed.refresh };
    }
  } catch {
  }
  return null;
}
function setStoredSession(kbId, session) {
  localStorage.setItem(sessionKey(kbId), JSON.stringify(session));
}
function clearStoredSession(kbId) {
  localStorage.removeItem(sessionKey(kbId));
}
function parseJwtExpiry(token) {
  try {
    const parts = token.split(".");
    if (parts.length !== 3 || !parts[1]) return null;
    const payload = JSON.parse(atob(parts[1]));
    if (!payload.exp) return null;
    return new Date(payload.exp * 1e3);
  } catch {
    return null;
  }
}
function isJwtExpired(token) {
  const expiry = parseJwtExpiry(token);
  if (!expiry) return true;
  return expiry.getTime() < Date.now();
}
function migrateLegacyEntry(entry) {
  if (entry.host !== void 0) return entry;
  try {
    const url = new URL(entry.backendUrl);
    return {
      id: entry.id,
      label: entry.label,
      host: url.hostname,
      port: parseInt(url.port, 10) || (url.protocol === "https:" ? 443 : 80),
      protocol: url.protocol === "https:" ? "https" : "http",
      email: ""
    };
  } catch {
    return {
      id: entry.id,
      label: entry.label || "Unknown",
      host: "localhost",
      port: 4e3,
      protocol: "http",
      email: ""
    };
  }
}
function loadKnowledgeBases() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const entries = JSON.parse(raw);
    return entries.map(migrateLegacyEntry);
  } catch {
    return [];
  }
}
function saveKnowledgeBases(knowledgeBases) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(knowledgeBases));
}
function defaultProtocol(host) {
  return host === "localhost" || host === "127.0.0.1" ? "http" : "https";
}
function kbBackendUrl(kb) {
  return `${kb.protocol}://${kb.host}:${kb.port}`;
}
function getKbSessionStatus(kbId) {
  const stored = getStoredSession(kbId);
  if (!stored) return "signed-out";
  return isJwtExpired(stored.access) ? "expired" : "authenticated";
}
function generateKbId() {
  return crypto.randomUUID();
}

// src/contexts/knowledge-base-session/notify.ts
var activeOnSessionExpired = null;
var activeOnPermissionDenied = null;
function notifySessionExpired(message) {
  activeOnSessionExpired?.(message);
}
function notifyPermissionDenied(message) {
  activeOnPermissionDenied?.(message);
}
function registerAuthNotifyHandlers(handlers) {
  activeOnSessionExpired = handlers.onSessionExpired;
  activeOnPermissionDenied = handlers.onPermissionDenied;
  return () => {
    activeOnSessionExpired = null;
    activeOnPermissionDenied = null;
  };
}

// src/contexts/KnowledgeBaseSessionContext.tsx
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState
} from "react";
import { SemiontApiClient as SemiontApiClient2, APIError } from "@semiont/api-client";
import { baseUrl as baseUrl2, EventBus as EventBus2, accessToken } from "@semiont/core";

// src/contexts/knowledge-base-session/refresh.ts
import { SemiontApiClient } from "@semiont/api-client";
import { baseUrl, EventBus, refreshToken as makeRefreshToken } from "@semiont/core";
var inFlightRefreshes = /* @__PURE__ */ new Map();
async function performRefresh(kb) {
  const existing = inFlightRefreshes.get(kb.id);
  if (existing) return existing;
  const promise = (async () => {
    const stored = getStoredSession(kb.id);
    if (!stored) return null;
    const client = new SemiontApiClient({
      baseUrl: baseUrl(kbBackendUrl(kb)),
      eventBus: new EventBus()
    });
    try {
      const response = await client.refreshToken(makeRefreshToken(stored.refresh));
      const newAccess = response.access_token;
      if (!newAccess) return null;
      setStoredSession(kb.id, { access: newAccess, refresh: stored.refresh });
      return newAccess;
    } catch {
      return null;
    }
  })();
  inFlightRefreshes.set(kb.id, promise);
  try {
    return await promise;
  } finally {
    inFlightRefreshes.delete(kb.id);
  }
}

// src/contexts/KnowledgeBaseSessionContext.tsx
import { jsx } from "react/jsx-runtime";
var KnowledgeBaseSessionContext = createContext(void 0);
function KnowledgeBaseSessionProvider({ children }) {
  const [knowledgeBases, setKnowledgeBases] = useState(() => loadKnowledgeBases());
  const [activeKnowledgeBaseId, setActiveKnowledgeBaseId] = useState(() => {
    const saved = localStorage.getItem(ACTIVE_KEY);
    const loaded = loadKnowledgeBases();
    if (saved && loaded.some((kb) => kb.id === saved)) return saved;
    return loaded[0]?.id ?? null;
  });
  const [session, setSession] = useState(null);
  const [isLoading, setIsLoading] = useState(() => {
    const id = activeKnowledgeBaseId;
    if (!id) return false;
    const stored = getStoredSession(id);
    if (!stored) return false;
    return !isJwtExpired(stored.access) || stored.refresh != null;
  });
  const [sessionExpiredAt, setSessionExpiredAt] = useState(null);
  const [sessionExpiredMessage, setSessionExpiredMessage] = useState(null);
  const [permissionDeniedAt, setPermissionDeniedAt] = useState(null);
  const [permissionDeniedMessage, setPermissionDeniedMessage] = useState(null);
  useEffect(() => {
    saveKnowledgeBases(knowledgeBases);
  }, [knowledgeBases]);
  useEffect(() => {
    if (activeKnowledgeBaseId) {
      localStorage.setItem(ACTIVE_KEY, activeKnowledgeBaseId);
    } else {
      localStorage.removeItem(ACTIVE_KEY);
    }
  }, [activeKnowledgeBaseId]);
  const activeKnowledgeBase = useMemo(
    () => knowledgeBases.find((kb) => kb.id === activeKnowledgeBaseId) ?? null,
    [knowledgeBases, activeKnowledgeBaseId]
  );
  const activeKbRef = useRef(activeKnowledgeBase);
  useEffect(() => {
    activeKbRef.current = activeKnowledgeBase;
  }, [activeKnowledgeBase]);
  const proactiveRefreshTimerRef = useRef(null);
  const scheduleProactiveRefresh = useCallback((accessTokenStr) => {
    if (proactiveRefreshTimerRef.current) {
      clearTimeout(proactiveRefreshTimerRef.current);
      proactiveRefreshTimerRef.current = null;
    }
    const expiresAt = parseJwtExpiry(accessTokenStr);
    if (!expiresAt) return;
    const refreshAt = expiresAt.getTime() - REFRESH_BEFORE_EXP_MS;
    const delay = Math.max(0, refreshAt - Date.now());
    proactiveRefreshTimerRef.current = setTimeout(() => {
      proactiveRefreshTimerRef.current = null;
      refreshActiveRef.current?.();
    }, delay);
  }, []);
  const refreshActiveRef = useRef(null);
  const refreshActive = useCallback(async () => {
    const kb = activeKbRef.current;
    if (!kb) return null;
    const newAccess = await performRefresh(kb);
    if (newAccess) {
      setSession((prev) => prev ? { ...prev, token: newAccess } : prev);
      scheduleProactiveRefresh(newAccess);
    } else {
      setSession(null);
      clearStoredSession(kb.id);
      setSessionExpiredMessage("Your session has expired. Please sign in again.");
      setSessionExpiredAt(Date.now());
      if (proactiveRefreshTimerRef.current) {
        clearTimeout(proactiveRefreshTimerRef.current);
        proactiveRefreshTimerRef.current = null;
      }
    }
    return newAccess;
  }, [scheduleProactiveRefresh]);
  refreshActiveRef.current = refreshActive;
  useEffect(() => {
    if (!activeKnowledgeBase) {
      setSession(null);
      setIsLoading(false);
      return;
    }
    const stored = getStoredSession(activeKnowledgeBase.id);
    if (!stored) {
      setSession(null);
      setIsLoading(false);
      return;
    }
    let cancelled = false;
    const validate = async (tokenToUse) => {
      const client = new SemiontApiClient2({
        baseUrl: baseUrl2(kbBackendUrl(activeKnowledgeBase)),
        eventBus: new EventBus2()
      });
      try {
        const data = await client.getMe({ auth: accessToken(tokenToUse) });
        if (cancelled) return;
        setSession({ token: tokenToUse, user: data });
        scheduleProactiveRefresh(tokenToUse);
      } catch (error) {
        if (cancelled) return;
        setSession(null);
        if (error instanceof APIError && error.status === 401) {
          const refreshed = await performRefresh(activeKnowledgeBase);
          if (cancelled) return;
          if (refreshed) {
            return validate(refreshed);
          }
          clearStoredSession(activeKnowledgeBase.id);
          setSessionExpiredMessage("Your session has expired. Please sign in again.");
          setSessionExpiredAt(Date.now());
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };
    setIsLoading(true);
    if (isJwtExpired(stored.access)) {
      (async () => {
        const refreshed = await performRefresh(activeKnowledgeBase);
        if (cancelled) return;
        if (refreshed) {
          await validate(refreshed);
        } else {
          setSession(null);
          clearStoredSession(activeKnowledgeBase.id);
          setIsLoading(false);
        }
      })();
    } else {
      validate(stored.access);
    }
    return () => {
      cancelled = true;
    };
  }, [activeKnowledgeBase, scheduleProactiveRefresh]);
  useEffect(() => {
    return () => {
      if (proactiveRefreshTimerRef.current) {
        clearTimeout(proactiveRefreshTimerRef.current);
        proactiveRefreshTimerRef.current = null;
      }
    };
  }, []);
  useEffect(() => {
    if (!activeKnowledgeBaseId) return;
    const watchKey = sessionKey(activeKnowledgeBaseId);
    const handler = (e) => {
      if (e.key !== watchKey) return;
      if (!e.newValue) {
        setSession(null);
        if (proactiveRefreshTimerRef.current) {
          clearTimeout(proactiveRefreshTimerRef.current);
          proactiveRefreshTimerRef.current = null;
        }
        return;
      }
      try {
        const parsed = JSON.parse(e.newValue);
        if (typeof parsed.access === "string") {
          setSession((prev) => prev ? { ...prev, token: parsed.access } : prev);
          scheduleProactiveRefresh(parsed.access);
        }
      } catch {
      }
    };
    window.addEventListener("storage", handler);
    return () => window.removeEventListener("storage", handler);
  }, [activeKnowledgeBaseId, scheduleProactiveRefresh]);
  useEffect(() => {
    return registerAuthNotifyHandlers({
      onSessionExpired: (message) => {
        setSessionExpiredMessage(message ?? "Your session has expired. Please sign in again.");
        setSessionExpiredAt(Date.now());
        setSession(null);
        if (activeKnowledgeBaseId) {
          clearStoredSession(activeKnowledgeBaseId);
        }
        if (proactiveRefreshTimerRef.current) {
          clearTimeout(proactiveRefreshTimerRef.current);
          proactiveRefreshTimerRef.current = null;
        }
      },
      onPermissionDenied: (message) => {
        setPermissionDeniedMessage(message ?? "You do not have permission to perform this action.");
        setPermissionDeniedAt(Date.now());
      }
    });
  }, [activeKnowledgeBaseId]);
  const addKnowledgeBase = useCallback((input, access, refresh) => {
    const kb = { id: generateKbId(), ...input };
    setStoredSession(kb.id, { access, refresh });
    setKnowledgeBases((prev) => [...prev, kb]);
    setActiveKnowledgeBaseId(kb.id);
    return kb;
  }, []);
  const removeKnowledgeBase = useCallback((id) => {
    clearStoredSession(id);
    setKnowledgeBases((prev) => {
      const remaining = prev.filter((kb) => kb.id !== id);
      setActiveKnowledgeBaseId((activeId) => activeId === id ? remaining[0]?.id ?? null : activeId);
      return remaining;
    });
  }, []);
  const setActiveKnowledgeBase = useCallback((id) => {
    setActiveKnowledgeBaseId(id);
  }, []);
  const updateKnowledgeBase = useCallback((id, updates) => {
    setKnowledgeBases((prev) => prev.map((kb) => kb.id === id ? { ...kb, ...updates } : kb));
  }, []);
  const signIn = useCallback((id, access, refresh) => {
    setStoredSession(id, { access, refresh });
    setKnowledgeBases((prev) => prev.map((kb) => kb.id === id ? { ...kb } : kb));
    setActiveKnowledgeBaseId(id);
  }, []);
  const signOut = useCallback((id) => {
    clearStoredSession(id);
    setActiveKnowledgeBaseId((activeId) => {
      if (activeId === id) {
        setSession(null);
        if (proactiveRefreshTimerRef.current) {
          clearTimeout(proactiveRefreshTimerRef.current);
          proactiveRefreshTimerRef.current = null;
        }
      }
      return activeId;
    });
    setKnowledgeBases((prev) => [...prev]);
  }, []);
  const acknowledgeSessionExpired = useCallback(() => {
    setSessionExpiredAt(null);
    setSessionExpiredMessage(null);
  }, []);
  const acknowledgePermissionDenied = useCallback(() => {
    setPermissionDeniedAt(null);
    setPermissionDeniedMessage(null);
  }, []);
  const [, setTick] = useState(0);
  useEffect(() => {
    const interval = setInterval(() => setTick((t) => t + 1), 3e4);
    return () => clearInterval(interval);
  }, []);
  const value = useMemo(() => {
    const user = session?.user ?? null;
    const token = session?.token ?? null;
    const expiresAt = token ? parseJwtExpiry(token) : null;
    return {
      knowledgeBases,
      activeKnowledgeBase,
      session,
      isLoading,
      user,
      token,
      isAuthenticated: !!session,
      hasValidBackendToken: !!token,
      isFullyAuthenticated: !!session,
      displayName: user?.name ?? user?.email?.split("@")[0] ?? "User",
      avatarUrl: user?.image ?? null,
      userDomain: user?.domain || user?.email?.split("@")[1],
      isAdmin: user?.isAdmin ?? false,
      isModerator: user?.isModerator ?? false,
      expiresAt,
      sessionExpiredAt,
      sessionExpiredMessage,
      permissionDeniedAt,
      permissionDeniedMessage,
      addKnowledgeBase,
      removeKnowledgeBase,
      setActiveKnowledgeBase,
      updateKnowledgeBase,
      signIn,
      signOut,
      refreshActive,
      acknowledgeSessionExpired,
      acknowledgePermissionDenied
    };
  }, [
    knowledgeBases,
    activeKnowledgeBase,
    session,
    isLoading,
    sessionExpiredAt,
    sessionExpiredMessage,
    permissionDeniedAt,
    permissionDeniedMessage,
    addKnowledgeBase,
    removeKnowledgeBase,
    setActiveKnowledgeBase,
    updateKnowledgeBase,
    signIn,
    signOut,
    refreshActive,
    acknowledgeSessionExpired,
    acknowledgePermissionDenied
  ]);
  return /* @__PURE__ */ jsx(KnowledgeBaseSessionContext.Provider, { value, children });
}
function useKnowledgeBaseSession() {
  const ctx = useContext(KnowledgeBaseSessionContext);
  if (!ctx) {
    throw new Error(
      "useKnowledgeBaseSession requires KnowledgeBaseSessionProvider. This component is rendered outside the auth boundary. Move it into a protected layout."
    );
  }
  return ctx;
}

// src/components/Toast.tsx
import React2, { useEffect as useEffect2, useState as useState2 } from "react";
import { createPortal } from "react-dom";
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var icons = {
  success: /* @__PURE__ */ jsx2("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }),
  error: /* @__PURE__ */ jsx2("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) }),
  warning: /* @__PURE__ */ jsx2("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" }) }),
  info: /* @__PURE__ */ jsx2("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" }) })
};
function Toast({ toast, onClose }) {
  useEffect2(() => {
    const timer = setTimeout(() => {
      onClose(toast.id);
    }, toast.duration || 3e3);
    return () => clearTimeout(timer);
  }, [toast, onClose]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "semiont-toast",
      "data-variant": toast.type,
      role: "alert",
      children: [
        /* @__PURE__ */ jsx2("div", { className: "semiont-toast-icon-wrapper", children: icons[toast.type] }),
        /* @__PURE__ */ jsx2("p", { className: "semiont-toast-message", children: toast.message }),
        /* @__PURE__ */ jsx2(
          "button",
          {
            onClick: () => onClose(toast.id),
            className: "semiont-toast-close",
            "aria-label": "Close",
            children: /* @__PURE__ */ jsx2("svg", { className: "semiont-toast-close-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx2("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) })
          }
        )
      ]
    }
  );
}
function ToastContainer({ toasts, onClose }) {
  const [mounted, setMounted] = useState2(false);
  useEffect2(() => {
    setMounted(true);
    return () => setMounted(false);
  }, []);
  if (!mounted) return null;
  return createPortal(
    /* @__PURE__ */ jsx2("div", { className: "semiont-toast-container", children: toasts.map((toast) => /* @__PURE__ */ jsx2(Toast, { toast, onClose }, toast.id)) }),
    document.body
  );
}
var ToastContext = React2.createContext(void 0);
function ToastProvider({ children }) {
  const [toasts, setToasts] = useState2([]);
  const showToast = React2.useCallback((message, type = "info", duration) => {
    const id = Date.now().toString();
    const newToast = duration !== void 0 ? { id, message, type, duration } : { id, message, type };
    setToasts((prev) => [...prev, newToast]);
  }, []);
  const showSuccess = React2.useCallback((message, duration) => showToast(message, "success", duration), [showToast]);
  const showError = React2.useCallback((message, duration) => showToast(message, "error", duration), [showToast]);
  const showWarning = React2.useCallback((message, duration) => showToast(message, "warning", duration), [showToast]);
  const showInfo = React2.useCallback((message, duration) => showToast(message, "info", duration), [showToast]);
  const handleClose = React2.useCallback((id) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  }, []);
  const contextValue = React2.useMemo(
    () => ({ showToast, showSuccess, showError, showWarning, showInfo }),
    [showToast, showSuccess, showError, showWarning, showInfo]
  );
  return /* @__PURE__ */ jsxs(ToastContext.Provider, { value: contextValue, children: [
    children,
    /* @__PURE__ */ jsx2(ToastContainer, { toasts, onClose: handleClose })
  ] });
}
function useToast() {
  const context = React2.useContext(ToastContext);
  if (context === void 0) {
    throw new Error("useToast must be used within a ToastProvider");
  }
  return context;
}

// src/contexts/OpenResourcesContext.tsx
import { createContext as createContext2, useContext as useContext2 } from "react";
import { jsx as jsx3 } from "react/jsx-runtime";
var OpenResourcesContext = createContext2(void 0);
function OpenResourcesProvider({
  openResourcesManager,
  children
}) {
  return /* @__PURE__ */ jsx3(OpenResourcesContext.Provider, { value: openResourcesManager, children });
}
function useOpenResources() {
  const context = useContext2(OpenResourcesContext);
  if (context === void 0) {
    throw new Error("useOpenResources must be used within an OpenResourcesProvider");
  }
  return context;
}

// src/contexts/TranslationContext.tsx
import { createContext as createContext3, useContext as useContext3, useState as useState3, useEffect as useEffect3, useMemo as useMemo2 } from "react";
import { Fragment, jsx as jsx4 } from "react/jsx-runtime";

// import("../../translations/**/*.json") in src/contexts/TranslationContext.tsx
var globImport_translations_json = __glob({
  "../../translations/ar.json": () => import("./ar-R4CRNXEF.mjs"),
  "../../translations/bn.json": () => import("./bn-CZKGRHTA.mjs"),
  "../../translations/cs.json": () => import("./cs-4WIB2IHH.mjs"),
  "../../translations/da.json": () => import("./da-JWYEUYPX.mjs"),
  "../../translations/de.json": () => import("./de-GWUQZGER.mjs"),
  "../../translations/el.json": () => import("./el-DM2GT7P5.mjs"),
  "../../translations/en.json": () => import("./en-IUV4ZXKH.mjs"),
  "../../translations/es.json": () => import("./es-6LVQIM3D.mjs"),
  "../../translations/fa.json": () => import("./fa-IRUJY3QI.mjs"),
  "../../translations/fi.json": () => import("./fi-53FBOEVT.mjs"),
  "../../translations/fr.json": () => import("./fr-Q5KY7QL6.mjs"),
  "../../translations/he.json": () => import("./he-HJNKULBY.mjs"),
  "../../translations/hi.json": () => import("./hi-UYZ4X6CR.mjs"),
  "../../translations/id.json": () => import("./id-UAQMH6U2.mjs"),
  "../../translations/it.json": () => import("./it-C7QEBNFA.mjs"),
  "../../translations/ja.json": () => import("./ja-THS6AOSJ.mjs"),
  "../../translations/ko.json": () => import("./ko-XKK3TWQG.mjs"),
  "../../translations/ms.json": () => import("./ms-GSK7LIF7.mjs"),
  "../../translations/nl.json": () => import("./nl-KUBWITGY.mjs"),
  "../../translations/no.json": () => import("./no-ECWZUHT6.mjs"),
  "../../translations/pl.json": () => import("./pl-PLVWSZWS.mjs"),
  "../../translations/pt.json": () => import("./pt-AL74ZTKB.mjs"),
  "../../translations/ro.json": () => import("./ro-WTPHLHGS.mjs"),
  "../../translations/sv.json": () => import("./sv-QCLI7SG4.mjs"),
  "../../translations/th.json": () => import("./th-WCKVZU6U.mjs"),
  "../../translations/tr.json": () => import("./tr-2CAFS2XS.mjs"),
  "../../translations/uk.json": () => import("./uk-TDE4JLCY.mjs"),
  "../../translations/vi.json": () => import("./vi-KKXZ4PCX.mjs"),
  "../../translations/zh.json": () => import("./zh-VH4XN5PV.mjs")
});

// src/contexts/TranslationContext.tsx
var TranslationContext = createContext3(null);
var translationCache = /* @__PURE__ */ new Map();
function processPluralFormat(text, params) {
  const pluralMatch = text.match(/\{(\w+),\s*plural,\s*/);
  if (!pluralMatch) {
    return text;
  }
  const paramName = pluralMatch[1];
  const count = params[paramName];
  if (count === void 0) {
    return text;
  }
  let startPos = pluralMatch[0].length;
  let braceCount = 1;
  let endPos = startPos;
  for (let i = startPos; i < text.length; i++) {
    if (text[i] === "{") braceCount++;
    else if (text[i] === "}") {
      braceCount--;
      if (braceCount === 0) {
        endPos = i;
        break;
      }
    }
  }
  const pluralCases = text.substring(startPos, endPos);
  const cases = {};
  const caseRegex = /(?:=(\d+)|(\w+))\s*\{([^}]+)\}/g;
  let caseMatch;
  while ((caseMatch = caseRegex.exec(pluralCases)) !== null) {
    const [, exactNumber, keyword, textContent] = caseMatch;
    const key = exactNumber !== void 0 ? `=${exactNumber}` : keyword;
    cases[key] = textContent;
  }
  const exactMatch = cases[`=${count}`];
  if (exactMatch !== void 0) {
    const result = exactMatch.replace(/#/g, String(count));
    return text.substring(0, pluralMatch.index) + result + text.substring(endPos + 1);
  }
  const otherCase = cases["other"];
  if (otherCase !== void 0) {
    const result = otherCase.replace(/#/g, String(count));
    return text.substring(0, pluralMatch.index) + result + text.substring(endPos + 1);
  }
  return text;
}
var AVAILABLE_LOCALES = [
  "ar",
  // Arabic
  "bn",
  // Bengali
  "cs",
  // Czech
  "da",
  // Danish
  "de",
  // German
  "el",
  // Greek
  "en",
  // English
  "es",
  // Spanish
  "fa",
  // Persian/Farsi
  "fi",
  // Finnish
  "fr",
  // French
  "he",
  // Hebrew
  "hi",
  // Hindi
  "id",
  // Indonesian
  "it",
  // Italian
  "ja",
  // Japanese
  "ko",
  // Korean
  "ms",
  // Malay
  "nl",
  // Dutch
  "no",
  // Norwegian
  "pl",
  // Polish
  "pt",
  // Portuguese
  "ro",
  // Romanian
  "sv",
  // Swedish
  "th",
  // Thai
  "tr",
  // Turkish
  "uk",
  // Ukrainian
  "vi",
  // Vietnamese
  "zh"
  // Chinese
];
async function loadTranslations(locale) {
  if (translationCache.has(locale)) {
    return translationCache.get(locale);
  }
  if (locale === "en") {
    translationCache.set("en", en_default);
    return en_default;
  }
  try {
    const translations = await globImport_translations_json(`../../translations/${locale}.json`);
    const translationData = translations.default || translations;
    translationCache.set(locale, translationData);
    return translationData;
  } catch (error) {
    console.error(`Failed to load translations for locale: ${locale}`, error);
    return en_default;
  }
}
var defaultTranslationManager = {
  t: (namespace, key, params) => {
    const translations = en_default;
    const translation = translations[namespace]?.[key];
    if (!translation) {
      console.warn(`Translation not found for ${namespace}.${key}`);
      return `${namespace}.${key}`;
    }
    if (params && typeof translation === "string") {
      let result = translation;
      result = processPluralFormat(result, params);
      Object.entries(params).forEach(([paramKey, paramValue]) => {
        result = result.replace(new RegExp(`\\{${paramKey}\\}`, "g"), String(paramValue));
      });
      return result;
    }
    return translation;
  }
};
function TranslationProvider({
  translationManager,
  locale,
  loadingComponent = null,
  children
}) {
  const [loadedTranslations, setLoadedTranslations] = useState3(null);
  const [isLoading, setIsLoading] = useState3(false);
  useEffect3(() => {
    if (locale && !translationManager) {
      setIsLoading(true);
      loadTranslations(locale).then((translations) => {
        setLoadedTranslations(translations);
        setIsLoading(false);
      }).catch((error) => {
        console.error("Failed to load translations:", error);
        setLoadedTranslations(en_default);
        setIsLoading(false);
      });
    }
  }, [locale, translationManager]);
  const localeManager = useMemo2(() => {
    if (!loadedTranslations) return null;
    return {
      t: (namespace, key, params) => {
        const translation = loadedTranslations[namespace]?.[key];
        if (!translation) {
          console.warn(`Translation not found for ${namespace}.${key} in locale ${locale}`);
          return `${namespace}.${key}`;
        }
        if (params && typeof translation === "string") {
          let result = translation;
          result = processPluralFormat(result, params);
          Object.entries(params).forEach(([paramKey, paramValue]) => {
            result = result.replace(new RegExp(`\\{${paramKey}\\}`, "g"), String(paramValue));
          });
          return result;
        }
        return translation;
      }
    };
  }, [loadedTranslations, locale]);
  if (translationManager) {
    return /* @__PURE__ */ jsx4(TranslationContext.Provider, { value: translationManager, children });
  }
  if (locale && isLoading) {
    return /* @__PURE__ */ jsx4(Fragment, { children: loadingComponent });
  }
  if (locale && localeManager) {
    return /* @__PURE__ */ jsx4(TranslationContext.Provider, { value: localeManager, children });
  }
  return /* @__PURE__ */ jsx4(TranslationContext.Provider, { value: defaultTranslationManager, children });
}
function useTranslations(namespace) {
  const context = useContext3(TranslationContext);
  if (!context) {
    return (key, params) => {
      const translations = en_default;
      const translation = translations[namespace]?.[key];
      if (!translation) {
        console.warn(`Translation not found for ${namespace}.${key}`);
        return `${namespace}.${key}`;
      }
      if (params && typeof translation === "string") {
        let result = translation;
        result = processPluralFormat(result, params);
        Object.entries(params).forEach(([paramKey, paramValue]) => {
          result = result.replace(new RegExp(`\\{${paramKey}\\}`, "g"), String(paramValue));
        });
        return result;
      }
      return translation;
    };
  }
  return (key, params) => context.t(namespace, key, params);
}
function usePreloadTranslations() {
  return {
    preload: async (locale) => {
      try {
        await loadTranslations(locale);
        return true;
      } catch (error) {
        console.error(`Failed to preload translations for ${locale}:`, error);
        return false;
      }
    },
    isLoaded: (locale) => translationCache.has(locale)
  };
}

export {
  defaultProtocol,
  kbBackendUrl,
  getKbSessionStatus,
  notifySessionExpired,
  notifyPermissionDenied,
  KnowledgeBaseSessionContext,
  KnowledgeBaseSessionProvider,
  useKnowledgeBaseSession,
  ToastContainer,
  ToastProvider,
  useToast,
  OpenResourcesProvider,
  useOpenResources,
  AVAILABLE_LOCALES,
  TranslationProvider,
  useTranslations,
  usePreloadTranslations
};
//# sourceMappingURL=chunk-R2U7P4TK.mjs.map