@serhii.olishevskyi/docs 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1980 @@
1
+ // src/UI/components/data.display/UserPopoverComponent.tsx
2
+ import { useEffect as useEffect8, useState as useState12 } from "react";
3
+ import {
4
+ Popover,
5
+ Box as Box4,
6
+ Avatar,
7
+ Typography as Typography2,
8
+ Divider,
9
+ IconButton as IconButton4,
10
+ CircularProgress as CircularProgress2,
11
+ Stack,
12
+ Badge
13
+ } from "@mui/material";
14
+ import {
15
+ NotificationsNone as NotificationIcon,
16
+ AssignmentOutlined as TaskIcon,
17
+ ChatBubble as ChatIcon,
18
+ Work as WorkIcon,
19
+ CalendarToday as CalendarIcon,
20
+ Phone as PhoneIcon,
21
+ Close as CloseIcon,
22
+ Email as EmailIcon,
23
+ AccessTime as AccessTimeIcon,
24
+ Cake as CakeIcon
25
+ } from "@mui/icons-material";
26
+
27
+ // src/UI/components/data.display/UserStatusChipComponent.tsx
28
+ import { Chip, IconButton as IconButton2 } from "@mui/material";
29
+ import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
30
+
31
+ // src/context/SupabaseProvider.tsx
32
+ import { createContext, useContext, useMemo } from "react";
33
+ import { createClient } from "@supabase/supabase-js";
34
+ import { jsx } from "react/jsx-runtime";
35
+ var SupabaseContext = createContext(null);
36
+ var SupabaseProvider = ({
37
+ children,
38
+ client,
39
+ config
40
+ }) => {
41
+ const supabaseInstance = useMemo(() => {
42
+ if (client) return client;
43
+ if (config?.url && config?.anonKey) {
44
+ return createClient(config.url, config.anonKey);
45
+ }
46
+ throw new Error(
47
+ '[SupabaseProvider]: \u0412\u0430\u043C \u043D\u0443\u0436\u043D\u043E \u043F\u0435\u0440\u0435\u0434\u0430\u0442\u044C \u043B\u0438\u0431\u043E prop "client", \u043B\u0438\u0431\u043E "config" ({ url, anonKey }).'
48
+ );
49
+ }, [client, config]);
50
+ return /* @__PURE__ */ jsx(SupabaseContext.Provider, { value: { supabase: supabaseInstance }, children });
51
+ };
52
+ var useSupabase = () => {
53
+ const context = useContext(SupabaseContext);
54
+ if (!context) {
55
+ throw new Error("useSupabase \u0434\u043E\u043B\u0436\u0435\u043D \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u0432\u043D\u0443\u0442\u0440\u0438 <SupabaseProvider>");
56
+ }
57
+ return context.supabase;
58
+ };
59
+
60
+ // src/context/TranslateProvider.tsx
61
+ import { createContext as createContext2, useContext as useContext2 } from "react";
62
+ import { jsx as jsx2 } from "react/jsx-runtime";
63
+ var TranslationNamespaceContext = createContext2({
64
+ namespace: "common"
65
+ // значение по умолчанию
66
+ });
67
+ var TranslateProvider = ({ namespace, children }) => {
68
+ return /* @__PURE__ */ jsx2(TranslationNamespaceContext.Provider, { value: { namespace }, children });
69
+ };
70
+ var useTranslationNamespace = (overrideNamespace) => {
71
+ const context = useContext2(TranslationNamespaceContext);
72
+ return overrideNamespace || context.namespace;
73
+ };
74
+
75
+ // src/context/TranslationEditProvider.tsx
76
+ import { createContext as createContext4, useContext as useContext4, useState as useState2, useEffect as useEffect2, useCallback as useCallback2 } from "react";
77
+
78
+ // src/i18n/config.ts
79
+ import i18n from "i18next";
80
+ import { initReactI18next } from "react-i18next";
81
+
82
+ // src/i18n/customCacheBackend.ts
83
+ var _SupabaseCacheBackend = class _SupabaseCacheBackend {
84
+ // 1. Принимаем SupabaseClient в конструктор
85
+ constructor(supabase) {
86
+ this.type = "backend";
87
+ this.supabase = supabase;
88
+ }
89
+ init(services, backendOptions, i18nextOptions) {
90
+ if (backendOptions?.supabase) {
91
+ this.supabase = backendOptions.supabase;
92
+ }
93
+ }
94
+ /**
95
+ * Загрузка всего манифеста версий из Supabase в память
96
+ */
97
+ async loadManifest() {
98
+ if (_SupabaseCacheBackend.isManifestLoaded || !this.supabase) return;
99
+ try {
100
+ const { data, error } = await this.supabase.from("translation_versions").select("namespace, lang_code, version");
101
+ if (error) {
102
+ if (error.code === "PGRST303" || error.message?.includes("future")) {
103
+ console.warn("[i18n] Time drift detected (JWT in future). Falling back to cached translations.");
104
+ }
105
+ throw error;
106
+ }
107
+ if (data) {
108
+ const manifestMap = {};
109
+ data.forEach((row) => {
110
+ manifestMap[`${row.lang_code}:${row.namespace}`] = row.version;
111
+ });
112
+ _SupabaseCacheBackend.manifest = manifestMap;
113
+ _SupabaseCacheBackend.isManifestLoaded = true;
114
+ }
115
+ } catch (err) {
116
+ console.warn("[i18n] Could not load translation versions manifest, using local cache:", err);
117
+ }
118
+ }
119
+ /**
120
+ * Основной метод чтения локализации
121
+ */
122
+ async read(language, namespace, callback) {
123
+ const cacheKey = `i18n_${language}_${namespace}`;
124
+ const versionKey = `i18n_ver_${language}_${namespace}`;
125
+ const manifestKey = `${language}:${namespace}`;
126
+ try {
127
+ await this.loadManifest();
128
+ const cachedData = localStorage.getItem(cacheKey);
129
+ const localVersion = parseInt(localStorage.getItem(versionKey) || "0", 10);
130
+ const serverVersion = _SupabaseCacheBackend.manifest[manifestKey];
131
+ if (cachedData && serverVersion !== void 0 && localVersion === serverVersion) {
132
+ callback(null, JSON.parse(cachedData));
133
+ return;
134
+ }
135
+ if (cachedData && !_SupabaseCacheBackend.isManifestLoaded) {
136
+ callback(null, JSON.parse(cachedData));
137
+ return;
138
+ }
139
+ if (!this.supabase) {
140
+ throw new Error("[SupabaseCacheBackend]: Supabase client is not initialized.");
141
+ }
142
+ const { data, error } = await this.supabase.from("translations").select("key, value").eq("lang_code", language).eq("namespace", namespace);
143
+ if (error) throw error;
144
+ const freshData = {};
145
+ if (data) {
146
+ data.forEach((row) => {
147
+ this.setNestedKey(freshData, row.key, row.value);
148
+ });
149
+ }
150
+ localStorage.setItem(cacheKey, JSON.stringify(freshData));
151
+ if (serverVersion !== void 0) {
152
+ localStorage.setItem(versionKey, serverVersion.toString());
153
+ }
154
+ callback(null, freshData);
155
+ } catch (err) {
156
+ console.warn(`[i18n] Fallback to cache for ${language}/${namespace} due to error:`, err);
157
+ const cachedData = localStorage.getItem(cacheKey);
158
+ if (cachedData) {
159
+ callback(null, JSON.parse(cachedData));
160
+ } else {
161
+ callback(err, false);
162
+ }
163
+ }
164
+ }
165
+ setNestedKey(obj, path, value) {
166
+ const keys = path.split(".");
167
+ let current = obj;
168
+ for (let i = 0; i < keys.length - 1; i++) {
169
+ const key = keys[i];
170
+ if (!current[key] || typeof current[key] !== "object") {
171
+ current[key] = {};
172
+ }
173
+ current = current[key];
174
+ }
175
+ current[keys[keys.length - 1]] = value;
176
+ }
177
+ create(languages, namespace, key, fallbackValue) {
178
+ }
179
+ };
180
+ _SupabaseCacheBackend.type = "backend";
181
+ // Локальный манифест версий
182
+ _SupabaseCacheBackend.manifest = {};
183
+ _SupabaseCacheBackend.isManifestLoaded = false;
184
+ var SupabaseCacheBackend = _SupabaseCacheBackend;
185
+
186
+ // src/i18n/config.ts
187
+ var config_default = i18n;
188
+
189
+ // src/context/AuthProvider.tsx
190
+ import { createContext as createContext3, useContext as useContext3, useEffect, useState, useCallback, useRef } from "react";
191
+
192
+ // src/services/session.service.ts
193
+ var getUserLastSeenAt = async (supabase, userId) => {
194
+ const { data, error } = await supabase.from("user_sessions").select("last_seen_at").eq("user_id", userId).order("last_seen_at", { ascending: false }).limit(1).maybeSingle();
195
+ if (error || !data) return null;
196
+ return data.last_seen_at;
197
+ };
198
+
199
+ // src/context/AuthProvider.tsx
200
+ import { jsx as jsx3 } from "react/jsx-runtime";
201
+ var AuthContext = createContext3(void 0);
202
+ var useAuth = () => {
203
+ const context = useContext3(AuthContext);
204
+ if (!context) {
205
+ throw new Error("useAuth should be used within the AuthProvider");
206
+ }
207
+ return context;
208
+ };
209
+
210
+ // src/context/TranslationEditProvider.tsx
211
+ import { jsx as jsx4 } from "react/jsx-runtime";
212
+ var TranslationEditContext = createContext4(void 0);
213
+ var TranslationEditProvider = ({ children }) => {
214
+ const supabase = useSupabase();
215
+ const { user } = useAuth();
216
+ const [isTranslationMode, setIsTranslationMode] = useState2(false);
217
+ const [canEdit, setCanEdit] = useState2(false);
218
+ const [isLoadingPermissions, setIsLoadingPermissions] = useState2(true);
219
+ const checkPermission = useCallback2(async () => {
220
+ if (!user) {
221
+ setCanEdit(false);
222
+ setIsTranslationMode(false);
223
+ setIsLoadingPermissions(false);
224
+ return;
225
+ }
226
+ try {
227
+ setIsLoadingPermissions(true);
228
+ const { data, error } = await supabase.from("translation_responsible_users").select("id").eq("user_id", user.id).maybeSingle();
229
+ if (error) {
230
+ console.error("Error checking translation responsibilities:", error);
231
+ setCanEdit(false);
232
+ setIsTranslationMode(false);
233
+ } else {
234
+ const hasAccess = Boolean(data);
235
+ setCanEdit(hasAccess);
236
+ if (!hasAccess) {
237
+ setIsTranslationMode(false);
238
+ }
239
+ }
240
+ } catch (err) {
241
+ console.error("Permission check failed:", err);
242
+ setCanEdit(false);
243
+ } finally {
244
+ setIsLoadingPermissions(false);
245
+ }
246
+ }, [user]);
247
+ useEffect2(() => {
248
+ checkPermission();
249
+ }, [checkPermission]);
250
+ const updateTranslation = async (key, namespace, newValue) => {
251
+ if (!canEdit) return;
252
+ const currentLang = config_default.language;
253
+ const { error } = await supabase.from("translations").upsert({
254
+ key,
255
+ namespace,
256
+ lang_code: currentLang,
257
+ value: newValue
258
+ }, { onConflict: "key,namespace,lang_code" });
259
+ if (error) return alert("\u041E\u0448\u0438\u0431\u043A\u0430 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0432 \u0411\u0414");
260
+ localStorage.removeItem(`i18n_ver_${currentLang}_${namespace}`);
261
+ config_default.addResource(currentLang, namespace, key, newValue);
262
+ config_default.changeLanguage(currentLang);
263
+ };
264
+ const handleSetTranslationMode = (val) => {
265
+ if (canEdit) {
266
+ setIsTranslationMode(val);
267
+ }
268
+ };
269
+ return /* @__PURE__ */ jsx4(
270
+ TranslationEditContext.Provider,
271
+ {
272
+ value: {
273
+ isTranslationMode,
274
+ setIsTranslationMode: handleSetTranslationMode,
275
+ canEdit,
276
+ isLoadingPermissions,
277
+ updateTranslation
278
+ },
279
+ children
280
+ }
281
+ );
282
+ };
283
+ var useTranslationEdit = () => {
284
+ const context = useContext4(TranslationEditContext);
285
+ if (!context) throw new Error("useTranslationEdit must be used within TranslationEditProvider");
286
+ return context;
287
+ };
288
+
289
+ // src/context/LocalizationProvider.tsx
290
+ import { createContext as createContext5, useContext as useContext5, useMemo as useMemo2, useEffect as useEffect3, useState as useState3 } from "react";
291
+ import { useTranslation } from "react-i18next";
292
+ import moment from "moment/min/moment-with-locales";
293
+ import { jsx as jsx5 } from "react/jsx-runtime";
294
+ var DEFAULT_DATETIME_FORMATS = {
295
+ uk: "DD.MM.YYYY, HH:mm",
296
+ de: "DD.MM.YYYY, HH:mm",
297
+ en: "MM/DD/YYYY, hh:mm A",
298
+ es: "DD/MM/YYYY, HH:mm",
299
+ fr: "DD/MM/YYYY, HH:mm",
300
+ it: "DD/MM/YYYY, HH:mm"
301
+ };
302
+ var DEFAULT_DATE_FORMATS = {
303
+ uk: "DD.MM.YYYY",
304
+ de: "DD.MM.YYYY",
305
+ en: "MM/DD/YYYY",
306
+ es: "DD/MM/YYYY",
307
+ fr: "DD/MM/YYYY",
308
+ it: "DD/MM/YYYY"
309
+ };
310
+ var DEFAULT_TIME_FORMATS = {
311
+ uk: "HH:mm:ss",
312
+ de: "HH:mm:ss",
313
+ en: "hh:mm:ss A",
314
+ es: "HH:mm:ss",
315
+ fr: "HH:mm:ss",
316
+ it: "HH:mm:ss"
317
+ };
318
+ var LocalizationContext = createContext5(void 0);
319
+ var LocalizationProvider = ({ children }) => {
320
+ const supabase = useSupabase();
321
+ const { i18n: i18n2 } = useTranslation();
322
+ const [languages, setLanguages] = useState3([]);
323
+ const [isLoadingLangs, setIsLoadingLangs] = useState3(true);
324
+ const [languagesError, setLanguagesError] = useState3(null);
325
+ useEffect3(() => {
326
+ let isMounted = true;
327
+ const fetchLanguages = async () => {
328
+ try {
329
+ setIsLoadingLangs(true);
330
+ setLanguagesError(null);
331
+ const { data: langs, error: langErr } = await supabase.from("languages").select("code, name, svg_flag, enabled, created_at").eq("enabled", true).order("code", { ascending: true });
332
+ if (langErr) {
333
+ throw langErr;
334
+ }
335
+ if (isMounted && langs) {
336
+ setLanguages(langs);
337
+ }
338
+ } catch (err) {
339
+ console.error("Failed to load languages from Supabase:", err);
340
+ if (isMounted) {
341
+ setLanguagesError(err.message || "Error loading languages");
342
+ }
343
+ } finally {
344
+ if (isMounted) {
345
+ setIsLoadingLangs(false);
346
+ }
347
+ }
348
+ };
349
+ fetchLanguages();
350
+ return () => {
351
+ isMounted = false;
352
+ };
353
+ }, [supabase]);
354
+ const rawLang = i18n2.language || "uk";
355
+ const currentLang = rawLang.split("-")[0].toLowerCase();
356
+ const getDateFormat = () => {
357
+ return DEFAULT_DATE_FORMATS[currentLang] || "DD.MM.YYYY";
358
+ };
359
+ const getTimeFormat = () => {
360
+ return DEFAULT_TIME_FORMATS[currentLang] || "HH:mm:ss";
361
+ };
362
+ const getDateTimeFormat = () => {
363
+ return DEFAULT_DATETIME_FORMATS[currentLang] || "DD.MM.YYYY, HH:mm";
364
+ };
365
+ const formatDateTime = (date, customPattern) => {
366
+ if (!date) return "\u2014";
367
+ const pattern = customPattern || DEFAULT_DATETIME_FORMATS[currentLang] || "DD.MM.YYYY, HH:mm";
368
+ return moment(date).locale(currentLang).format(pattern);
369
+ };
370
+ const formatDate = (date, customPattern) => {
371
+ if (!date) return "\u2014";
372
+ const pattern = customPattern || DEFAULT_DATE_FORMATS[currentLang] || "DD.MM.YYYY";
373
+ return moment(date).locale(currentLang).format(pattern);
374
+ };
375
+ const formatTime = (date, customPattern) => {
376
+ if (!date) return "\u2014";
377
+ const pattern = customPattern || DEFAULT_TIME_FORMATS[currentLang] || "HH:mm:ss";
378
+ return moment(date).locale(currentLang).format(pattern);
379
+ };
380
+ const formatRelativeTime = (date, withoutSuffix = false) => {
381
+ if (!date) return "\u2014";
382
+ return moment(date).locale(currentLang).fromNow(withoutSuffix);
383
+ };
384
+ const changeLanguage = async (lang) => {
385
+ await i18n2.changeLanguage(lang);
386
+ };
387
+ const value = useMemo2(
388
+ () => ({
389
+ currentLang,
390
+ languages,
391
+ isLoadingLangs,
392
+ languagesError,
393
+ changeLanguage,
394
+ getDateFormat,
395
+ getTimeFormat,
396
+ getDateTimeFormat,
397
+ formatDateTime,
398
+ formatDate,
399
+ formatTime,
400
+ formatRelativeTime
401
+ }),
402
+ [currentLang, languages, isLoadingLangs, languagesError]
403
+ );
404
+ return /* @__PURE__ */ jsx5(LocalizationContext.Provider, { value, children });
405
+ };
406
+ var useLocalization = () => {
407
+ const context = useContext5(LocalizationContext);
408
+ if (!context) {
409
+ throw new Error("useLocalization must be used within a LocalizationProvider");
410
+ }
411
+ return context;
412
+ };
413
+
414
+ // src/context/ThemeProvider.tsx
415
+ import { createContext as createContext6, useContext as useContext6, useMemo as useMemo3, useState as useState4, useEffect as useEffect4 } from "react";
416
+ import { createTheme, ThemeProvider as MuiThemeProvider, CssBaseline, useMediaQuery } from "@mui/material";
417
+ import { jsx as jsx6, jsxs } from "react/jsx-runtime";
418
+ var DEFAULT_LIGHT_COLORS = {
419
+ primary: "#1976d2",
420
+ secondary: "#9c27b0",
421
+ backgroundDefault: "#f5f5f5",
422
+ backgroundPaper: "#ffffff",
423
+ textPrimary: "#0f172a",
424
+ textSecondary: "#475569",
425
+ success: "#2e7d32",
426
+ error: "#d32f2f",
427
+ warning: "#ed6c02",
428
+ info: "#0288d1"
429
+ };
430
+ var DEFAULT_DARK_COLORS = {
431
+ primary: "#90caf9",
432
+ secondary: "#ce93d8",
433
+ backgroundDefault: "#0f172a",
434
+ backgroundPaper: "#1e293b",
435
+ textPrimary: "#f8fafc",
436
+ textSecondary: "#94a3b8",
437
+ success: "#66bb6a",
438
+ error: "#f44336",
439
+ warning: "#ffa726",
440
+ info: "#29b6f6"
441
+ };
442
+ var INITIAL_THEME_CONFIG = {
443
+ name: "Base MUI Theme",
444
+ mode: "light",
445
+ borderRadius: 12,
446
+ colors: {
447
+ light: DEFAULT_LIGHT_COLORS,
448
+ dark: DEFAULT_DARK_COLORS
449
+ },
450
+ typography: {
451
+ fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
452
+ fontSize: 14,
453
+ fontWeightLight: 300,
454
+ fontWeightRegular: 400,
455
+ fontWeightMedium: 600,
456
+ fontWeightBold: 700
457
+ }
458
+ };
459
+ var buildMuiTheme = (config) => {
460
+ const currentMode = config.mode;
461
+ const currentColors = config.colors?.[currentMode] || (currentMode === "light" ? DEFAULT_LIGHT_COLORS : DEFAULT_DARK_COLORS);
462
+ return createTheme({
463
+ palette: {
464
+ mode: currentMode,
465
+ primary: {
466
+ main: currentColors.primary,
467
+ light: currentMode === "light" ? "#63a4ff" : "#a1d2fa",
468
+ dark: currentMode === "light" ? "#004ba0" : "#42a5f5"
469
+ },
470
+ secondary: {
471
+ main: currentColors.secondary
472
+ },
473
+ background: {
474
+ default: currentColors.backgroundDefault,
475
+ paper: currentColors.backgroundPaper
476
+ },
477
+ text: {
478
+ primary: currentColors.textPrimary,
479
+ secondary: currentColors.textSecondary || (currentMode === "light" ? "#475569" : "#94a3b8")
480
+ },
481
+ success: { main: currentColors.success },
482
+ error: { main: currentColors.error },
483
+ warning: { main: currentColors.warning },
484
+ info: { main: currentColors.info }
485
+ },
486
+ shape: {
487
+ borderRadius: config.borderRadius
488
+ },
489
+ typography: {
490
+ fontFamily: config.typography?.fontFamily || INITIAL_THEME_CONFIG.typography.fontFamily,
491
+ fontSize: config.typography?.fontSize || INITIAL_THEME_CONFIG.typography.fontSize,
492
+ fontWeightLight: config.typography?.fontWeightLight || INITIAL_THEME_CONFIG.typography.fontWeightLight,
493
+ fontWeightRegular: config.typography?.fontWeightRegular || INITIAL_THEME_CONFIG.typography.fontWeightRegular,
494
+ fontWeightMedium: config.typography?.fontWeightMedium || INITIAL_THEME_CONFIG.typography.fontWeightMedium,
495
+ fontWeightBold: config.typography?.fontWeightBold || INITIAL_THEME_CONFIG.typography.fontWeightBold,
496
+ h5: { fontWeight: 700, fontSize: "1.25rem" },
497
+ subtitle1: { fontWeight: 600, fontSize: "0.95rem" },
498
+ body2: { fontSize: "0.85rem" }
499
+ },
500
+ components: {
501
+ MuiAutocomplete: {
502
+ defaultProps: {
503
+ noOptionsText: "\u041D\u0456\u0447\u043E\u0433\u043E \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u043E"
504
+ }
505
+ },
506
+ MuiListItem: {
507
+ styleOverrides: {
508
+ root: {
509
+ transition: "all 0.2s ease-in-out",
510
+ "&:hover": {
511
+ backgroundColor: currentMode === "light" ? "#f1f5f9" : "#334155"
512
+ }
513
+ }
514
+ }
515
+ },
516
+ MuiListItemButton: {
517
+ styleOverrides: {
518
+ root: {
519
+ transition: "all 0.2s ease-in-out",
520
+ "&:hover": {
521
+ backgroundColor: currentMode === "light" ? "#f1f5f9" : "#334155"
522
+ }
523
+ }
524
+ }
525
+ },
526
+ MuiButton: {
527
+ styleOverrides: {
528
+ root: {
529
+ textTransform: "none",
530
+ fontWeight: 600,
531
+ borderRadius: `${config.borderRadius}px`,
532
+ padding: "10px 24px",
533
+ transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
534
+ }
535
+ }
536
+ },
537
+ MuiPaper: {
538
+ styleOverrides: {
539
+ rounded: {
540
+ borderRadius: `${config.borderRadius * 1.25}px`
541
+ }
542
+ }
543
+ }
544
+ }
545
+ });
546
+ };
547
+ var ThemeContext = createContext6(void 0);
548
+ var THEME_STORAGE_KEY = "docsua_custom_theme_config";
549
+ var THEME_MODE_STORAGE_KEY = "docsua_custom_theme_mode";
550
+ var ThemeProvider = ({ children }) => {
551
+ const supabase = useSupabase();
552
+ const { user, isAuthenticated, loading: isAuthLoading } = useAuth();
553
+ const userId = user?.id;
554
+ const [themeConfig, setThemeConfig] = useState4(() => {
555
+ const saved = localStorage.getItem(THEME_STORAGE_KEY);
556
+ if (saved) {
557
+ try {
558
+ return JSON.parse(saved);
559
+ } catch (e) {
560
+ }
561
+ }
562
+ return INITIAL_THEME_CONFIG;
563
+ });
564
+ useEffect4(() => {
565
+ if (isAuthLoading) return;
566
+ if (isAuthenticated && userId) {
567
+ const fetchActiveTheme = async () => {
568
+ try {
569
+ const { data, error } = await supabase.from("user_themes").select("*").eq("user_id", userId).eq("is_active", true).maybeSingle();
570
+ if (error) {
571
+ console.error("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0437\u0430\u0433\u0440\u0443\u0437\u043A\u0435 \u0442\u0435\u043C\u044B \u0438\u0437 Supabase:", error.message);
572
+ return;
573
+ }
574
+ if (data) {
575
+ const activeTheme = data;
576
+ const savedMode = localStorage.getItem(THEME_MODE_STORAGE_KEY);
577
+ setThemeConfig({
578
+ id: activeTheme.id,
579
+ name: activeTheme.name || INITIAL_THEME_CONFIG.name,
580
+ mode: savedMode || activeTheme.config?.mode || "light",
581
+ borderRadius: activeTheme.config?.borderRadius ?? INITIAL_THEME_CONFIG.borderRadius,
582
+ colors: activeTheme.config?.colors || INITIAL_THEME_CONFIG.colors,
583
+ typography: activeTheme.config?.typography || INITIAL_THEME_CONFIG.typography,
584
+ updatedAt: activeTheme.updated_at || void 0
585
+ });
586
+ }
587
+ } catch (err) {
588
+ console.error("\u041D\u0435\u043F\u0440\u0435\u0434\u0432\u0438\u0434\u0435\u043D\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0437\u0430\u043F\u0440\u043E\u0441\u0435 \u0442\u0435\u043C\u044B:", err);
589
+ }
590
+ };
591
+ fetchActiveTheme();
592
+ } else {
593
+ setThemeConfig(INITIAL_THEME_CONFIG);
594
+ localStorage.removeItem(THEME_STORAGE_KEY);
595
+ localStorage.removeItem(THEME_MODE_STORAGE_KEY);
596
+ }
597
+ }, [isAuthenticated, isAuthLoading, userId]);
598
+ useEffect4(() => {
599
+ if (isAuthenticated) {
600
+ localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify(themeConfig));
601
+ localStorage.setItem(THEME_MODE_STORAGE_KEY, themeConfig.mode);
602
+ }
603
+ }, [themeConfig, isAuthenticated]);
604
+ const mode = themeConfig.mode;
605
+ const setMode = (newMode) => {
606
+ setThemeConfig((prev) => ({ ...prev, mode: newMode }));
607
+ };
608
+ const toggleTheme = () => {
609
+ setMode(mode === "light" ? "dark" : "light");
610
+ };
611
+ const theme = useMemo3(() => buildMuiTheme(themeConfig), [themeConfig]);
612
+ const displayState = {
613
+ isMobile: useMediaQuery(theme.breakpoints.down("sm")),
614
+ isTablet: useMediaQuery(theme.breakpoints.between("sm", "md")),
615
+ isDesktop: useMediaQuery(theme.breakpoints.between("md", "lg")),
616
+ isWideDesktop: useMediaQuery(theme.breakpoints.between("lg", "xl")),
617
+ isSuperWideDesktop: useMediaQuery(theme.breakpoints.up("xl"))
618
+ };
619
+ return /* @__PURE__ */ jsx6(ThemeContext.Provider, { value: { mode, toggleTheme, setMode, theme, themeConfig, setThemeConfig, displayState }, children: /* @__PURE__ */ jsxs(MuiThemeProvider, { theme, children: [
620
+ /* @__PURE__ */ jsx6(CssBaseline, {}),
621
+ children
622
+ ] }) });
623
+ };
624
+ var useAppTheme = () => {
625
+ const context = useContext6(ThemeContext);
626
+ if (!context) {
627
+ throw new Error("useAppTheme should be used within the ThemeProvider");
628
+ }
629
+ return context;
630
+ };
631
+
632
+ // src/context/BreadcrumbProvider.tsx
633
+ import { createContext as createContext7, useContext as useContext7, useState as useState5 } from "react";
634
+ import { jsx as jsx7 } from "react/jsx-runtime";
635
+ var BreadcrumbContext = createContext7({
636
+ breadcrumbTitles: {},
637
+ setBreadcrumbTitle: () => {
638
+ }
639
+ });
640
+ var BreadcrumbProvider = ({ children }) => {
641
+ const [breadcrumbTitles, setBreadcrumbTitles] = useState5({});
642
+ const setBreadcrumbTitle = (path, title) => {
643
+ setBreadcrumbTitles((prev) => {
644
+ if (prev[path] === title) return prev;
645
+ return { ...prev, [path]: title };
646
+ });
647
+ };
648
+ return /* @__PURE__ */ jsx7(BreadcrumbContext.Provider, { value: { breadcrumbTitles, setBreadcrumbTitle }, children });
649
+ };
650
+ var useBreadcrumb = () => useContext7(BreadcrumbContext);
651
+
652
+ // src/context/ToastProvider.tsx
653
+ import { createContext as createContext8, useContext as useContext8, useState as useState6, useCallback as useCallback3, useMemo as useMemo4 } from "react";
654
+ import { Snackbar, Alert } from "@mui/material";
655
+ import { jsx as jsx8, jsxs as jsxs2 } from "react/jsx-runtime";
656
+ var ToastContext = createContext8(void 0);
657
+ var ToastProvider = ({ children }) => {
658
+ const [toast, setToast] = useState6(null);
659
+ const showToast = useCallback3((text, type = "info") => {
660
+ setToast({ text, type });
661
+ }, []);
662
+ const hideToast = useCallback3(() => {
663
+ setToast(null);
664
+ }, []);
665
+ const contextValue = useMemo4(() => ({
666
+ showToast,
667
+ hideToast
668
+ }), [showToast, hideToast]);
669
+ return /* @__PURE__ */ jsxs2(ToastContext.Provider, { value: contextValue, children: [
670
+ children,
671
+ /* @__PURE__ */ jsx8(
672
+ Snackbar,
673
+ {
674
+ open: Boolean(toast),
675
+ autoHideDuration: 3500,
676
+ onClose: hideToast,
677
+ anchorOrigin: { vertical: "bottom", horizontal: "center" },
678
+ children: /* @__PURE__ */ jsx8(
679
+ Alert,
680
+ {
681
+ severity: toast?.type || "info",
682
+ variant: "filled",
683
+ onClose: hideToast,
684
+ children: toast?.text
685
+ }
686
+ )
687
+ }
688
+ )
689
+ ] });
690
+ };
691
+ var useToast = () => {
692
+ const context = useContext8(ToastContext);
693
+ if (!context) {
694
+ throw new Error("useToast must be used within a ToastProvider");
695
+ }
696
+ return context;
697
+ };
698
+
699
+ // src/context/ConfirmationProvider.tsx
700
+ import { createContext as createContext10, useContext as useContext10, useState as useState9, useCallback as useCallback4 } from "react";
701
+ import {
702
+ Button as Button2,
703
+ Dialog as Dialog2,
704
+ DialogActions as DialogActions2,
705
+ DialogContent as DialogContent2,
706
+ DialogContentText,
707
+ DialogTitle as DialogTitle2,
708
+ Box as Box3
709
+ } from "@mui/material";
710
+ import {
711
+ Error as ErrorIcon,
712
+ WarningAmberOutlined as WarningIcon,
713
+ InfoOutlined as InfoIcon,
714
+ CheckCircleOutlined as SuccessIcon
715
+ } from "@mui/icons-material";
716
+
717
+ // src/i18n/TranslateText.tsx
718
+ import { useState as useState8, useRef as useRef2, useEffect as useEffect6 } from "react";
719
+ import { useTranslation as useTranslation2 } from "react-i18next";
720
+ import { Box as Box2, Popper, Paper as Paper2, MenuList, MenuItem, ListItemIcon, ListItemText } from "@mui/material";
721
+ import TranslateIcon2 from "@mui/icons-material/Translate";
722
+ import LaunchIcon from "@mui/icons-material/Launch";
723
+
724
+ // src/i18n/TranslationDialog.tsx
725
+ import { useEffect as useEffect5, useState as useState7 } from "react";
726
+ import {
727
+ Dialog,
728
+ DialogTitle,
729
+ DialogContent,
730
+ DialogActions,
731
+ Button,
732
+ TextField,
733
+ Box,
734
+ Typography,
735
+ CircularProgress,
736
+ IconButton,
737
+ Tooltip,
738
+ Paper,
739
+ Alert as Alert2
740
+ } from "@mui/material";
741
+ import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh";
742
+ import TranslateIcon from "@mui/icons-material/Translate";
743
+ import LightbulbIcon from "@mui/icons-material/Lightbulb";
744
+
745
+ // src/services/translation.service.ts
746
+ var translationService = {
747
+ // 1. Принимаем client первым аргументом
748
+ incrementVersion: async (client, namespace, langCodes) => {
749
+ try {
750
+ const { data } = await client.from("translation_versions").select("version, lang_code").eq("namespace", namespace);
751
+ const currentVersion = data && data.length > 0 ? Math.max(...data.map((d) => d.version || 0)) : 0;
752
+ const nextVersion = currentVersion + 1;
753
+ const languagesToUpdate = langCodes && langCodes.length > 0 ? langCodes : ["uk"];
754
+ const updates = languagesToUpdate.map((lang_code) => ({
755
+ namespace,
756
+ lang_code,
757
+ version: nextVersion,
758
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
759
+ }));
760
+ const { error } = await client.from("translation_versions").upsert(updates, { onConflict: "namespace,lang_code" });
761
+ if (error) console.error("Error updating translation version:", error);
762
+ return nextVersion;
763
+ } catch (err) {
764
+ console.error("Failed to increment version in Supabase:", err);
765
+ return null;
766
+ }
767
+ },
768
+ translateSmart: async (client, aiGenerateFn, params) => {
769
+ const languagesToTranslate = params.targetLangs || (params.targetLang ? [params.targetLang] : []);
770
+ try {
771
+ const { data, error } = await client.functions.invoke("translate-smart", { body: params });
772
+ if (!error && data) return data;
773
+ } catch {
774
+ console.warn("Edge Function translate-smart \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C AIProvider...");
775
+ }
776
+ if (aiGenerateFn) {
777
+ const prompt = `Translate the source text into language codes: ${JSON.stringify(languagesToTranslate)}.
778
+ Source Text: "${params.text}"
779
+ ${params.contextHint ? `Context Hint: "${params.contextHint}"` : ""}`;
780
+ const translations = await aiGenerateFn({
781
+ prompt,
782
+ systemInstruction: 'Respond STRICTLY with a valid JSON mapping lang code to text. Example: {"en": "Hello"}',
783
+ jsonMode: true
784
+ });
785
+ if (translations) {
786
+ if (params.targetLang) {
787
+ return { translatedText: translations[params.targetLang] || params.text };
788
+ }
789
+ return { translations };
790
+ }
791
+ }
792
+ if (params.targetLang) {
793
+ const fallbackUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${params.targetLang}&dt=t&q=${encodeURIComponent(params.text)}`;
794
+ const res = await fetch(fallbackUrl);
795
+ if (res.ok) {
796
+ const data = await res.json();
797
+ return { translatedText: data[0].map((x) => x[0]).join("") };
798
+ }
799
+ }
800
+ throw new Error("All translation strategies failed.");
801
+ }
802
+ };
803
+
804
+ // src/context/AIProvider.tsx
805
+ import { createContext as createContext9, useContext as useContext9, useMemo as useMemo5 } from "react";
806
+ import { GoogleGenAI } from "@google/genai";
807
+ import { jsx as jsx9 } from "react/jsx-runtime";
808
+ var AIContext = createContext9(null);
809
+ var AIProvider = ({
810
+ children,
811
+ config,
812
+ apiKey: directApiKey
813
+ }) => {
814
+ const apiKey = directApiKey || config?.apiKey;
815
+ const provider = config?.provider || "gemini";
816
+ const modelName = config?.modelName || (provider === "gemini" ? "gemini-2.5-flash" : "gpt-4o-mini");
817
+ const contextValue = useMemo5(() => {
818
+ return {
819
+ apiKey,
820
+ provider,
821
+ modelName,
822
+ generate: async ({
823
+ prompt,
824
+ systemInstruction,
825
+ jsonMode = false,
826
+ temperature
827
+ }) => {
828
+ if (!apiKey) {
829
+ console.warn("[AIProvider]: API Key \u043D\u0435 \u0437\u0430\u0434\u0430\u043D.");
830
+ return null;
831
+ }
832
+ if (provider === "gemini") {
833
+ try {
834
+ const ai = new GoogleGenAI({ apiKey });
835
+ const response = await ai.models.generateContent({
836
+ model: modelName,
837
+ contents: prompt,
838
+ config: {
839
+ systemInstruction,
840
+ temperature,
841
+ responseMimeType: jsonMode ? "application/json" : "text/plain"
842
+ }
843
+ });
844
+ const rawText = response.text?.trim() || "";
845
+ if (jsonMode) {
846
+ const cleanedText = rawText.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim();
847
+ return JSON.parse(cleanedText);
848
+ }
849
+ return rawText;
850
+ } catch (err) {
851
+ console.error("[AIProvider Gemini Error]:", err);
852
+ return null;
853
+ }
854
+ }
855
+ if (provider === "openai") {
856
+ try {
857
+ const messages = [];
858
+ if (systemInstruction) {
859
+ messages.push({ role: "system", content: systemInstruction });
860
+ }
861
+ messages.push({ role: "user", content: prompt });
862
+ const res = await fetch("https://api.openai.com/v1/chat/completions", {
863
+ method: "POST",
864
+ headers: {
865
+ "Content-Type": "application/json",
866
+ Authorization: `Bearer ${apiKey}`
867
+ },
868
+ body: JSON.stringify({
869
+ model: modelName,
870
+ messages,
871
+ temperature,
872
+ ...jsonMode ? { response_format: { type: "json_object" } } : {}
873
+ })
874
+ });
875
+ const data = await res.json();
876
+ const content = data.choices?.[0]?.message?.content?.trim() || "";
877
+ if (jsonMode) {
878
+ return JSON.parse(content);
879
+ }
880
+ return content;
881
+ } catch (err) {
882
+ console.error("[AIProvider OpenAI Error]:", err);
883
+ return null;
884
+ }
885
+ }
886
+ return null;
887
+ }
888
+ };
889
+ }, [apiKey, provider, modelName]);
890
+ return /* @__PURE__ */ jsx9(AIContext.Provider, { value: contextValue, children });
891
+ };
892
+ var useAI = () => {
893
+ const context = useContext9(AIContext);
894
+ if (!context) {
895
+ throw new Error("useAI \u0434\u043E\u043B\u0436\u0435\u043D \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C\u0441\u044F \u0432\u043D\u0443\u0442\u0440\u0438 <AIProvider>");
896
+ }
897
+ return context;
898
+ };
899
+
900
+ // src/i18n/TranslationDialog.tsx
901
+ import { jsx as jsx10, jsxs as jsxs3 } from "react/jsx-runtime";
902
+ var TranslationDialog = ({
903
+ open,
904
+ onClose,
905
+ translationKey,
906
+ namespace,
907
+ onSave
908
+ }) => {
909
+ const supabase = useSupabase();
910
+ const { generate } = useAI();
911
+ const [languages, setLanguages] = useState7([]);
912
+ const [values, setValues] = useState7({});
913
+ const [contextHint, setContextHint] = useState7("");
914
+ const [loading, setLoading] = useState7(false);
915
+ const [saving, setSaving] = useState7(false);
916
+ const [translatingCode, setTranslatingCode] = useState7(null);
917
+ const [isTranslatingAll, setIsTranslatingAll] = useState7(false);
918
+ const [error, setError] = useState7(null);
919
+ useEffect5(() => {
920
+ if (!open) return;
921
+ const fetchData = async () => {
922
+ setLoading(true);
923
+ setError(null);
924
+ try {
925
+ const { data: langs, error: langErr } = await supabase.from("languages").select("code, name, svg_flag").eq("enabled", true);
926
+ if (langErr) throw langErr;
927
+ setLanguages(langs || []);
928
+ const { data: trans, error: transErr } = await supabase.from("translations").select("lang_code, value, context_hint").eq("namespace", namespace).eq("key", translationKey);
929
+ if (transErr) throw transErr;
930
+ const initialValues = {};
931
+ let existingHint = "";
932
+ langs?.forEach((l) => {
933
+ const found = trans?.find((t) => t.lang_code === l.code);
934
+ initialValues[l.code] = found ? found.value : "";
935
+ if (found?.context_hint) {
936
+ existingHint = found.context_hint;
937
+ }
938
+ });
939
+ setValues(initialValues);
940
+ setContextHint(existingHint);
941
+ } catch (err) {
942
+ console.error("Failed to load translations:", err);
943
+ setError(err?.message || "Failed to load initial translation data.");
944
+ } finally {
945
+ setLoading(false);
946
+ }
947
+ };
948
+ fetchData();
949
+ }, [open, translationKey, namespace]);
950
+ const handleAutoTranslate = async (e, targetLang) => {
951
+ e.preventDefault();
952
+ e.stopPropagation();
953
+ setError(null);
954
+ setTranslatingCode(targetLang);
955
+ try {
956
+ const res = await translationService.translateSmart(supabase, generate, {
957
+ text: translationKey,
958
+ targetLang,
959
+ contextHint
960
+ });
961
+ if (res?.translatedText) {
962
+ setValues((prev) => ({ ...prev, [targetLang]: res.translatedText }));
963
+ }
964
+ } catch (err) {
965
+ console.log(err);
966
+ setError(`Failed to translate into ${targetLang}. ${err?.message || ""}`);
967
+ } finally {
968
+ setTranslatingCode(null);
969
+ }
970
+ };
971
+ const handleTranslateAll = async (e) => {
972
+ e.preventDefault();
973
+ e.stopPropagation();
974
+ if (!translationKey || languages.length === 0) return;
975
+ setIsTranslatingAll(true);
976
+ setError(null);
977
+ try {
978
+ const targetLangs = languages.map((l) => l.code);
979
+ const res = await translationService.translateSmart(supabase, generate, {
980
+ text: translationKey,
981
+ targetLangs,
982
+ contextHint
983
+ });
984
+ if (res?.translations) {
985
+ setValues((prev) => ({ ...prev, ...res.translations }));
986
+ }
987
+ } catch (err) {
988
+ console.error("Batch translation error:", err);
989
+ setError(err?.message || "Failed to translate all languages.");
990
+ } finally {
991
+ setIsTranslatingAll(false);
992
+ }
993
+ };
994
+ const handleSaveAll = async (e) => {
995
+ e.preventDefault();
996
+ e.stopPropagation();
997
+ setSaving(true);
998
+ setError(null);
999
+ try {
1000
+ await onSave(values, contextHint);
1001
+ onClose();
1002
+ } catch (err) {
1003
+ console.error("Failed to save translations:", err);
1004
+ setError(err?.message || "Failed to save translations. Please try again.");
1005
+ } finally {
1006
+ setSaving(false);
1007
+ }
1008
+ };
1009
+ const handleClose = (_, reason) => {
1010
+ if (reason === "backdropClick" && isBusy) return;
1011
+ setError(null);
1012
+ onClose();
1013
+ };
1014
+ const isBusy = loading || saving || isTranslatingAll || translatingCode !== null;
1015
+ return /* @__PURE__ */ jsxs3(
1016
+ Dialog,
1017
+ {
1018
+ open,
1019
+ onClose: handleClose,
1020
+ fullWidth: true,
1021
+ maxWidth: "sm",
1022
+ onClick: (e) => e.stopPropagation(),
1023
+ onMouseDown: (e) => e.stopPropagation(),
1024
+ children: [
1025
+ /* @__PURE__ */ jsxs3(DialogTitle, { sx: { pb: 1, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }, children: [
1026
+ /* @__PURE__ */ jsxs3(Box, { children: [
1027
+ "Context Translation",
1028
+ /* @__PURE__ */ jsxs3(Typography, { component: "div", variant: "subtitle2", color: "text.secondary", sx: { wordBreak: "break-all", mt: 0.5 }, children: [
1029
+ "Original: ",
1030
+ /* @__PURE__ */ jsxs3("strong", { children: [
1031
+ '"',
1032
+ translationKey,
1033
+ '"'
1034
+ ] })
1035
+ ] })
1036
+ ] }),
1037
+ !loading && /* @__PURE__ */ jsx10(
1038
+ Button,
1039
+ {
1040
+ type: "button",
1041
+ size: "small",
1042
+ variant: "outlined",
1043
+ color: "secondary",
1044
+ startIcon: isTranslatingAll ? /* @__PURE__ */ jsx10(CircularProgress, { size: 16, color: "inherit" }) : /* @__PURE__ */ jsx10(TranslateIcon, { fontSize: "small" }),
1045
+ onClick: handleTranslateAll,
1046
+ disabled: isBusy,
1047
+ sx: { flexShrink: 0, ml: 2, whiteSpace: "nowrap" },
1048
+ children: isTranslatingAll ? "Translating..." : "Translate All"
1049
+ }
1050
+ )
1051
+ ] }),
1052
+ /* @__PURE__ */ jsxs3(DialogContent, { dividers: true, sx: { pt: 2 }, children: [
1053
+ error && /* @__PURE__ */ jsx10(Alert2, { severity: "error", onClose: () => setError(null), sx: { mb: 2 }, children: error }),
1054
+ loading ? /* @__PURE__ */ jsx10(Box, { sx: { display: "flex", justifyContent: "center", py: 4 }, children: /* @__PURE__ */ jsx10(CircularProgress, {}) }) : /* @__PURE__ */ jsxs3(Box, { sx: { display: "flex", flexDirection: "column", gap: 2.5 }, children: [
1055
+ /* @__PURE__ */ jsxs3(Paper, { variant: "outlined", sx: { p: 2, bgcolor: "action.hover", borderRadius: 2 }, children: [
1056
+ /* @__PURE__ */ jsxs3(Box, { sx: { display: "flex", alignItems: "center", gap: 1, mb: 1 }, children: [
1057
+ /* @__PURE__ */ jsx10(LightbulbIcon, { color: "warning", fontSize: "small" }),
1058
+ /* @__PURE__ */ jsx10(Typography, { variant: "subtitle2", sx: { fontWeight: 600 }, children: "Context Hint / Clarification" })
1059
+ ] }),
1060
+ /* @__PURE__ */ jsx10(
1061
+ TextField,
1062
+ {
1063
+ fullWidth: true,
1064
+ multiline: true,
1065
+ rows: 2,
1066
+ size: "small",
1067
+ value: contextHint,
1068
+ onChange: (e) => setContextHint(e.target.value),
1069
+ placeholder: "e.g. Website navigation menu link to the home page",
1070
+ helperText: "This hint explains the exact meaning to AI translation models.",
1071
+ disabled: isBusy
1072
+ }
1073
+ )
1074
+ ] }),
1075
+ languages.map((lang) => /* @__PURE__ */ jsxs3(Box, { sx: { display: "flex", alignItems: "center", gap: 2 }, children: [
1076
+ /* @__PURE__ */ jsx10(
1077
+ Box,
1078
+ {
1079
+ sx: {
1080
+ width: 32,
1081
+ height: 22,
1082
+ flexShrink: 0,
1083
+ borderRadius: "4px",
1084
+ overflow: "hidden",
1085
+ boxShadow: 1,
1086
+ "& svg": { width: "100%", height: "100%", display: "block" }
1087
+ },
1088
+ dangerouslySetInnerHTML: { __html: lang.svg_flag }
1089
+ }
1090
+ ),
1091
+ /* @__PURE__ */ jsx10(
1092
+ TextField,
1093
+ {
1094
+ fullWidth: true,
1095
+ label: lang.name,
1096
+ size: "small",
1097
+ value: values[lang.code] || "",
1098
+ onChange: (e) => setValues((prev) => ({ ...prev, [lang.code]: e.target.value })),
1099
+ placeholder: "Enter manual translation...",
1100
+ disabled: isBusy
1101
+ }
1102
+ ),
1103
+ /* @__PURE__ */ jsx10(Tooltip, { title: "Translate with context hint", children: /* @__PURE__ */ jsx10("span", { children: /* @__PURE__ */ jsx10(
1104
+ IconButton,
1105
+ {
1106
+ type: "button",
1107
+ color: "primary",
1108
+ disabled: isBusy,
1109
+ onClick: (e) => handleAutoTranslate(e, lang.code),
1110
+ children: translatingCode === lang.code ? /* @__PURE__ */ jsx10(CircularProgress, { size: 20, color: "inherit" }) : /* @__PURE__ */ jsx10(AutoFixHighIcon, { fontSize: "small" })
1111
+ }
1112
+ ) }) })
1113
+ ] }, lang.code))
1114
+ ] })
1115
+ ] }),
1116
+ /* @__PURE__ */ jsxs3(DialogActions, { sx: { px: 3, py: 2 }, children: [
1117
+ /* @__PURE__ */ jsx10(Button, { onClick: onClose, disabled: isBusy, color: "inherit", type: "button", children: "Cancel" }),
1118
+ /* @__PURE__ */ jsx10(
1119
+ Button,
1120
+ {
1121
+ onClick: handleSaveAll,
1122
+ variant: "contained",
1123
+ disabled: isBusy,
1124
+ type: "button",
1125
+ children: saving ? "Saving..." : "Save All"
1126
+ }
1127
+ )
1128
+ ] })
1129
+ ]
1130
+ }
1131
+ );
1132
+ };
1133
+
1134
+ // src/i18n/TranslateText.tsx
1135
+ import { Fragment, jsx as jsx11, jsxs as jsxs4 } from "react/jsx-runtime";
1136
+ var TranslateText = ({
1137
+ overrideNamespace,
1138
+ children,
1139
+ values
1140
+ }) => {
1141
+ const namespace = useTranslationNamespace(overrideNamespace);
1142
+ const { t, i18n: i18n2 } = useTranslation2(namespace);
1143
+ const { isTranslationMode, canEdit } = useTranslationEdit();
1144
+ const supabase = useSupabase();
1145
+ const [anchorEl, setAnchorEl] = useState8(null);
1146
+ const [isDialogOpen, setIsDialogOpen] = useState8(false);
1147
+ const timeoutRef = useRef2(null);
1148
+ const translatedValue = t(children, values);
1149
+ useEffect6(() => {
1150
+ return () => {
1151
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
1152
+ };
1153
+ }, []);
1154
+ if (!canEdit || !isTranslationMode) {
1155
+ return /* @__PURE__ */ jsx11(Fragment, { children: translatedValue });
1156
+ }
1157
+ const handleSaveTranslations = async (newValues, contextHint) => {
1158
+ const upsertData = Object.entries(newValues).map(([langCode, text]) => ({
1159
+ lang_code: langCode,
1160
+ namespace,
1161
+ key: children,
1162
+ value: text,
1163
+ context_hint: contextHint
1164
+ }));
1165
+ const { error } = await supabase.from("translations").upsert(upsertData, { onConflict: "lang_code,namespace,key" });
1166
+ if (error) {
1167
+ alert("\u041E\u0448\u0438\u0431\u043A\u0430 \u043F\u0440\u0438 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0438 \u0432 \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445");
1168
+ throw error;
1169
+ }
1170
+ await translationService.incrementVersion(supabase, namespace, Object.keys(newValues));
1171
+ Object.entries(newValues).forEach(([langCode, text]) => {
1172
+ i18n2.addResource(langCode, namespace, children, text);
1173
+ });
1174
+ };
1175
+ const handleMouseEnter = (event) => {
1176
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
1177
+ setAnchorEl(event.currentTarget);
1178
+ };
1179
+ const handleMouseLeave = () => {
1180
+ timeoutRef.current = setTimeout(() => {
1181
+ setAnchorEl(null);
1182
+ }, 200);
1183
+ };
1184
+ const handleOpenDialog = (e) => {
1185
+ e.preventDefault();
1186
+ e.stopPropagation();
1187
+ setAnchorEl(null);
1188
+ if (document.activeElement instanceof HTMLElement) {
1189
+ document.activeElement.blur();
1190
+ }
1191
+ setIsDialogOpen(true);
1192
+ };
1193
+ const handleLaunchAction = (_) => {
1194
+ setAnchorEl(null);
1195
+ };
1196
+ const open = Boolean(anchorEl);
1197
+ return /* @__PURE__ */ jsxs4(Fragment, { children: [
1198
+ /* @__PURE__ */ jsx11(
1199
+ Box2,
1200
+ {
1201
+ component: "span",
1202
+ onMouseEnter: handleMouseEnter,
1203
+ onMouseLeave: handleMouseLeave,
1204
+ onClick: (e) => {
1205
+ e.preventDefault();
1206
+ e.stopPropagation();
1207
+ },
1208
+ sx: {
1209
+ display: "inline-block",
1210
+ position: "relative",
1211
+ borderRadius: "4px",
1212
+ padding: "0 3px",
1213
+ margin: "0 1px",
1214
+ border: "1px dashed #f59e0b",
1215
+ backgroundColor: "rgba(254, 243, 199, 0.35)",
1216
+ cursor: "pointer",
1217
+ transition: "all 0.2s ease-in-out",
1218
+ userSelect: "none",
1219
+ "&:hover": {
1220
+ backgroundColor: "#fef08a",
1221
+ borderColor: "#d97706",
1222
+ boxShadow: "0 0 0 2px rgba(245, 158, 11, 0.35)",
1223
+ transform: "scale(1.02)"
1224
+ }
1225
+ },
1226
+ children: translatedValue
1227
+ }
1228
+ ),
1229
+ /* @__PURE__ */ jsx11(
1230
+ Popper,
1231
+ {
1232
+ open,
1233
+ anchorEl,
1234
+ placement: "bottom-start",
1235
+ style: { zIndex: 1300 },
1236
+ children: /* @__PURE__ */ jsx11(
1237
+ Paper2,
1238
+ {
1239
+ elevation: 4,
1240
+ onMouseEnter: () => {
1241
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
1242
+ },
1243
+ onMouseLeave: handleMouseLeave,
1244
+ sx: {
1245
+ mt: 0.5,
1246
+ borderRadius: 2,
1247
+ minWidth: 140,
1248
+ boxShadow: "0px 10px 15px -3px rgba(0,0,0,0.1)"
1249
+ },
1250
+ children: /* @__PURE__ */ jsxs4(MenuList, { dense: true, sx: { py: 0.5 }, children: [
1251
+ /* @__PURE__ */ jsxs4(MenuItem, { onClick: handleOpenDialog, sx: { py: 0.8, px: 1.5 }, children: [
1252
+ /* @__PURE__ */ jsx11(ListItemIcon, { sx: { minWidth: "28px !important" }, children: /* @__PURE__ */ jsx11(TranslateIcon2, { fontSize: "small", sx: { color: "#d97706" } }) }),
1253
+ /* @__PURE__ */ jsx11(
1254
+ ListItemText,
1255
+ {
1256
+ primary: "Localization",
1257
+ slotProps: {
1258
+ primary: {
1259
+ sx: {
1260
+ fontSize: "0.825rem",
1261
+ fontWeight: 600,
1262
+ color: "text.primary"
1263
+ }
1264
+ }
1265
+ }
1266
+ }
1267
+ )
1268
+ ] }),
1269
+ /* @__PURE__ */ jsxs4(MenuItem, { onClick: handleLaunchAction, sx: { py: 0.8, px: 1.5 }, children: [
1270
+ /* @__PURE__ */ jsx11(ListItemIcon, { sx: { minWidth: "28px !important" }, children: /* @__PURE__ */ jsx11(LaunchIcon, { fontSize: "small", color: "secondary" }) }),
1271
+ /* @__PURE__ */ jsx11(
1272
+ ListItemText,
1273
+ {
1274
+ primary: "Launch action",
1275
+ slotProps: {
1276
+ primary: {
1277
+ sx: {
1278
+ fontSize: "0.825rem",
1279
+ fontWeight: 600,
1280
+ color: "text.primary"
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ )
1286
+ ] })
1287
+ ] })
1288
+ }
1289
+ )
1290
+ }
1291
+ ),
1292
+ /* @__PURE__ */ jsx11("span", { style: { display: "inline" }, onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsx11(
1293
+ TranslationDialog,
1294
+ {
1295
+ open: isDialogOpen,
1296
+ onClose: () => setIsDialogOpen(false),
1297
+ translationKey: children,
1298
+ namespace,
1299
+ onSave: handleSaveTranslations
1300
+ }
1301
+ ) })
1302
+ ] });
1303
+ };
1304
+
1305
+ // src/context/ConfirmationProvider.tsx
1306
+ import { jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
1307
+ var ConfirmContext = createContext10(null);
1308
+ var SEVERITY_ICONS = {
1309
+ error: /* @__PURE__ */ jsx12(ErrorIcon, { color: "error", sx: { fontSize: 40 } }),
1310
+ warning: /* @__PURE__ */ jsx12(WarningIcon, { color: "warning", sx: { fontSize: 40 } }),
1311
+ info: /* @__PURE__ */ jsx12(InfoIcon, { color: "info", sx: { fontSize: 40 } }),
1312
+ success: /* @__PURE__ */ jsx12(SuccessIcon, { color: "success", sx: { fontSize: 40 } })
1313
+ };
1314
+ var ConfirmationProvider = ({ children }) => {
1315
+ const [open, setOpen] = useState9(false);
1316
+ const [options, setOptions] = useState9(null);
1317
+ const [resolver, setResolver] = useState9(null);
1318
+ const confirm = useCallback4((opts) => {
1319
+ setOptions(opts);
1320
+ setOpen(true);
1321
+ return new Promise((resolve) => {
1322
+ setResolver(() => resolve);
1323
+ });
1324
+ }, []);
1325
+ const handleClose = (result) => {
1326
+ setOpen(false);
1327
+ if (resolver) {
1328
+ resolver(result);
1329
+ }
1330
+ };
1331
+ const severityType = options?.type || "info";
1332
+ return /* @__PURE__ */ jsxs5(ConfirmContext.Provider, { value: { confirm }, children: [
1333
+ children,
1334
+ /* @__PURE__ */ jsxs5(
1335
+ Dialog2,
1336
+ {
1337
+ open,
1338
+ onClose: () => handleClose("cancel"),
1339
+ maxWidth: "xs",
1340
+ fullWidth: true,
1341
+ disableEnforceFocus: true,
1342
+ disableRestoreFocus: true,
1343
+ children: [
1344
+ /* @__PURE__ */ jsxs5(DialogTitle2, { sx: { display: "flex", alignItems: "center", gap: 1.5, pb: 1 }, children: [
1345
+ SEVERITY_ICONS[severityType],
1346
+ /* @__PURE__ */ jsx12(Box3, { component: "span", sx: { fontWeight: 600 }, children: options?.title || /* @__PURE__ */ jsx12(TranslateText, { children: "Confirmation" }) })
1347
+ ] }),
1348
+ /* @__PURE__ */ jsx12(DialogContent2, { sx: { py: 2 }, dividers: true, children: /* @__PURE__ */ jsx12(DialogContentText, { color: "text.secondary", children: options?.message }) }),
1349
+ /* @__PURE__ */ jsxs5(DialogActions2, { sx: { pt: 2, px: 2, justifyContent: "flex-end", gap: 1 }, children: [
1350
+ (options?.showCancelButton ?? true) && /* @__PURE__ */ jsx12(
1351
+ Button2,
1352
+ {
1353
+ onClick: () => handleClose("cancel"),
1354
+ color: "inherit",
1355
+ variant: "text",
1356
+ children: options?.cancelText || /* @__PURE__ */ jsx12(TranslateText, { children: "Cancel" })
1357
+ }
1358
+ ),
1359
+ options?.showNoButton && /* @__PURE__ */ jsx12(
1360
+ Button2,
1361
+ {
1362
+ onClick: () => handleClose("no"),
1363
+ color: "inherit",
1364
+ variant: "outlined",
1365
+ children: options?.noText || /* @__PURE__ */ jsx12(TranslateText, { children: "No" })
1366
+ }
1367
+ ),
1368
+ /* @__PURE__ */ jsx12(
1369
+ Button2,
1370
+ {
1371
+ onClick: () => handleClose("yes"),
1372
+ color: options?.confirmColor || (severityType === "error" ? "error" : "primary"),
1373
+ variant: "contained",
1374
+ autoFocus: true,
1375
+ children: options?.confirmText || /* @__PURE__ */ jsx12(TranslateText, { children: "Yes" })
1376
+ }
1377
+ )
1378
+ ] })
1379
+ ]
1380
+ }
1381
+ )
1382
+ ] });
1383
+ };
1384
+ var useConfirmation = () => {
1385
+ const context = useContext10(ConfirmContext);
1386
+ if (!context) {
1387
+ throw new Error("useConfirm must be used within a ConfirmProvider");
1388
+ }
1389
+ return context.confirm;
1390
+ };
1391
+
1392
+ // src/context/index.ts
1393
+ var Providers = {
1394
+ Supabase: SupabaseProvider,
1395
+ Translate: TranslateProvider,
1396
+ TranslationEdit: TranslationEditProvider,
1397
+ Localization: LocalizationProvider,
1398
+ Theme: ThemeProvider,
1399
+ Breadcrumb: BreadcrumbProvider,
1400
+ Toast: ToastProvider,
1401
+ Confirmation: ConfirmationProvider,
1402
+ AI: AIProvider
1403
+ };
1404
+
1405
+ // src/UI/components/data.display/UserStatusChipComponent.tsx
1406
+ import { jsx as jsx13 } from "react/jsx-runtime";
1407
+ var UserStatusChipComponent = ({ overrideNamespace, state }) => {
1408
+ const confirm = useConfirmation();
1409
+ const handleShowReason = async (e) => {
1410
+ e.stopPropagation();
1411
+ if (!state.locked_reason) return;
1412
+ await confirm({
1413
+ title: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Lock Reason" }),
1414
+ message: state.locked_reason,
1415
+ type: "info",
1416
+ confirmText: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "OK" }),
1417
+ showNoButton: false,
1418
+ showCancelButton: false
1419
+ });
1420
+ };
1421
+ if (state.profile_archived) {
1422
+ return /* @__PURE__ */ jsx13(
1423
+ Chip,
1424
+ {
1425
+ label: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Archived" }),
1426
+ color: "default",
1427
+ size: "small",
1428
+ variant: "filled"
1429
+ }
1430
+ );
1431
+ }
1432
+ if (state.profile_locked) {
1433
+ return /* @__PURE__ */ jsx13(
1434
+ Chip,
1435
+ {
1436
+ label: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "System Locked" }),
1437
+ color: "error",
1438
+ size: "small",
1439
+ variant: "filled"
1440
+ }
1441
+ );
1442
+ }
1443
+ if (state.excluded) {
1444
+ return /* @__PURE__ */ jsx13(
1445
+ Chip,
1446
+ {
1447
+ label: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Excluded" }),
1448
+ size: "small"
1449
+ }
1450
+ );
1451
+ }
1452
+ if (state.locked) {
1453
+ return /* @__PURE__ */ jsx13(
1454
+ Chip,
1455
+ {
1456
+ label: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Locked" }),
1457
+ color: "error",
1458
+ size: "small",
1459
+ onDelete: state.locked_reason ? handleShowReason : void 0,
1460
+ deleteIcon: state.locked_reason ? /* @__PURE__ */ jsx13(IconButton2, { size: "small", component: "span", sx: { p: 0.2 }, children: /* @__PURE__ */ jsx13(InfoOutlinedIcon, { fontSize: "small" }) }) : void 0
1461
+ }
1462
+ );
1463
+ }
1464
+ return /* @__PURE__ */ jsx13(
1465
+ Chip,
1466
+ {
1467
+ label: /* @__PURE__ */ jsx13(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Active" }),
1468
+ color: "success",
1469
+ size: "small",
1470
+ variant: "outlined"
1471
+ }
1472
+ );
1473
+ };
1474
+
1475
+ // src/UI/components/data.display/UserRoleChipComponent.tsx
1476
+ import { Chip as Chip2 } from "@mui/material";
1477
+ import { jsx as jsx14 } from "react/jsx-runtime";
1478
+ var UserRoleChipComponent = ({ overrideNamespace, role }) => {
1479
+ switch (role) {
1480
+ case "superadmin":
1481
+ return /* @__PURE__ */ jsx14(
1482
+ Chip2,
1483
+ {
1484
+ label: /* @__PURE__ */ jsx14(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Superadministrator" }),
1485
+ color: "error",
1486
+ size: "small"
1487
+ }
1488
+ );
1489
+ case "admin":
1490
+ return /* @__PURE__ */ jsx14(
1491
+ Chip2,
1492
+ {
1493
+ label: /* @__PURE__ */ jsx14(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "Administrator" }),
1494
+ color: "primary",
1495
+ size: "small"
1496
+ }
1497
+ );
1498
+ default:
1499
+ return /* @__PURE__ */ jsx14(
1500
+ Chip2,
1501
+ {
1502
+ label: /* @__PURE__ */ jsx14(TranslateText, { overrideNamespace: overrideNamespace || "system_widgets", children: "User" }),
1503
+ variant: "outlined",
1504
+ size: "small"
1505
+ }
1506
+ );
1507
+ }
1508
+ };
1509
+
1510
+ // src/UI/components/buttons/CopyClipboardButtonComponent.tsx
1511
+ import { useState as useState10 } from "react";
1512
+ import { IconButton as IconButton3 } from "@mui/material";
1513
+ import CheckIcon from "@mui/icons-material/Check";
1514
+ import CopyIcon from "@mui/icons-material/ContentCopy";
1515
+
1516
+ // src/UI/components/data.display/TranslatableTooltipComponent.tsx
1517
+ import { Tooltip as Tooltip2 } from "@mui/material";
1518
+ import { jsx as jsx15 } from "react/jsx-runtime";
1519
+ var TranslatableTooltipComponent = ({
1520
+ overrideNamespace,
1521
+ title,
1522
+ disableSpan,
1523
+ children,
1524
+ ...props
1525
+ }) => {
1526
+ const { isTranslationMode } = useTranslationEdit();
1527
+ return /* @__PURE__ */ jsx15(
1528
+ Tooltip2,
1529
+ {
1530
+ title: typeof title === "string" ? /* @__PURE__ */ jsx15(TranslateText, { overrideNamespace, children: title }) : title,
1531
+ slotProps: {
1532
+ popper: {
1533
+ sx: isTranslationMode ? {
1534
+ pointerEvents: "auto",
1535
+ // Разрешаем клики внутри тултипа
1536
+ "& .MuiTooltip-tooltip": {
1537
+ pointerEvents: "auto"
1538
+ }
1539
+ } : void 0
1540
+ }
1541
+ },
1542
+ leaveDelay: isTranslationMode ? 1e3 : 100,
1543
+ ...props,
1544
+ children: disableSpan ? children : /* @__PURE__ */ jsx15("span", { children })
1545
+ }
1546
+ );
1547
+ };
1548
+
1549
+ // src/UI/components/buttons/CopyClipboardButtonComponent.tsx
1550
+ import { jsx as jsx16 } from "react/jsx-runtime";
1551
+ var CopyClipboardButtonComponent = ({
1552
+ overrideNamespace,
1553
+ textToCopy,
1554
+ copyTooltipText = "Copy",
1555
+ copiedTooltipText = "Copied",
1556
+ namespace = "form_components",
1557
+ resetDelay = 2e3,
1558
+ onCopySuccess,
1559
+ size = "small",
1560
+ sx,
1561
+ ...iconButtonProps
1562
+ }) => {
1563
+ const [copied, setCopied] = useState10(false);
1564
+ const handleCopy = async (e) => {
1565
+ e.stopPropagation();
1566
+ if (!textToCopy) return;
1567
+ try {
1568
+ await navigator.clipboard.writeText(textToCopy);
1569
+ setCopied(true);
1570
+ if (onCopySuccess) {
1571
+ onCopySuccess(textToCopy);
1572
+ }
1573
+ setTimeout(() => {
1574
+ setCopied(false);
1575
+ }, resetDelay);
1576
+ } catch (error) {
1577
+ console.error("Failed to copy text to clipboard:", error);
1578
+ }
1579
+ };
1580
+ return /* @__PURE__ */ jsx16(TranslatableTooltipComponent, { title: copied ? copiedTooltipText : copyTooltipText, children: /* @__PURE__ */ jsx16("span", { children: /* @__PURE__ */ jsx16(
1581
+ IconButton3,
1582
+ {
1583
+ size,
1584
+ onClick: handleCopy,
1585
+ disabled: !textToCopy || iconButtonProps.disabled,
1586
+ sx: { p: 0.25, ...sx },
1587
+ ...iconButtonProps,
1588
+ children: copied ? /* @__PURE__ */ jsx16(CheckIcon, { fontSize: size === "large" ? "medium" : "small", color: "success" }) : /* @__PURE__ */ jsx16(CopyIcon, { fontSize: size === "large" ? "medium" : "small" })
1589
+ }
1590
+ ) }) });
1591
+ };
1592
+
1593
+ // src/context/UserSettingsProvider.tsx
1594
+ import { createContext as createContext11, useContext as useContext11, useEffect as useEffect7, useState as useState11, useCallback as useCallback5 } from "react";
1595
+ import { jsx as jsx17 } from "react/jsx-runtime";
1596
+ var UserSettingsContext = createContext11(void 0);
1597
+ var useUserSettings = () => {
1598
+ const context = useContext11(UserSettingsContext);
1599
+ if (!context) {
1600
+ throw new Error("useUserSettings should be used within the UserSettingsProvider");
1601
+ }
1602
+ return context;
1603
+ };
1604
+
1605
+ // src/UI/components/data.display/UserPopoverComponent.tsx
1606
+ import { Fragment as Fragment2, jsx as jsx18, jsxs as jsxs6 } from "react/jsx-runtime";
1607
+ var useUserStatus = (supabase, userId, open) => {
1608
+ const [lastSeenAt, setLastSeenAt] = useState12(null);
1609
+ const [loading, setLoading] = useState12(true);
1610
+ useEffect8(() => {
1611
+ if (!userId || !open) {
1612
+ setLastSeenAt(null);
1613
+ setLoading(false);
1614
+ return;
1615
+ }
1616
+ let isMounted = true;
1617
+ const loadStatus = async () => {
1618
+ setLoading(true);
1619
+ const date = await getUserLastSeenAt(supabase, userId);
1620
+ if (isMounted) {
1621
+ setLastSeenAt(date);
1622
+ setLoading(false);
1623
+ }
1624
+ };
1625
+ loadStatus();
1626
+ const channel = supabase.channel(`user_status_popover_${userId}`).on(
1627
+ "postgres_changes",
1628
+ {
1629
+ event: "*",
1630
+ schema: "public",
1631
+ table: "user_sessions",
1632
+ filter: `user_id=eq.${userId}`
1633
+ },
1634
+ () => {
1635
+ loadStatus();
1636
+ }
1637
+ ).subscribe();
1638
+ return () => {
1639
+ isMounted = false;
1640
+ supabase.removeChannel(channel);
1641
+ };
1642
+ }, [userId, open]);
1643
+ const isOnline = Boolean(
1644
+ lastSeenAt && (/* @__PURE__ */ new Date()).getTime() - new Date(lastSeenAt).getTime() < 3 * 60 * 1e3
1645
+ );
1646
+ return { lastSeenAt, isOnline, loading };
1647
+ };
1648
+ var UserPopoverComponent = ({
1649
+ overrideNamespace,
1650
+ userId,
1651
+ anchorEl,
1652
+ open,
1653
+ onClose
1654
+ }) => {
1655
+ const supabase = useSupabase();
1656
+ const { activeCompanyId, membership: currentMembership } = useAuth();
1657
+ const { openChatWithUser } = useUserSettings();
1658
+ const { formatDate, formatRelativeTime } = useLocalization();
1659
+ const [profileData, setProfileData] = useState12(null);
1660
+ const [membershipData, setMembershipData] = useState12(null);
1661
+ const [avatarUrl, setAvatarUrl] = useState12(null);
1662
+ const [coverUrl, setCoverUrl] = useState12(null);
1663
+ const [loading, setLoading] = useState12(true);
1664
+ const { lastSeenAt, isOnline } = useUserStatus(supabase, userId, open);
1665
+ useEffect8(() => {
1666
+ if (!open || !userId || !activeCompanyId) return;
1667
+ let isMounted = true;
1668
+ setLoading(true);
1669
+ const fetchUserData = async () => {
1670
+ try {
1671
+ const { data, error } = await supabase.rpc("get_user_avatar_and_profile", {
1672
+ p_company_id: activeCompanyId,
1673
+ //currentMembership?.id || null,
1674
+ p_user_id: userId
1675
+ }).maybeSingle();
1676
+ if (error) throw error;
1677
+ if (isMounted && data) {
1678
+ const rpcData = data;
1679
+ const profile = rpcData.profile;
1680
+ const membership = rpcData.membership;
1681
+ setProfileData(profile);
1682
+ setMembershipData(membership);
1683
+ const avatarPath = profile?.avatar_path || profile?.avatar_url;
1684
+ if (avatarPath && !avatarPath.startsWith("http")) {
1685
+ const { data: avatarSigned } = await supabase.storage.from("user-media").createSignedUrl(avatarPath, 3600);
1686
+ if (isMounted) setAvatarUrl(avatarSigned?.signedUrl || null);
1687
+ } else {
1688
+ if (isMounted) setAvatarUrl(avatarPath || null);
1689
+ }
1690
+ const coverPath = profile?.cover_image_path || profile?.cover_image_url;
1691
+ if (coverPath && !coverPath.startsWith("http")) {
1692
+ const { data: coverSigned } = await supabase.storage.from("user-media").createSignedUrl(coverPath, 3600);
1693
+ if (isMounted) setCoverUrl(coverSigned?.signedUrl || null);
1694
+ } else {
1695
+ if (isMounted) setCoverUrl(coverPath || null);
1696
+ }
1697
+ }
1698
+ } catch (err) {
1699
+ console.error("Error loading user popover data:", err);
1700
+ } finally {
1701
+ if (isMounted) setLoading(false);
1702
+ }
1703
+ };
1704
+ fetchUserData();
1705
+ return () => {
1706
+ isMounted = false;
1707
+ };
1708
+ }, [open, userId, currentMembership?.id, activeCompanyId]);
1709
+ const getStatusChip = () => {
1710
+ if (!profileData) return null;
1711
+ return /* @__PURE__ */ jsx18(UserStatusChipComponent, { state: { profile_archived: profileData.archived, profile_locked: profileData.locked, excluded: membershipData?.excluded || false, locked: membershipData?.locked || false, locked_reason: membershipData?.locked_reason || "" } });
1712
+ };
1713
+ const getStatusTypographyColor = (isOnline2, lastSeenAt2) => {
1714
+ if (isOnline2) return "success";
1715
+ if (!lastSeenAt2) return "textSecondary";
1716
+ const diffInMinutes = (Date.now() - new Date(lastSeenAt2).getTime()) / (1e3 * 60);
1717
+ if (diffInMinutes <= 15) {
1718
+ return "warning";
1719
+ }
1720
+ return "textSecondary";
1721
+ };
1722
+ const getStatusIconColor = (isOnline2, lastSeenAt2) => {
1723
+ if (isOnline2) return "success";
1724
+ if (!lastSeenAt2) return "inherit";
1725
+ const diffInMinutes = (Date.now() - new Date(lastSeenAt2).getTime()) / (1e3 * 60);
1726
+ if (diffInMinutes <= 15) {
1727
+ return "warning";
1728
+ }
1729
+ return "inherit";
1730
+ };
1731
+ const canChat = currentMembership && membershipData && currentMembership.id !== membershipData.id;
1732
+ return /* @__PURE__ */ jsx18(
1733
+ Popover,
1734
+ {
1735
+ open,
1736
+ anchorEl,
1737
+ onClose,
1738
+ anchorOrigin: { vertical: "bottom", horizontal: "left" },
1739
+ transformOrigin: { vertical: "top", horizontal: "left" },
1740
+ slotProps: {
1741
+ paper: {
1742
+ sx: {
1743
+ width: 350,
1744
+ p: 0,
1745
+ overflow: "hidden",
1746
+ borderRadius: 0,
1747
+ boxShadow: 4
1748
+ }
1749
+ }
1750
+ },
1751
+ children: loading ? /* @__PURE__ */ jsx18(Box4, { sx: { display: "flex", justifyContent: "center", py: 4 }, children: /* @__PURE__ */ jsx18(CircularProgress2, { size: 28 }) }) : profileData ? /* @__PURE__ */ jsxs6(Box4, { sx: { display: "flex", flexDirection: "column" }, children: [
1752
+ /* @__PURE__ */ jsxs6(
1753
+ Box4,
1754
+ {
1755
+ sx: {
1756
+ position: "relative",
1757
+ width: "100%",
1758
+ height: 96,
1759
+ bgcolor: "action.selected"
1760
+ },
1761
+ children: [
1762
+ coverUrl && /* @__PURE__ */ jsx18(
1763
+ Box4,
1764
+ {
1765
+ component: "img",
1766
+ src: coverUrl,
1767
+ alt: "Profile background",
1768
+ sx: {
1769
+ width: "100%",
1770
+ height: "100%",
1771
+ objectFit: "cover",
1772
+ display: "block",
1773
+ m: 0,
1774
+ p: 0
1775
+ }
1776
+ }
1777
+ ),
1778
+ /* @__PURE__ */ jsx18(
1779
+ IconButton4,
1780
+ {
1781
+ size: "small",
1782
+ onClick: onClose,
1783
+ sx: {
1784
+ position: "absolute",
1785
+ top: 8,
1786
+ right: 8,
1787
+ color: "common.white",
1788
+ bgcolor: "rgba(0, 0, 0, 0.4)",
1789
+ backdropFilter: "blur(4px)",
1790
+ transition: "all 0.2s ease",
1791
+ "&:hover": {
1792
+ bgcolor: "rgba(0, 0, 0, 0.8)",
1793
+ transform: "scale(1.1)"
1794
+ }
1795
+ },
1796
+ children: /* @__PURE__ */ jsx18(CloseIcon, { fontSize: "small" })
1797
+ }
1798
+ )
1799
+ ]
1800
+ }
1801
+ ),
1802
+ /* @__PURE__ */ jsxs6(Box4, { sx: { p: 2, pt: 0 }, children: [
1803
+ /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1.5, sx: { alignItems: "flex-end", mt: "-18px", mb: 1 }, children: [
1804
+ /* @__PURE__ */ jsx18(
1805
+ Badge,
1806
+ {
1807
+ overlap: "circular",
1808
+ anchorOrigin: { vertical: "bottom", horizontal: "right" },
1809
+ variant: "dot",
1810
+ sx: {
1811
+ "& .MuiBadge-badge": {
1812
+ backgroundColor: isOnline ? "#44b700" : "#bdbdbd",
1813
+ color: isOnline ? "#44b700" : "#bdbdbd",
1814
+ boxShadow: `0 0 0 2px #fff`,
1815
+ width: 12,
1816
+ height: 12,
1817
+ borderRadius: "50%",
1818
+ "&::after": isOnline ? {
1819
+ position: "absolute",
1820
+ top: 0,
1821
+ left: 0,
1822
+ width: "100%",
1823
+ height: "100%",
1824
+ borderRadius: "50%",
1825
+ animation: "ripple 1.2s infinite ease-in-out",
1826
+ border: "1px solid currentColor",
1827
+ content: '""'
1828
+ } : {}
1829
+ },
1830
+ "@keyframes ripple": {
1831
+ "0%": {
1832
+ transform: "scale(.8)",
1833
+ opacity: 1
1834
+ },
1835
+ "100%": {
1836
+ transform: "scale(2.4)",
1837
+ opacity: 0
1838
+ }
1839
+ }
1840
+ },
1841
+ children: /* @__PURE__ */ jsx18(
1842
+ Avatar,
1843
+ {
1844
+ src: avatarUrl || coverUrl || void 0,
1845
+ sx: {
1846
+ width: 65,
1847
+ height: 65,
1848
+ border: "3px solid",
1849
+ borderColor: "background.paper",
1850
+ boxShadow: 2,
1851
+ bgcolor: "primary.main",
1852
+ fontSize: 22,
1853
+ fontWeight: 600
1854
+ },
1855
+ children: profileData.display_name?.[0]?.toUpperCase() || "?"
1856
+ }
1857
+ )
1858
+ }
1859
+ ),
1860
+ /* @__PURE__ */ jsxs6(Box4, { sx: { overflow: "hidden", pb: 0.5 }, children: [
1861
+ /* @__PURE__ */ jsx18(Typography2, { variant: "subtitle1", sx: { fontWeight: 600, lineHeight: 1.2 }, noWrap: true, children: profileData.display_name || `${profileData.first_name || ""} ${profileData.last_name || ""}` }),
1862
+ membershipData?.employee_post && /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: "text.secondary", noWrap: true, children: membershipData.employee_post })
1863
+ ] })
1864
+ ] }),
1865
+ /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { my: 1, flexWrap: "wrap", gap: 0.5 }, children: [
1866
+ getStatusChip(),
1867
+ /* @__PURE__ */ jsx18(UserRoleChipComponent, { role: membershipData?.role || "user" })
1868
+ ] }),
1869
+ /* @__PURE__ */ jsx18(Divider, { sx: { my: 1.5 } }),
1870
+ /* @__PURE__ */ jsxs6(Stack, { spacing: 1, sx: { fontSize: "0.875rem", mb: 1.5 }, children: [
1871
+ /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1872
+ /* @__PURE__ */ jsx18(AccessTimeIcon, { fontSize: "small", color: getStatusIconColor(isOnline, lastSeenAt) }),
1873
+ /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: getStatusTypographyColor(isOnline, lastSeenAt), children: isOnline ? /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Online" }) : lastSeenAt ? /* @__PURE__ */ jsxs6(Fragment2, { children: [
1874
+ /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Last seen" }),
1875
+ ":",
1876
+ " ",
1877
+ /* @__PURE__ */ jsx18("strong", { children: formatRelativeTime(lastSeenAt) })
1878
+ ] }) : /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Offline" }) })
1879
+ ] }),
1880
+ profileData.email && /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1881
+ /* @__PURE__ */ jsx18(EmailIcon, { fontSize: "small" }),
1882
+ /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: "text.primary", noWrap: true, sx: { flexGrow: 1 }, children: profileData.email }),
1883
+ /* @__PURE__ */ jsx18(CopyClipboardButtonComponent, { textToCopy: profileData.email })
1884
+ ] }),
1885
+ membershipData?.employee_post && /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1886
+ /* @__PURE__ */ jsx18(WorkIcon, { fontSize: "small" }),
1887
+ /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: "text.primary", noWrap: true, sx: { flexGrow: 1 }, children: membershipData.employee_post }),
1888
+ /* @__PURE__ */ jsx18(CopyClipboardButtonComponent, { textToCopy: membershipData.employee_post })
1889
+ ] }),
1890
+ profileData.phone && /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1891
+ /* @__PURE__ */ jsx18(PhoneIcon, { fontSize: "small" }),
1892
+ /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: "text.primary", children: profileData.phone })
1893
+ ] }),
1894
+ profileData.birthday && /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1895
+ /* @__PURE__ */ jsx18(CakeIcon, { fontSize: "small" }),
1896
+ /* @__PURE__ */ jsx18(Typography2, { variant: "body2", color: "text.primary", children: formatDate(profileData.birthday) })
1897
+ ] }),
1898
+ membershipData?.created_at && /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { alignItems: "center" }, color: "text.secondary", children: [
1899
+ /* @__PURE__ */ jsx18(CalendarIcon, { fontSize: "small" }),
1900
+ /* @__PURE__ */ jsxs6(Typography2, { variant: "body2", color: "text.primary", children: [
1901
+ /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "In company from" }),
1902
+ ": ",
1903
+ formatDate(membershipData.created_at)
1904
+ ] })
1905
+ ] }),
1906
+ profileData.description && /* @__PURE__ */ jsx18(
1907
+ Typography2,
1908
+ {
1909
+ variant: "caption",
1910
+ color: "text.secondary",
1911
+ sx: {
1912
+ display: "-webkit-box",
1913
+ WebkitLineClamp: 2,
1914
+ WebkitBoxOrient: "vertical",
1915
+ overflow: "hidden",
1916
+ mt: 0.5
1917
+ },
1918
+ children: profileData.description
1919
+ }
1920
+ )
1921
+ ] }),
1922
+ /* @__PURE__ */ jsx18(Divider, { sx: { my: 1 } }),
1923
+ /* @__PURE__ */ jsxs6(Stack, { direction: "row", spacing: 1, sx: { justifyContent: "space-around", pt: 0.5 }, children: [
1924
+ /* @__PURE__ */ jsx18(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Send a notification" }), children: /* @__PURE__ */ jsx18(IconButton4, { size: "small", color: "primary", children: /* @__PURE__ */ jsx18(NotificationIcon, { fontSize: "small" }) }) }),
1925
+ /* @__PURE__ */ jsx18(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Set a task" }), children: /* @__PURE__ */ jsx18(IconButton4, { size: "small", color: "primary", children: /* @__PURE__ */ jsx18(TaskIcon, { fontSize: "small" }) }) }),
1926
+ /* @__PURE__ */ jsx18(TranslatableTooltipComponent, { title: /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Start a chat" }), children: /* @__PURE__ */ jsx18(
1927
+ IconButton4,
1928
+ {
1929
+ size: "small",
1930
+ color: "primary",
1931
+ disabled: !canChat,
1932
+ onClick: () => membershipData && openChatWithUser(membershipData.id),
1933
+ children: /* @__PURE__ */ jsx18(ChatIcon, { fontSize: "small" })
1934
+ }
1935
+ ) })
1936
+ ] })
1937
+ ] })
1938
+ ] }) : /* @__PURE__ */ jsx18(Box4, { sx: { p: 2 }, children: /* @__PURE__ */ jsx18(
1939
+ Typography2,
1940
+ {
1941
+ color: "error",
1942
+ variant: "body2",
1943
+ children: /* @__PURE__ */ jsx18(TranslateText, { overrideNamespace: overrideNamespace || "form_components", children: "Failed to load user data" })
1944
+ }
1945
+ ) })
1946
+ }
1947
+ );
1948
+ };
1949
+ var UserPopoverComponent_default = UserPopoverComponent;
1950
+
1951
+ export {
1952
+ SupabaseProvider,
1953
+ useSupabase,
1954
+ TranslationEditProvider,
1955
+ useTranslationEdit,
1956
+ translationService,
1957
+ AIProvider,
1958
+ useAI,
1959
+ TranslationDialog,
1960
+ TranslateProvider,
1961
+ useTranslationNamespace,
1962
+ TranslateText,
1963
+ TranslatableTooltipComponent,
1964
+ LocalizationProvider,
1965
+ useLocalization,
1966
+ ThemeProvider,
1967
+ useAppTheme,
1968
+ BreadcrumbProvider,
1969
+ useBreadcrumb,
1970
+ ToastProvider,
1971
+ useToast,
1972
+ ConfirmationProvider,
1973
+ useConfirmation,
1974
+ Providers,
1975
+ UserStatusChipComponent,
1976
+ UserRoleChipComponent,
1977
+ CopyClipboardButtonComponent,
1978
+ UserPopoverComponent,
1979
+ UserPopoverComponent_default
1980
+ };