'use client';
import {
  en_default
} from "./chunk-JH7BXE2P.mjs";
import {
  __glob
} from "./chunk-3JTO27MH.mjs";

// src/contexts/ApiClientContext.tsx
import { createContext, useContext, useMemo } from "react";
import { baseUrl } from "@semiont/core";
import { SemiontApiClient } from "@semiont/api-client";
import { jsx } from "react/jsx-runtime";
var ApiClientContext = createContext(void 0);
function ApiClientProvider({
  baseUrl: url,
  children
}) {
  const client = useMemo(
    () => new SemiontApiClient({
      baseUrl: baseUrl(url),
      // Use no timeout in test environment to avoid AbortController issues with ky + vitest
      ...process.env.NODE_ENV !== "test" && { timeout: 3e4 }
    }),
    [url]
    // Only baseUrl in deps, token removed
  );
  return /* @__PURE__ */ jsx(ApiClientContext.Provider, { value: client, children });
}
function useApiClient() {
  const context = useContext(ApiClientContext);
  if (context === void 0) {
    throw new Error("useApiClient must be used within an ApiClientProvider");
  }
  return context;
}

// src/contexts/SessionContext.tsx
import { createContext as createContext2, useContext as useContext2 } from "react";
import { jsx as jsx2 } from "react/jsx-runtime";
var SessionContext = createContext2(null);
function SessionProvider({
  sessionManager,
  children
}) {
  return /* @__PURE__ */ jsx2(SessionContext.Provider, { value: sessionManager, children });
}
function useSessionContext() {
  const context = useContext2(SessionContext);
  if (!context) {
    throw new Error("useSessionContext must be used within SessionProvider");
  }
  return context;
}

// src/components/Toast.tsx
import React, { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
var icons = {
  success: /* @__PURE__ */ jsx3("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx3("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }),
  error: /* @__PURE__ */ jsx3("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx3("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) }),
  warning: /* @__PURE__ */ jsx3("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx3("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__ */ jsx3("svg", { className: "semiont-toast-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx3("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 }) {
  useEffect(() => {
    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__ */ jsx3("div", { className: "semiont-toast-icon-wrapper", children: icons[toast.type] }),
        /* @__PURE__ */ jsx3("p", { className: "semiont-toast-message", children: toast.message }),
        /* @__PURE__ */ jsx3(
          "button",
          {
            onClick: () => onClose(toast.id),
            className: "semiont-toast-close",
            "aria-label": "Close",
            children: /* @__PURE__ */ jsx3("svg", { className: "semiont-toast-close-icon", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsx3("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }) })
          }
        )
      ]
    }
  );
}
function ToastContainer({ toasts, onClose }) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
    return () => setMounted(false);
  }, []);
  if (!mounted) return null;
  return createPortal(
    /* @__PURE__ */ jsx3("div", { className: "semiont-toast-container", children: toasts.map((toast) => /* @__PURE__ */ jsx3(Toast, { toast, onClose }, toast.id)) }),
    document.body
  );
}
var ToastContext = React.createContext(void 0);
function ToastProvider({ children }) {
  const [toasts, setToasts] = useState([]);
  const showToast = React.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 = React.useCallback((message, duration) => showToast(message, "success", duration), [showToast]);
  const showError = React.useCallback((message, duration) => showToast(message, "error", duration), [showToast]);
  const showWarning = React.useCallback((message, duration) => showToast(message, "warning", duration), [showToast]);
  const showInfo = React.useCallback((message, duration) => showToast(message, "info", duration), [showToast]);
  const handleClose = React.useCallback((id) => {
    setToasts((prev) => prev.filter((toast) => toast.id !== id));
  }, []);
  const contextValue = React.useMemo(
    () => ({ showToast, showSuccess, showError, showWarning, showInfo }),
    [showToast, showSuccess, showError, showWarning, showInfo]
  );
  return /* @__PURE__ */ jsxs(ToastContext.Provider, { value: contextValue, children: [
    children,
    /* @__PURE__ */ jsx3(ToastContainer, { toasts, onClose: handleClose })
  ] });
}
function useToast() {
  const context = React.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 createContext3, useContext as useContext3 } from "react";
import { jsx as jsx4 } from "react/jsx-runtime";
var OpenResourcesContext = createContext3(void 0);
function OpenResourcesProvider({
  openResourcesManager,
  children
}) {
  return /* @__PURE__ */ jsx4(OpenResourcesContext.Provider, { value: openResourcesManager, children });
}
function useOpenResources() {
  const context = useContext3(OpenResourcesContext);
  if (context === void 0) {
    throw new Error("useOpenResources must be used within an OpenResourcesProvider");
  }
  return context;
}

// src/contexts/TranslationContext.tsx
import { createContext as createContext4, useContext as useContext4, useState as useState2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
import { Fragment, jsx as jsx5 } from "react/jsx-runtime";

// import("../../translations/**/*.json") in src/contexts/TranslationContext.tsx
var globImport_translations_json = __glob({
  "../../translations/ar.json": () => import("./ar-7SUXNE34.mjs"),
  "../../translations/bn.json": () => import("./bn-XOET3DOI.mjs"),
  "../../translations/cs.json": () => import("./cs-X63DXX7L.mjs"),
  "../../translations/da.json": () => import("./da-OWTCV57A.mjs"),
  "../../translations/de.json": () => import("./de-77BMFDVF.mjs"),
  "../../translations/el.json": () => import("./el-FIBNLH2V.mjs"),
  "../../translations/en.json": () => import("./en-XWEPVTB4.mjs"),
  "../../translations/es.json": () => import("./es-726NTS53.mjs"),
  "../../translations/fa.json": () => import("./fa-3N4CIWE6.mjs"),
  "../../translations/fi.json": () => import("./fi-JOM3M7Z4.mjs"),
  "../../translations/fr.json": () => import("./fr-56QSXS7E.mjs"),
  "../../translations/he.json": () => import("./he-SNAXPJEK.mjs"),
  "../../translations/hi.json": () => import("./hi-CRBRD5TB.mjs"),
  "../../translations/id.json": () => import("./id-BRCVLICF.mjs"),
  "../../translations/it.json": () => import("./it-M2Z27BNB.mjs"),
  "../../translations/ja.json": () => import("./ja-TZUKW7HD.mjs"),
  "../../translations/ko.json": () => import("./ko-NKBGGOL6.mjs"),
  "../../translations/ms.json": () => import("./ms-XFXPN6RX.mjs"),
  "../../translations/nl.json": () => import("./nl-MVYXAS5C.mjs"),
  "../../translations/no.json": () => import("./no-XOLO4JPV.mjs"),
  "../../translations/pl.json": () => import("./pl-TRWLMMC4.mjs"),
  "../../translations/pt.json": () => import("./pt-M3TE24UI.mjs"),
  "../../translations/ro.json": () => import("./ro-QBFG2T64.mjs"),
  "../../translations/sv.json": () => import("./sv-IUECBXWX.mjs"),
  "../../translations/th.json": () => import("./th-US7KIN5Q.mjs"),
  "../../translations/tr.json": () => import("./tr-DWJ2FFUK.mjs"),
  "../../translations/uk.json": () => import("./uk-M4ZE4DPZ.mjs"),
  "../../translations/vi.json": () => import("./vi-FERZNPSH.mjs"),
  "../../translations/zh.json": () => import("./zh-3J2I3WYK.mjs")
});

// src/contexts/TranslationContext.tsx
var TranslationContext = createContext4(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] = useState2(null);
  const [isLoading, setIsLoading] = useState2(false);
  useEffect2(() => {
    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__ */ jsx5(TranslationContext.Provider, { value: translationManager, children });
  }
  if (locale && isLoading) {
    return /* @__PURE__ */ jsx5(Fragment, { children: loadingComponent });
  }
  if (locale && localeManager) {
    return /* @__PURE__ */ jsx5(TranslationContext.Provider, { value: localeManager, children });
  }
  return /* @__PURE__ */ jsx5(TranslationContext.Provider, { value: defaultTranslationManager, children });
}
function useTranslations(namespace) {
  const context = useContext4(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 {
  ApiClientProvider,
  useApiClient,
  SessionProvider,
  useSessionContext,
  ToastContainer,
  ToastProvider,
  useToast,
  OpenResourcesProvider,
  useOpenResources,
  AVAILABLE_LOCALES,
  TranslationProvider,
  useTranslations,
  usePreloadTranslations
};
//# sourceMappingURL=chunk-Q2KV6Y2J.mjs.map